id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
15,200
0008_allow_blank_directory_name_and_parent.py
translate_pootle/pootle/apps/pootle_app/migrations/0008_allow_blank_directory_name_and_parent.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import pootle_app.models.directory class Migration(migrations.Migration): dependencies = [ ('pootle_app', '0007_add_directory_name_validation'), ] operations = [ migrations.AlterField( model_name='directory', name='name', field=models.CharField(blank=True, max_length=255, validators=[pootle_app.models.directory.validate_no_slashes]), ), migrations.AlterField( model_name='directory', name='parent', field=models.ForeignKey(related_name='child_dirs', blank=True, to='pootle_app.Directory', null=True, on_delete=models.CASCADE), ), ]
772
Python
.py
20
30.95
139
0.647925
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,201
0010_obsolete_path_idx.py
translate_pootle/pootle/apps/pootle_app/migrations/0010_obsolete_path_idx.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.10 on 2016-10-23 18:15 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pootle_app', '0009_set_default_directory_pootle_path'), ] operations = [ migrations.AlterIndexTogether( name='directory', index_together=set([('obsolete', 'pootle_path')]), ), ]
451
Python
.py
14
26.285714
65
0.638889
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,202
0015_add_tp_path_idx.py
translate_pootle/pootle/apps/pootle_app/migrations/0015_add_tp_path_idx.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.11 on 2016-11-04 16:36 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pootle_app', '0014_set_directory_tp_path'), ] operations = [ migrations.AlterIndexTogether( name='directory', index_together=set([('obsolete', 'tp', 'tp_path'), ('obsolete', 'pootle_path')]), ), ]
470
Python
.py
14
27.642857
93
0.62306
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,203
0009_set_default_directory_pootle_path.py
translate_pootle/pootle/apps/pootle_app/migrations/0009_set_default_directory_pootle_path.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pootle_app', '0008_allow_blank_directory_name_and_parent'), ] operations = [ migrations.AlterField( model_name='directory', name='pootle_path', field=models.CharField(default='/', unique=True, max_length=255, db_index=True), ), ]
474
Python
.py
14
27.071429
92
0.630769
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,204
0004_set_directory_has_no_default_permissions.py
translate_pootle/pootle/apps/pootle_app/migrations/0004_set_directory_has_no_default_permissions.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pootle_app', '0003_drop_existing_directory_default_permissions'), ] operations = [ migrations.AlterModelOptions( name='directory', options={'ordering': ['name'], 'default_permissions': ()}, ), ]
427
Python
.py
13
26.538462
75
0.633252
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,205
0001_initial.py
translate_pootle/pootle/apps/pootle_app/migrations/0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import pootle.core.mixins.treeitem from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Directory', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=255)), ('pootle_path', models.CharField(unique=True, max_length=255, db_index=True)), ('obsolete', models.BooleanField(default=False)), ('parent', models.ForeignKey(related_name='child_dirs', to='pootle_app.Directory', null=True, on_delete=models.CASCADE)), ], options={ 'ordering': ['name'], }, bases=(models.Model, pootle.core.mixins.treeitem.CachedTreeItem), ), migrations.CreateModel( name='PermissionSet', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('directory', models.ForeignKey(related_name='permission_sets', to='pootle_app.Directory', on_delete=models.CASCADE)), ('negative_permissions', models.ManyToManyField(related_name='permission_sets_negative', to='auth.Permission', db_index=True)), ('positive_permissions', models.ManyToManyField(related_name='permission_sets_positive', to='auth.Permission', db_index=True)), ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)), ], options={ }, bases=(models.Model,), ), migrations.AlterUniqueTogether( name='permissionset', unique_together=set([('user', 'directory')]), ), ]
2,072
Python
.py
43
37.209302
143
0.606719
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,206
0019_remove_extra_indeces.py
translate_pootle/pootle/apps/pootle_app/migrations/0019_remove_extra_indeces.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-06-02 16:53 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('pootle_app', '0018_set_directory_base_manager_name'), ] operations = [ migrations.AlterField( model_name='permissionset', name='user', field=models.ForeignKey(db_index=False, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ]
614
Python
.py
17
30.352941
126
0.682432
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,207
0007_add_directory_name_validation.py
translate_pootle/pootle/apps/pootle_app/migrations/0007_add_directory_name_validation.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import pootle_app.models.directory class Migration(migrations.Migration): dependencies = [ ('pootle_app', '0006_change_administrate_permission_name'), ] operations = [ migrations.AlterField( model_name='directory', name='name', field=models.CharField(max_length=255, validators=[pootle_app.models.directory.validate_no_slashes]), ), ]
521
Python
.py
15
28.333333
113
0.666667
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,208
0017_drop_stray_directories.py
translate_pootle/pootle/apps/pootle_app/migrations/0017_drop_stray_directories.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.11 on 2016-11-08 17:23 from __future__ import unicode_literals from django.db import migrations def drop_stray_directories(apps, schema_editor): """Drop directories that belong to no existing TP.""" Directory = apps.get_model("pootle_app.Directory") TP = apps.get_model("pootle_translationproject.TranslationProject") Language = apps.get_model("pootle_language.Language") dirs = Directory.objects.exclude( pootle_path="/" ).exclude( pootle_path__startswith="/goals/" ).exclude( pootle_path__startswith="/projects/" ) language_codes = Language.objects.values_list("code", flat=True) for directory in dirs: directory_path_parts = directory.pootle_path.split("/") if len(directory_path_parts) < 4: continue directory_lang_code = directory_path_parts[1] if directory_lang_code in language_codes: tp_path = "/".join(directory_path_parts[:3] + [""]) has_tp = TP.objects.filter(pootle_path=tp_path).exists() if not has_tp: Directory.objects.filter( pootle_path__startswith=directory.pootle_path ).delete() class Migration(migrations.Migration): dependencies = [ ('pootle_app', '0016_set_directory_tp_again'), ('pootle_translationproject', '0005_remove_empty_translationprojects'), ('pootle_language', '0002_case_insensitive_schema'), ] operations = [ migrations.RunPython(drop_stray_directories), ]
1,601
Python
.py
38
34.315789
79
0.649871
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,209
0012_set_directory_tp.py
translate_pootle/pootle/apps/pootle_app/migrations/0012_set_directory_tp.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.10 on 2016-11-02 19:58 from __future__ import unicode_literals from django.db import migrations def set_directory_tp(apps, schema_editor): dirs = apps.get_model("pootle_app.Directory").objects.all() TP = apps.get_model("pootle_translationproject.TranslationProject") tps = TP.objects.all() for tp in tps: dirs.filter( pootle_path__startswith=tp.pootle_path).update(tp=tp) class Migration(migrations.Migration): dependencies = [ ('pootle_app', '0011_directory_tp'), ] operations = [ migrations.RunPython(set_directory_tp), ]
650
Python
.py
18
30.888889
71
0.682692
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,210
0011_directory_tp.py
translate_pootle/pootle/apps/pootle_app/migrations/0011_directory_tp.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.11 on 2016-11-04 07:36 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('pootle_translationproject', '0003_realpath_can_be_none'), ('pootle_app', '0010_obsolete_path_idx'), ] operations = [ migrations.AddField( model_name='directory', name='tp', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='dirs', to='pootle_translationproject.TranslationProject'), ), ]
677
Python
.py
17
33.588235
176
0.674809
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,211
0005_case_sensitive_schema.py
translate_pootle/pootle/apps/pootle_app/migrations/0005_case_sensitive_schema.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from pootle.core.utils.db import set_mysql_collation_for_column def make_directory_paths_cs(apps, schema_editor): cursor = schema_editor.connection.cursor() set_mysql_collation_for_column( apps, cursor, "pootle_app.Directory", "pootle_path", "utf8_bin", "varchar(255)") set_mysql_collation_for_column( apps, cursor, "pootle_app.Directory", "name", "utf8_bin", "varchar(255)") class Migration(migrations.Migration): dependencies = [ ('pootle_app', '0004_set_directory_has_no_default_permissions'), ] operations = [ migrations.RunPython(make_directory_paths_cs), ]
816
Python
.py
27
23.740741
72
0.638924
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,212
urls.py
translate_pootle/pootle/apps/pootle_app/views/index/urls.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django.conf.urls import url from django.views.generic import TemplateView from .index import AboutView, IndexView urlpatterns = [ url(r'^robots\.txt$', TemplateView.as_view(template_name='robots.txt', content_type='text/plain'), name="pootle-robots"), url(r'^$', IndexView.as_view(), name='pootle-home'), url(r'^about/$', AboutView.as_view(), name='pootle-about'), ]
742
Python
.py
22
28.409091
77
0.662465
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,213
index.py
translate_pootle/pootle/apps/pootle_app/views/index/index.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django.contrib.auth import REDIRECT_FIELD_NAME from django.shortcuts import redirect from django.urls import reverse from django.utils.functional import cached_property from django.utils.translation import get_language from django.views.generic import TemplateView, View from pootle.core.decorators import persistent_property from pootle.core.delegate import revision, scores from pootle.i18n.override import get_lang_from_http_header from pootle_language.models import Language from pootle_project.models import Project, ProjectSet COOKIE_NAME = 'pootle-language' class WelcomeView(TemplateView): ns = "pootle.web.welcome" template_name = "welcome.html" @property def revision(self): return revision.get(self.project_set.directory.__class__)( self.project_set.directory).get(key="stats") @property def cache_key(self): return ( "%s.%s.%s" % (self.request.user.username, self.revision, self.request_lang)) @cached_property def project_set(self): user_projects = Project.accessible_by_user(self.request.user) user_projects = ( Project.objects.for_user(self.request.user) .filter(code__in=user_projects)) return ProjectSet(user_projects) @property def request_lang(self): return get_language() @persistent_property def score_data(self): return scores.get(ProjectSet)( self.project_set).display(language=self.request_lang) def get_context_data(self, **kwargs): context = super(WelcomeView, self).get_context_data(**kwargs) context.update(dict(score_data=self.score_data)) return context class IndexView(View): @property def active_languages(self): return Language.objects.filter( translationproject__isnull=False, translationproject__directory__obsolete=False) @property def all_languages(self): return self.active_languages @property def languages(self): return self.active_languages.filter( translationproject__project__disabled=False) def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated: ctx = { 'next': request.GET.get(REDIRECT_FIELD_NAME, '')} return WelcomeView.as_view()(request, ctx) lang = request.COOKIES.get(COOKIE_NAME, None) if lang is None: lang = get_lang_from_http_header( request, dict((self.all_languages if request.user.is_superuser else self.languages).values_list('code', 'fullname'))) if lang is not None and lang not in ('projects', ''): url = reverse('pootle-language-browse', args=[lang]) else: url = reverse('pootle-projects-browse') # Preserve query strings args = request.GET.urlencode() qs = '?%s' % args if args else '' redirect_url = '%s%s' % (url, qs) return redirect(redirect_url) class AboutView(TemplateView): template_name = 'about.html' def get_context_data(self, **kwargs): from translate.__version__ import sver as toolkit_version from pootle import __version__ from pootle.core.utils.version import get_git_hash git_hash = get_git_hash() if git_hash: pootle_version = __version__ + " [%s]" % git_hash else: pootle_version = __version__ return { 'pootle_version': pootle_version, 'toolkit_version': toolkit_version, }
3,977
Python
.py
100
31.65
77
0.650752
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,214
users.py
translate_pootle/pootle/apps/pootle_app/views/admin/users.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django.contrib.auth import get_user_model from django.views.generic import TemplateView from pootle.core.views import APIView from pootle.core.views.mixins import SuperuserRequiredMixin from pootle_app.forms import UserForm __all__ = ('UserAdminView', 'UserAPIView') class UserAdminView(SuperuserRequiredMixin, TemplateView): template_name = 'admin/users.html' def get_context_data(self, **kwargs): return { 'page': 'admin-users', } class UserAPIView(SuperuserRequiredMixin, APIView): model = get_user_model() base_queryset = get_user_model().objects.hide_permission_users() \ .order_by('-id') add_form_class = UserForm edit_form_class = UserForm page_size = 10 search_fields = ('username', 'full_name', 'email')
1,106
Python
.py
27
35.777778
77
0.705607
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,215
util.py
translate_pootle/pootle/apps/pootle_app/views/admin/util.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django import forms from django.forms.models import modelformset_factory from django.forms.utils import ErrorList from django.shortcuts import render from django.utils.safestring import mark_safe from pootle.core.paginator import paginate from pootle.i18n.gettext import ugettext as _ def form_set_as_table(formset, link=None, linkfield='code'): """Create an HTML table from the formset. The first form in the formset is used to obtain a list of the fields that need to be displayed. Errors, if there are any, appear in the row above the form which triggered any errors. If the forms are based on database models, the order of the columns is determined by the order of the fields in the model specification. """ def add_header(result, fields, form): result.append('<tr>\n') for field in fields: widget = form.fields[field].widget widget_name = widget.__class__.__name__ if widget.is_hidden or \ widget_name in ('CheckboxInput', 'SelectMultiple'): result.append('<th class="sorttable_nosort">') else: result.append('<th>') if widget_name in ('CheckboxInput',): result.append(form[field].as_widget()) result.append(form[field].label_tag()) elif form.fields[field].label is not None and not widget.is_hidden: result.append(unicode(form.fields[field].label)) result.append('</th>\n') result.append('</tr>\n') def add_footer(result, fields, form): result.append('<tr>\n') for field in fields: field_obj = form.fields[field] result.append('<td>') if field_obj.label is not None and not field_obj.widget.is_hidden: result.append(unicode(field_obj.label)) result.append('</td>\n') result.append('</tr>\n') def add_errors(result, fields, form): # If the form has errors, then we'll add a table row with the # errors. if len(form.errors) > 0: result.append('<tr>\n') for field in fields: result.append('<td>') result.append(form.errors.get(field, ErrorList()).as_ul()) result.append('</td>\n') result.append('</tr>\n') def add_widgets(result, fields, form, link): result.append('<tr class="item">\n') for i, field in enumerate(fields): result.append('<td class="%s">' % field) # Include a hidden element containing the form's id to the # first column. if i == 0: result.append(form['id'].as_hidden()) # `link` indicates whether we put the first field as a link or as # widget if field == linkfield and linkfield in form.initial and link: if callable(link): result.append(link(form.instance)) result.append(form[field].as_hidden()) else: result.append(form[field].as_widget()) result.append('</td>\n') result.append('</tr>\n') result = [] try: first_form = formset.forms[0] # Get the fields of the form, but filter our the 'id' field, # since we don't want to print a table column for it. fields = [field for field in first_form.fields if field != 'id'] result.append('<thead>\n') add_header(result, fields, first_form) result.append('</thead>\n') result.append('<tfoot>\n') add_footer(result, fields, first_form) result.append('</tfoot>\n') result.append('<tbody>\n') # Do not display the delete checkbox for the 'add a new entry' form. if formset.extra_forms: formset.forms[-1].fields['DELETE'].widget = forms.HiddenInput() for form in formset.forms: add_errors(result, fields, form) add_widgets(result, fields, form, link) result.append('</tbody>\n') except IndexError: result.append('<tr>\n') result.append('<td>\n') result.append(_('No files in this project.')) result.append('</td>\n') result.append('</tr>\n') return u''.join(result) def process_modelformset(request, model_class, queryset, **kwargs): """With the Django model class `model_class` and the given `queryset`, construct a formset process its submission. """ # Create a formset class for the model `model_class` (i.e. it will contain # forms whose contents are based on the fields of `model_class`); # parameters for the construction of the forms used in the formset should # be in kwargs. formset_class = modelformset_factory(model_class, **kwargs) if queryset is None: queryset = model_class.objects.all() # If the request is a POST, we want to possibly update our data if request.method == 'POST' and request.POST: # Create a formset from all the 'model_class' instances whose values # will be updated using the contents of request.POST objects = paginate(request, queryset) formset = formset_class(request.POST, queryset=objects.object_list) # Validate all the forms in the formset if formset.is_valid(): # If all is well, Django can save all our data for us formset.save() else: # Otherwise, complain to the user that something went wrong return formset, _("There are errors in the form. Please review " "the problems below."), objects # Hack to force reevaluation of same query queryset = queryset.filter() objects = paginate(request, queryset) return formset_class(queryset=objects.object_list), None, objects def edit(request, template, model_class, ctx=None, link=None, linkfield='code', queryset=None, **kwargs): formset, msg, objects = process_modelformset(request, model_class, queryset=queryset, **kwargs) if ctx is None: ctx = {} ctx.update({ 'formset_text': mark_safe(form_set_as_table(formset, link, linkfield)), 'formset': formset, 'objects': objects, 'error_msg': msg, 'can_add': kwargs.get('extra', 1) != 0, }) return render(request, template, ctx)
6,759
Python
.py
148
36.202703
79
0.616461
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,216
urls.py
translate_pootle/pootle/apps/pootle_app/views/admin/urls.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django.conf.urls import include, url import staticpages.urls from . import (LanguageAdminView, LanguageAPIView, PermissionsUsersJSON, ProjectAdminView, ProjectAPIView, UserAdminView, UserAPIView, adminroot, dashboard) urlpatterns = [ url(r'^$', dashboard.view, name='pootle-admin'), # FIXME: remove ad-hoc inclusion, make this pluggable url(r'^pages/', include(staticpages.urls.admin_patterns)), url(r'^users/$', UserAdminView.as_view(), name='pootle-admin-users'), url(r'^users/(?P<id>[0-9]+)/?$', UserAdminView.as_view(), name='pootle-admin-user-edit'), url(r'^languages/$', LanguageAdminView.as_view(), name='pootle-admin-languages'), url(r'^languages/(?P<id>[0-9]+)/?$', LanguageAdminView.as_view(), name='pootle-admin-language-edit'), url(r'^projects/$', ProjectAdminView.as_view(), name='pootle-admin-projects'), url(r'^projects/(?P<id>[0-9]+)/?$', ProjectAdminView.as_view(), name='pootle-admin-project-edit'), url(r'^permissions/$', adminroot.view, name='pootle-admin-permissions'), url(r'^xhr/permissions/users/(?P<directory>[^/]*)/$', PermissionsUsersJSON.as_view(), name='pootle-permissions-users')] api_patterns = [ url(r'^users/?$', UserAPIView.as_view(), name='pootle-xhr-admin-users'), url(r'^users/(?P<id>[0-9]+)/?$', UserAPIView.as_view(), name='pootle-xhr-admin-user'), url(r'^languages/?$', LanguageAPIView.as_view(), name='pootle-xhr-admin-languages'), url(r'^languages/(?P<id>[0-9]+)/?$', LanguageAPIView.as_view(), name='pootle-xhr-admin-languages'), url(r'^projects/?$', ProjectAPIView.as_view(), name='pootle-xhr-admin-projects'), url(r'^projects/(?P<id>[0-9]+)/?$', ProjectAPIView.as_view(), name='pootle-xhr-admin-project'), ]
2,294
Python
.py
63
29.68254
77
0.619585
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,217
languages.py
translate_pootle/pootle/apps/pootle_app/views/admin/languages.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django.views.generic import TemplateView from pootle.core.views import APIView from pootle.core.views.mixins import SuperuserRequiredMixin from pootle_app.forms import LanguageForm from pootle_language.models import Language __all__ = ('LanguageAdminView', 'LanguageAPIView') class LanguageAdminView(SuperuserRequiredMixin, TemplateView): template_name = 'admin/languages.html' def get_context_data(self, **kwargs): return { 'page': 'admin-languages', } class LanguageAPIView(SuperuserRequiredMixin, APIView): model = Language base_queryset = Language.objects.order_by('-id') add_form_class = LanguageForm edit_form_class = LanguageForm page_size = 10 search_fields = ('code', 'fullname')
1,038
Python
.py
26
36.269231
77
0.751745
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,218
projects.py
translate_pootle/pootle/apps/pootle_app/views/admin/projects.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django.views.generic import TemplateView from pootle.core.delegate import formats from pootle.core.views import APIView from pootle.core.views.mixins import SuperuserRequiredMixin from pootle_app.forms import ProjectForm from pootle_config.utils import ObjectConfig from pootle_fs.delegate import fs_plugins from pootle_fs.presets import FS_PRESETS from pootle_language.models import Language from pootle_project.models import PROJECT_CHECKERS, Project __all__ = ('ProjectAdminView', 'ProjectAPIView') class ProjectAdminView(SuperuserRequiredMixin, TemplateView): template_name = 'admin/projects.html' def get_context_data(self, **kwargs): languages = Language.objects.exclude(code='templates') language_choices = [(lang.id, unicode(lang)) for lang in languages] try: english = Language.objects.get(code='en') default_language = english.id except Language.DoesNotExist: default_language = languages[0].id filetypes = [] for info in formats.get().values(): filetypes.append( [info["pk"], info["display_title"]]) project_checker_choices = [ (checker, checker) for checker in sorted(PROJECT_CHECKERS.keys())] plugin_choices = sorted([(x, x) for x in fs_plugins.gather()]) fs_presets = FS_PRESETS.values() return { 'page': 'admin-projects', 'form_choices': { 'checkstyle': project_checker_choices, 'filetypes': filetypes, 'fs_plugin': plugin_choices, 'fs_preset': fs_presets, 'source_language': language_choices, 'defaults': { 'source_language': default_language, }, }, } class ProjectAPIView(SuperuserRequiredMixin, APIView): model = Project base_queryset = Project.objects.order_by('-id') add_form_class = ProjectForm edit_form_class = ProjectForm page_size = 10 search_fields = ('code', 'fullname', 'disabled') m2m = ("filetypes", ) config = ( ("fs_plugin", "pootle_fs.fs_type"), ("fs_url", "pootle_fs.fs_url"), ("fs_mapping", "pootle_fs.translation_mappings")) def serialize_config(self, info, item): config = ObjectConfig(item) for k, v in self.config: if k == "fs_mapping": mapping = config.get(v) or {} info[k] = mapping.get("default") else: info[k] = config.get(v) info["template_name"] = ( item.lang_mapper.get_upstream_code("templates"))
2,968
Python
.py
73
32.205479
77
0.628512
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,219
dashboard.py
translate_pootle/pootle/apps/pootle_app/views/admin/dashboard.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from redis.exceptions import ConnectionError from django.contrib.auth import get_user_model from django.core.cache import cache from django.shortcuts import render from django_rq.queues import get_failed_queue, get_queue from django_rq.workers import Worker from pootle.core.decorators import admin_required from pootle.i18n import formatter from pootle.i18n.gettext import ugettext as _, ungettext from pootle_statistics.models import Submission from pootle_store.models import Suggestion def _format_numbers(numbers): for k in numbers.keys(): numbers[k] = formatter.number(numbers[k]) def server_stats(): User = get_user_model() result = cache.get("server_stats") if result is None: result = {} result['user_count'] = max(User.objects.filter( is_active=True).count()-2, 0) # 'default' and 'nobody' might be counted # FIXME: the special users should not be retuned with is_active result['submission_count'] = Submission.objects.count() result['pending_count'] = Suggestion.objects.pending().count() cache.set("server_stats", result, 86400) _format_numbers(result) return result def rq_stats(): queue = get_queue() failed_queue = get_failed_queue() try: workers = Worker.all(queue.connection) except ConnectionError: return None num_workers = len(workers) is_running = len(queue.connection.smembers(Worker.redis_workers_keys)) > 0 if is_running: # Translators: this refers to the status of the background job worker status_msg = ungettext('Running (%d worker)', 'Running (%d workers)', num_workers) % num_workers else: # Translators: this refers to the status of the background job worker status_msg = _('Stopped') result = { 'job_count': queue.count, 'failed_job_count': failed_queue.count, 'is_running': is_running, 'status_msg': status_msg, } return result def checks(): from django.core.checks.registry import registry return [e for e in registry.run_checks() if not e.is_silenced()] @admin_required def view(request): ctx = { 'page': 'admin-dashboard', 'server_stats': server_stats(), 'rq_stats': rq_stats(), 'checks': checks(), } return render(request, "admin/dashboard.html", ctx)
2,688
Python
.py
70
32.757143
78
0.685769
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,220
adminroot.py
translate_pootle/pootle/apps/pootle_app/views/admin/adminroot.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from pootle.core.decorators import admin_required from pootle_app.models.directory import Directory from pootle_app.views.admin.permissions import admin_permissions @admin_required def view(request): directory = Directory.objects.root ctx = { 'page': 'admin-permissions', 'directory': directory, } return admin_permissions(request, directory, "admin/permissions.html", ctx)
684
Python
.py
18
35.055556
79
0.757164
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,221
__init__.py
translate_pootle/pootle/apps/pootle_app/views/admin/__init__.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from .languages import LanguageAdminView, LanguageAPIView from .projects import ProjectAdminView, ProjectAPIView from .users import UserAdminView, UserAPIView from .permissions import PermissionsUsersJSON __all__ = ( 'LanguageAdminView', 'LanguageAPIView', 'PermissionsUsersJSON', 'ProjectAdminView', 'ProjectAPIView', 'UserAdminView', 'UserAPIView')
637
Python
.py
14
43.714286
77
0.790323
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,222
permissions.py
translate_pootle/pootle/apps/pootle_app/views/admin/permissions.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django import forms from django.contrib.auth import get_user_model from django.urls import reverse from pootle.core.decorators import get_object_or_404 from pootle.core.exceptions import Http400 from pootle.core.views.admin import PootleAdminFormView from pootle.core.views.mixins import PootleJSONMixin from pootle.core.views.widgets import RemoteSelectWidget from pootle.i18n.gettext import ugettext as _ from pootle_app.forms import PermissionsUsersSearchForm from pootle_app.models import Directory from pootle_app.models.permissions import (PermissionSet, get_permission_contenttype) from pootle_app.views.admin import util from pootle_misc.forms import GroupedModelChoiceField User = get_user_model() PERMISSIONS = { 'positive': ['view', 'suggest', 'translate', 'review', 'administrate'], 'negative': ['hide'], } class PermissionFormField(forms.ModelMultipleChoiceField): def label_from_instance(self, instance): return _(instance.name) def admin_permissions(request, current_directory, template, ctx): language = ctx.get('language', None) negative_permissions_excl = list(PERMISSIONS['negative']) positive_permissions_excl = list(PERMISSIONS['positive']) # Don't provide means to alter access permissions under /<lang_code>/* # In other words: only allow setting access permissions for the root # and the `/projects/<code>/` directories if language is not None: access_permissions = ['view', 'hide'] negative_permissions_excl.extend(access_permissions) positive_permissions_excl.extend(access_permissions) content_type = get_permission_contenttype() positive_permissions_qs = content_type.permission_set.exclude( codename__in=negative_permissions_excl, ) negative_permissions_qs = content_type.permission_set.exclude( codename__in=positive_permissions_excl, ) base_queryset = User.objects.filter(is_active=1).exclude( id__in=current_directory.permission_sets.values_list('user_id', flat=True),) choice_groups = [(None, base_queryset.filter( username__in=('nobody', 'default') ))] choice_groups.append(( _('All Users'), base_queryset.exclude(username__in=('nobody', 'default')).order_by('username'), )) class PermissionSetForm(forms.ModelForm): class Meta(object): model = PermissionSet fields = ('user', 'directory', 'positive_permissions', 'negative_permissions') directory = forms.ModelChoiceField( queryset=Directory.objects.filter(pk=current_directory.pk), initial=current_directory.pk, widget=forms.HiddenInput, ) user = GroupedModelChoiceField( label=_('Username'), choice_groups=choice_groups, queryset=User.objects.all(), required=True, widget=RemoteSelectWidget( attrs={ "data-s2-placeholder": _("Search for users to add"), 'class': ('js-select2-remote select2-username ' 'js-s2-new-members')})) positive_permissions = PermissionFormField( label=_('Add Permissions'), queryset=positive_permissions_qs, required=False, widget=forms.SelectMultiple(attrs={ 'class': 'js-select2 select2-multiple', 'data-placeholder': _('Select one or more permissions'), }), ) negative_permissions = PermissionFormField( label=_('Revoke Permissions'), queryset=negative_permissions_qs, required=False, widget=forms.SelectMultiple(attrs={ 'class': 'js-select2 select2-multiple', 'data-placeholder': _('Select one or more permissions'), }), ) def __init__(self, *args, **kwargs): super(PermissionSetForm, self).__init__(*args, **kwargs) self.fields["user"].widget.attrs["data-select2-url"] = reverse( "pootle-permissions-users", kwargs=dict(directory=current_directory.pk)) # Don't display extra negative permissions field where they # are not applicable if language is not None: del self.fields['negative_permissions'] link = lambda instance: unicode(instance.user) directory_permissions = current_directory.permission_sets \ .order_by('user').all() return util.edit(request, template, PermissionSet, ctx, link, linkfield='user', queryset=directory_permissions, can_delete=True, form=PermissionSetForm) class PermissionsUsersJSON(PootleJSONMixin, PootleAdminFormView): form_class = PermissionsUsersSearchForm @property def directory(self): return get_object_or_404( Directory.objects, pk=self.kwargs["directory"]) def get_context_data(self, **kwargs): context = super( PermissionsUsersJSON, self).get_context_data(**kwargs) form = context["form"] return ( dict(items=form.search()) if form.is_valid() else dict(items=[])) def get_form_kwargs(self): kwargs = super(PermissionsUsersJSON, self).get_form_kwargs() kwargs["directory"] = self.directory return kwargs def form_valid(self, form): return self.render_to_response( self.get_context_data(form=form)) def form_invalid(self, form): raise Http400(form.errors)
6,105
Python
.py
136
34.933824
77
0.63843
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,223
__init__.py
translate_pootle/pootle/apps/pootle_app/management/__init__.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import logging from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType from django.db.models.signals import pre_delete, post_delete from django.dispatch import receiver permission_queryset = None @receiver(pre_delete, sender=ContentType) def fix_permission_content_type_pre(**kwargs): instance = kwargs["instance"] if instance.name == 'pootle' and instance.model == "": logging.debug("Fixing permissions content types") global permission_queryset permission_queryset = [permission for permission in Permission.objects.filter( content_type=instance)] @receiver(post_delete, sender=ContentType) def fix_permission_content_type_post(**kwargs_): global permission_queryset if permission_queryset is not None: dir_content_type = ContentType.objects.get(app_label='pootle_app', model='directory') dir_content_type.name = 'pootle' dir_content_type.save() for permission in permission_queryset: permission.content_type = dir_content_type permission.save() permission_queryset = None
1,532
Python
.py
34
37.323529
77
0.690604
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,224
set_filetype.py
translate_pootle/pootle/apps/pootle_app/management/commands/set_filetype.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import os os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings' from django.core.management.base import CommandError from pootle_format.models import Format from pootle_project.models import Project from . import PootleCommand class Command(PootleCommand): help = "Manage Store formats." def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument( 'filetype', action='store', help="File type to set") parser.add_argument( '--from-filetype', action='store', help="Only convert Stores of this file type") parser.add_argument( '--matching', action='store', help="Glob match Store path excluding extension") def get_projects(self): if not self.projects: return Project.objects.all() return Project.objects.filter(code__in=self.projects) def get_filetype(self, name): try: return Format.objects.get(name=name) except Format.DoesNotExist: raise CommandError("Unrecognized filetype '%s'" % name) def handle_all(self, **options): filetype = self.get_filetype(options["filetype"]) from_filetype = ( options["from_filetype"] and self.get_filetype(options["from_filetype"]) or None) for project in self.get_projects(): # add the filetype to project, and convert the stores project.filetype_tool.add_filetype(filetype) project.filetype_tool.set_filetypes( filetype, from_filetype=from_filetype, matching=options["matching"])
2,012
Python
.py
51
30.921569
77
0.642894
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,225
sync_stores.py
translate_pootle/pootle/apps/pootle_app/management/commands/sync_stores.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import logging import os os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings' from pootle_app.management.commands import PootleCommand from pootle_fs.utils import FSPlugin logger = logging.getLogger(__name__) class Command(PootleCommand): help = "Save new translations to disk manually." process_disabled_projects = True def __init__(self, *args, **kwargs): self.warn_on_conflict = [] super(Command, self).__init__(*args, **kwargs) def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument( '--overwrite', action='store_true', dest='overwrite', default=False, help="This option has been removed.") parser.add_argument( '--skip-missing', action='store_true', dest='skip_missing', default=False, help="Ignore missing files on disk", ) parser.add_argument( '--force', action='store_true', dest='force', default=False, help="This option has been removed.") def handle(self, **options): logger.warn( "The sync_stores command is deprecated, use pootle fs instead") if options["force"]: logger.warn( "The force option no longer has any affect on this command") if options["overwrite"]: logger.warn( "The overwrite option no longer has any affect on this command") super(Command, self).handle(**options) def handle_all_stores(self, translation_project, **options): path_glob = "%s*" % translation_project.pootle_path plugin = FSPlugin(translation_project.project) plugin.fetch() if translation_project.project.pk not in self.warn_on_conflict: state = plugin.state() if any(k in state for k in ["conflict", "conflict_untracked"]): logger.warn( "The project '%s' has conflicting changes in the database " "and translation files. Use `pootle fs resolve` to tell " "pootle how to merge", translation_project.project.code) self.warn_on_conflict.append( translation_project.project.pk) if not options["skip_missing"]: plugin.add(pootle_path=path_glob, update="fs") plugin.sync(pootle_path=path_glob, update="fs")
2,802
Python
.py
67
32.074627
80
0.609541
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,226
create_project.py
translate_pootle/pootle/apps/pootle_app/management/commands/create_project.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import os import traceback os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings' from django.db import transaction from django.core.management.base import BaseCommand from django.core.exceptions import ValidationError from django.core.management import CommandError from django.core.validators import validate_email from pootle.core.delegate import formats from pootle_fs.delegate import fs_plugins from pootle_fs.presets import FS_PRESETS from pootle_language.models import Language from pootle_project.models import Project, PROJECT_CHECKERS class Command(BaseCommand): help = "Creates a new project from command line." def add_arguments(self, parser): format_names = formats.get().keys() fs_plugins_names = fs_plugins.gather().keys() parser.add_argument( 'code', action='store', help='Project code', ) parser.add_argument( "--name", action="store", dest="name", help="Project name", ) parser.add_argument( "--filetype", action="append", dest="filetypes", choices=format_names, default=[], help="File types: {0}. Default: po".format( " | ".join(format_names)), ) mapping_group = parser.add_mutually_exclusive_group(required=True) mapping_group.add_argument( "--preset-mapping", action="store", dest="preset_mapping", choices=FS_PRESETS.keys(), help="Filesystem layout preset: {0}".format( " | ".join(FS_PRESETS.keys())), ) mapping_group.add_argument( "--mapping", action="store", dest="mapping", help="Custom filesystem layout", ) parser.add_argument( "--fs-type", action="store", dest="fs_type", default="localfs", choices=fs_plugins_names, help="Filesystem type: {0}".format(" | ".join(fs_plugins_names)), ) parser.add_argument( "--fs-url", action="store", dest="fs_url", default="", help="Filesystem path or URL.", ) parser.add_argument( "--source-language", action="store", dest="sourcelang", default="en", help=("Source language. Examples: [en | es | fr | ...]." "Default: %(default)s"), ) parser.add_argument( "--report-email", action="store", default="", dest="contact", help="Contact email for reports. Example: admin@mail.com.", ) parser.add_argument( "--disabled", action="store_true", dest="disabled", help="Does the project start disabled?", ) parser.add_argument( "--checkstyle", action="store", dest="checkstyle", choices=PROJECT_CHECKERS.keys(), default="standard", help="Quality check styles. Example: {0}. Default: %(default)s" .format(" | ".join(PROJECT_CHECKERS.keys())), ) @transaction.atomic def handle(self, **options): """Imitates the behaviour of the admin interface for creating a project from command line. """ self.check_project_options(**options) self.set_project_config( self.create_project(**options), **options) def check_project_options(self, **options): if options["contact"]: try: validate_email(options["contact"]) except ValidationError as e: if options["traceback"]: traceback.print_exc() raise CommandError(e) if options["fs_type"] != "localfs" and options["fs_url"] == "": raise CommandError("Parameter --fs-url is mandatory " "when --fs-type is not `localfs`") def create_project(self, **options): try: return Project.objects.create( code=options["code"], fullname=options["name"] or options["code"].capitalize(), checkstyle=options["checkstyle"], source_language=self.get_source_language(**options), filetypes=options["filetypes"] or ["po"], report_email=options["contact"], disabled=options["disabled"]) except ValidationError as e: if options["traceback"]: traceback.print_exc() raise CommandError(e) def get_source_language(self, **options): try: return Language.objects.get(code=options["sourcelang"]) except Language.DoesNotExist: raise CommandError("Source language %s does not exist" % options["sourcelang"]) def set_project_config(self, project, **options): mapping = ( dict(default=FS_PRESETS[options["preset_mapping"]][0]) if options["preset_mapping"] else dict(default=options["mapping"])) try: project.config["pootle_fs.translation_mapping"] = mapping project.config["pootle_fs.fs_type"] = options["fs_type"] if options["fs_url"]: project.config["pootle_fs.fs_url"] = options["fs_url"] except ValidationError as e: if options["traceback"]: traceback.print_exc() raise CommandError(e)
5,973
Python
.py
158
26.955696
77
0.561531
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,227
webpack.py
translate_pootle/pootle/apps/pootle_app/management/commands/webpack.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import os os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings' import subprocess from django.conf import settings from django.contrib.staticfiles.finders import AppDirectoriesFinder from django.core.management.base import BaseCommand, CommandError from pootle_misc.baseurl import link class Command(BaseCommand): help = 'Builds and bundles static assets using webpack' requires_system_checks = False def add_arguments(self, parser): parser.add_argument( '--dev', action='store_true', dest='dev', default=False, help='Enable development builds and watch for changes.', ) parser.add_argument( '--nowatch', action='store_false', dest='watch', default=True, help='Disable watching for changes.', ) parser.add_argument( '--progress', action='store_true', default=False, help='Show progress (implied if --dev is present).', ) parser.add_argument( '--extra', action='append', default=[], help='Additional options to pass to the JavaScript webpack tool.', ) def handle(self, **options): default_static_dir = os.path.join(settings.WORKING_DIR, 'static') custom_static_dirs = filter(lambda x: x != default_static_dir, settings.STATICFILES_DIRS) finder = AppDirectoriesFinder() for app_name in finder.storages: location = finder.storages[app_name].location add_new_custom_dir = (location != default_static_dir and location not in custom_static_dirs) if add_new_custom_dir: custom_static_dirs.append(location) default_js_dir = os.path.join(default_static_dir, 'js') webpack_config_file = os.path.join(default_js_dir, 'webpack.config.js') webpack_bin = os.path.join(default_js_dir, 'node_modules/.bin/webpack') if os.name == 'nt': webpack_bin = '%s.cmd' % webpack_bin webpack_progress = ( '--progress' if options['progress'] or options['dev'] else '' ) webpack_colors = '--colors' if not options['no_color'] else '' webpack_args = [webpack_bin, '--config=%s' % webpack_config_file] if webpack_progress: webpack_args.append(webpack_progress) if webpack_colors: webpack_args.append(webpack_colors) if options['dev']: watch = '--watch' if options['watch'] else '' webpack_args.extend([watch, '--display-error-details']) else: os.environ['NODE_ENV'] = 'production' webpack_args.append("--bail") webpack_args.extend(options['extra']) static_base = link(settings.STATIC_URL) suffix = 'js/' if static_base.endswith('/') else '/js/' os.environ['WEBPACK_PUBLIC_PATH'] = static_base + suffix if custom_static_dirs: # XXX: review this for css # Append `js/` so that it's not necessary to reference it from the # `webpack.config.js` file custom_static_dirs = map(lambda x: os.path.join(x, 'js/'), custom_static_dirs) os.environ['WEBPACK_ROOT'] = ':'.join(custom_static_dirs) try: subprocess.call(webpack_args) except OSError: raise CommandError( 'webpack executable not found.\n' 'Make sure to install it by running ' '`cd %s && npm install`' % default_js_dir )
4,013
Python
.py
94
32.148936
79
0.590361
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,228
config.py
translate_pootle/pootle/apps/pootle_app/management/commands/config.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import collections import json import os os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings' from django.contrib.contenttypes.models import ContentType from django.core.exceptions import FieldError from django.core.management.base import BaseCommand, CommandError from pootle.core.delegate import config class Command(BaseCommand): help = "Manage configuration for Pootle objects." def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument( 'content_type', action='store', nargs="?", help="Get/set config for given content type") parser.add_argument( 'object', action='store', nargs="?", help="Unique identifier for object, by default pk") parser.add_argument( '-o', '--object-field', action='store', dest='object_field', help=( "Use given field as identifier to get object, " "should be unique")) group = parser.add_mutually_exclusive_group() group.add_argument( '-g', '--get', action='store', dest='get', metavar="KEY", help="Get config with this key, key must be unique") group.add_argument( '-l', '--list', action='append', dest='list', metavar="KEY", help=( "List config with this key, " "can be specified multiple times")) group.add_argument( '-s', '--set', action='store', dest="set", metavar=("KEY", "VALUE"), nargs=2, help=( "Set config with this VALUE, KEY should not exist " "or must be unique")) group.add_argument( '-a', '--append', action='store', dest="append", metavar=("KEY", "VALUE"), nargs=2, help="Append config with this value") group.add_argument( '-c', '--clear', action='append', dest='clear', metavar="KEY", help="Clear config with this key") parser.add_argument( '-j', '--json', action='store_true', dest='json', help=( "When getting/setting/appending a config dump/load " "VALUE as json")) def print_config_item(self, name, key, value, name_col=25, key_col=25): format_string = "{: <%d} {: <%d} {: <30}" % (name_col, key_col) self.stdout.write( format_string.format( name, key, self.repr_value(value))) def get_conf(self, **kwargs): if kwargs["object"] and not kwargs["content_type"]: raise CommandError( "You must set --content-type (-t) when using " "--object-pk (-o)") if kwargs["content_type"]: if "." not in kwargs["content_type"]: raise CommandError( "content_type should be set with $app_label.$model_name") parts = kwargs["content_type"].split(".") model_name = parts[-1] app_label = ".".join(parts[:-1]) try: ct = ContentType.objects.get( app_label=app_label, model=model_name) except ContentType.DoesNotExist as e: raise CommandError(e) ct_model = ct.model_class() if kwargs["object"]: if kwargs["object_field"]: model_query = {kwargs["object_field"]: kwargs["object"]} else: model_query = dict(pk=kwargs["object"]) catch_exc = ( ct_model.DoesNotExist, ct_model.MultipleObjectsReturned, ValueError, FieldError) try: instance = ct_model.objects.get(**model_query) except catch_exc as e: raise CommandError(e) return config.get(ct_model, instance=instance) return config.get(ct_model) return config.get() def print_no_config(self): self.stdout.write("No configuration found") def handle(self, **kwargs): conf = self.get_conf(**kwargs) if kwargs["get"]: return self.handle_get_config( conf, **kwargs) elif kwargs["set"]: return self.handle_set_config( conf, **kwargs) elif kwargs["append"]: return self.handle_append_config( conf, **kwargs) elif kwargs["clear"]: return self.handle_clear_config( conf, **kwargs) return self.handle_list_config( conf, **kwargs) def handle_set_config(self, conf, **kwargs): k, v = kwargs["set"] if kwargs["json"]: v = self.json_value(v) try: conf.set_config(k, v) except conf.model.MultipleObjectsReturned as e: raise CommandError(e) self.stdout.write("Config '%s' set" % k) def json_value(self, value): try: return json.JSONDecoder( object_pairs_hook=collections.OrderedDict).decode(value) except ValueError as e: raise CommandError(e) def handle_append_config(self, conf, **kwargs): k, v = kwargs["append"] if kwargs["json"]: v = self.json_value(v) conf.append_config(k, v) self.stdout.write("Config '%s' appended" % k) def repr_value(self, value): if not isinstance(value, (str, unicode)): value_class = type(value).__name__ return ( "%s(%s)" % (value_class, json.dumps(value))) return value def handle_get_config(self, conf, **kwargs): try: v = conf.get_config(kwargs["get"]) except conf.model.MultipleObjectsReturned as e: raise CommandError(e) if kwargs["json"]: v = json.dumps(v) else: v = self.repr_value(v) self.stdout.write(v, ending="") def get_item_name(self, item, object_field=None): if item.content_type: ct = ".".join(item.content_type.natural_key()) if item.object_pk: if object_field: pk = getattr( item.content_object, object_field) else: pk = item.object_pk return "%s[%s]" % (ct, pk) else: return ct return "Pootle" def handle_list_config(self, conf, **kwargs): if kwargs["list"]: conf = conf.filter(key__in=set(kwargs["list"])) items = [] name_col = 25 key_col = 25 # first pass, populate the list and find longest name/key for item in conf.order_by("key", "pk").iterator(): name = self.get_item_name( item, object_field=kwargs["object_field"]) if len(name) > name_col: name_col = len(name) if len(item.key) > key_col: key_col = len(item.key) items.append((name, item.key, item.value)) for name, key, value in items: self.print_config_item( name, key, value, name_col=name_col, key_col=key_col) if not items: self.print_no_config() def handle_clear_config(self, conf, **kwargs): for key in kwargs["clear"]: conf.clear_config(key)
8,129
Python
.py
217
25.428571
77
0.519068
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,229
retry_failed_jobs.py
translate_pootle/pootle/apps/pootle_app/management/commands/retry_failed_jobs.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import os # This must be run before importing Django. os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings' from django.core.management.base import BaseCommand from django_rq.queues import get_failed_queue class Command(BaseCommand): help = "Retry failed RQ jobs." def handle(self, **options): failed_queue = get_failed_queue() for job_id in failed_queue.get_job_ids(): failed_queue.requeue(job_id=job_id)
727
Python
.py
18
37
77
0.736467
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,230
update_stores.py
translate_pootle/pootle/apps/pootle_app/management/commands/update_stores.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import logging import os os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings' from pootle_app.management.commands import PootleCommand from pootle_language.models import Language from pootle_fs.utils import FSPlugin from pootle_project.models import Project logger = logging.getLogger(__name__) class Command(PootleCommand): help = "Update database stores from files." process_disabled_projects = True log_name = "update" def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument( '--overwrite', action='store_true', dest='overwrite', default=False, help="Don't just update untranslated units " "and add new units, but overwrite database " "translations to reflect state in files.", ) parser.add_argument( '--force', action='store_true', dest='force', default=False, help="This option has been removed.") def handle_translation_project(self, translation_project, **options): """ """ path_glob = "%s*" % translation_project.pootle_path plugin = FSPlugin(translation_project.project) plugin.add(pootle_path=path_glob, update="pootle") plugin.rm(pootle_path=path_glob, update="pootle") plugin.resolve( pootle_path=path_glob, merge=not options["overwrite"]) plugin.sync(pootle_path=path_glob, update="pootle") def _parse_tps_to_create(self, project): plugin = FSPlugin(project) plugin.fetch() untracked_languages = set( fs.pootle_path.split("/")[1] for fs in plugin.state()["fs_untracked"]) new_langs = ( [lang for lang in untracked_languages if lang in self.languages] if self.languages else untracked_languages) return Language.objects.filter( code__in=new_langs).exclude( code__in=project.translationproject_set.values_list( "language__code", flat=True)) def _create_tps_for_project(self, project): for language in self._parse_tps_to_create(project): project.translationproject_set.create( language=language, project=project) def handle_all(self, **options): logger.warn( "The update_stores command is deprecated, use pootle fs instead") if options["force"]: logger.warn( "The force option no longer has any affect on this command") projects = ( Project.objects.filter(code__in=self.projects) if self.projects else Project.objects.all()) for project in projects.iterator(): self._create_tps_for_project(project) super(Command, self).handle_all(**options)
3,254
Python
.py
82
30.353659
77
0.621639
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,231
update_data.py
translate_pootle/pootle/apps/pootle_app/management/commands/update_data.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import logging import os os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings' from pootle.core.signals import update_data from pootle_app.management.commands import PootleCommand from pootle_store.models import Store from pootle_translationproject.models import TranslationProject logger = logging.getLogger(__name__) class Command(PootleCommand): help = "Update stats data" def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument( '--store', action='append', dest='stores', help='Store to update data') def handle_stores(self, stores): stores = Store.objects.filter(pootle_path__in=stores) tps = set() for store in stores: update_data.send(store.__class__, instance=store) logger.debug( "Updated data for store: %s", store.pootle_path) tps.add(store.tp) for tp in tps: update_data.send(tp.__class__, instance=tp) logger.debug( "Updated data for translation project: %s", tp.pootle_path) def handle(self, **options): projects = options.get("projects") languages = options.get("languages") stores = options.get("stores") tps = TranslationProject.objects.all() if stores: return self.handle_stores(stores) if projects: tps = tps.filter(project__code__in=projects) if languages: tps = tps.filter(language__code__in=languages) for tp in tps: for store in tp.stores.all(): update_data.send(store.__class__, instance=store) logger.debug( "Updated data for store: %s", store.pootle_path) update_data.send(tp.__class__, instance=tp) logger.debug( "Updated data for translation project: %s", tp.pootle_path)
2,303
Python
.py
59
29.813559
77
0.61387
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,232
list_projects.py
translate_pootle/pootle/apps/pootle_app/management/commands/list_projects.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import os os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings' from django.core.management.base import BaseCommand from pootle_project.models import Project class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( "--modified-since", action="store", dest="revision", type=int, default=0, help="Only process translations newer than specified revision", ) def handle(self, **options): self.list_projects(**options) def list_projects(self, **options): """List all projects on the server.""" if options['revision'] > 0: from pootle_translationproject.models import TranslationProject tps = TranslationProject.objects.filter( submission__id__gt=options['revision']) \ .distinct().values("project__code") for tp in tps: self.stdout.write(tp["project__code"]) else: for project in Project.objects.all(): self.stdout.write(project.code)
1,386
Python
.py
35
31.371429
77
0.640089
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,233
list_serializers.py
translate_pootle/pootle/apps/pootle_app/management/commands/list_serializers.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import os os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings' from django.contrib.contenttypes.models import ContentType from django.core.management.base import BaseCommand, CommandError from pootle.core.delegate import serializers, deserializers class Command(BaseCommand): help = "Manage serialization for Projects." def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument( '-m --model', dest="model", action="store", help='List de/serializers for given model.') parser.add_argument( '-d --deserializers', action="store_true", dest="deserializers", help='List deserializers') def model_from_content_type(self, ct_name): if not ct_name: return if "." not in ct_name: raise CommandError( "Model name should be contenttype " "$app_name.$label") try: return ContentType.objects.get_by_natural_key( *ct_name.split(".")).model_class() except ContentType.DoesNotExist as e: raise CommandError(e) def handle(self, **kwargs): model = self.model_from_content_type(kwargs["model"]) if kwargs["deserializers"]: return self.print_serializers_list( deserializers.gather(model), serializer_type="deserializers") return self.print_serializers_list( serializers.gather(model)) def print_serializers_list(self, serials, serializer_type="serializers"): if not serials.keys(): self.stdout.write( "There are no %s set up on your system" % serializer_type) if not serials.keys(): return heading = serializer_type.capitalize() self.stdout.write("\n%s" % heading) self.stdout.write("-" * len(heading)) for name, serializer in serials.items(): self.stdout.write( "{!s: <30} {!s: <50} ".format(name, serializer))
2,383
Python
.py
58
31.913793
77
0.623326
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,234
__init__.py
translate_pootle/pootle/apps/pootle_app/management/commands/__init__.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import datetime import logging from django.db import transaction from django.core.management.base import BaseCommand, CommandError from pootle.runner import set_sync_mode from pootle_language.models import Language from pootle_project.models import Project from pootle_translationproject.models import TranslationProject logger = logging.getLogger(__name__) class SkipChecksMixin(object): def check(self, app_configs=None, tags=None, display_num_errors=False, include_deployment_checks=False): skip_tags = getattr(self, 'skip_system_check_tags', None) if skip_tags is not None: from django.core.checks.registry import registry tags = registry.tags_available() - set(skip_tags) super(SkipChecksMixin, self).check( app_configs=app_configs, tags=tags, display_num_errors=display_num_errors, include_deployment_checks=include_deployment_checks) class PootleCommand(BaseCommand): """Base class for handling recursive pootle store management commands.""" atomic_default = "tp" process_disabled_projects = False project_related = ( "source_language", ) tp_related = ( "data", "language", "directory", "directory__parent", "directory__parent__parent") def add_arguments(self, parser): parser.add_argument( '--project', action='append', dest='projects', help='Project to refresh', ) parser.add_argument( '--language', action='append', dest='languages', help='Language to refresh', ) parser.add_argument( "--noinput", action="store_true", default=False, help=u"Never prompt for input", ) parser.add_argument( "--no-rq", action="store_true", default=False, help=(u"Run all jobs in a single process, without " "using rq workers"), ) parser.add_argument( "--atomic", action="store", default=self.atomic_default, choices=["tp", "all", "none"], help=( u"Run commands using database atomic " u"transactions")) def __init__(self, *args, **kwargs): self.languages = [] self.projects = [] super(PootleCommand, self).__init__(*args, **kwargs) def do_translation_project(self, tp, **options): if hasattr(self, "handle_translation_project"): logging.info(u"[pootle] Running: %s for %s", self.name, tp) if not self.handle_translation_project(tp, **options): return if hasattr(self, "handle_all_stores"): logging.info(u"[pootle] Running: %s for %s's files", self.name, tp) self.handle_all_stores(tp, **options) def check_projects(self, project_codes): existing_projects = Project.objects.filter( code__in=project_codes ).values_list("code", flat=True) if len(existing_projects) != len(project_codes): unrecognized_projects = list(set(project_codes) - set(existing_projects)) raise CommandError("Unrecognized projects: %s" % unrecognized_projects) def check_languages(self, language_codes): existing_languages = Language.objects.filter( code__in=language_codes ).values_list("code", flat=True) if len(existing_languages) != len(language_codes): unrecognized_languages = list(set(language_codes) - set(existing_languages)) raise CommandError("Unrecognized languages: %s" % unrecognized_languages) def handle(self, **options): if options["atomic"] == "all": with transaction.atomic(): return self._handle(**options) else: return self._handle(**options) def _handle(self, **options): # adjust debug level to the verbosity option debug_levels = { 0: logging.ERROR, 1: logging.WARNING, 2: logging.INFO, 3: logging.DEBUG } logging.getLogger().setLevel( debug_levels.get(options['verbosity'], logging.DEBUG) ) # reduce size of parse pool early on self.name = self.__class__.__module__.split('.')[-1] self.projects = options.pop('projects', []) self.languages = options.pop('languages', []) if self.projects: self.check_projects(self.projects) if self.languages: self.check_languages(self.languages) # info start start = datetime.datetime.now() logger.info('[pootle] Running: %s', self.name) self.handle_all(**options) # info finish end = datetime.datetime.now() logging.info('[pootle] Complete: %s in %s', self.name, end - start) def handle_all(self, **options): if options["no_rq"]: set_sync_mode(options['noinput']) if options["atomic"] == "tp": self._handle_atomic_tps(**options) else: self._handle_tps(**options) def _handle_tps(self, **options): projects = Project.objects.select_related( *self.project_related).order_by("code").all() if self.projects: projects = projects.filter(code__in=self.projects) if not self.process_disabled_projects: projects = projects.exclude(disabled=True) for project in projects.iterator(): tps = project.translationproject_set.live().order_by( "language__code").select_related(*self.tp_related) if self.languages: tps = tps.filter(language__code__in=self.languages) for tp in tps.iterator(): self.do_translation_project(tp, **options) def _handle_atomic_tps(self, **options): related = [ ("project__%s" % project_related) for project_related in self.project_related] related += list(self.tp_related) tps = TranslationProject.objects.select_related( *related).order_by("project__code", "language__code").all() if self.projects: tps = tps.filter(project__code__in=self.projects) if not self.process_disabled_projects: tps = tps.exclude(project__disabled=True) if self.languages: tps = tps.filter(language__code__in=self.languages) for tp in tps.iterator(): with transaction.atomic(): self.do_translation_project(tp, **options)
7,156
Python
.py
173
30.820809
79
0.591308
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,235
update_tmserver.py
translate_pootle/pootle/apps/pootle_app/management/commands/update_tmserver.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import os from hashlib import md5 # This must be run before importing Django. os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings' from elasticsearch import Elasticsearch, helpers from translate.storage import factory from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django.utils import dateparse from django.utils.encoding import force_bytes from pootle.core.utils import dateformat from pootle_store.models import Unit from pootle_translationproject.models import TranslationProject BULK_CHUNK_SIZE = 5000 class BaseParser(object): def __init__(self, *args, **kwargs): """Initialize the parser.""" self.stdout = kwargs.pop('stdout') self.INDEX_NAME = kwargs.pop('index', None) def get_units(self): """Gets the units to import and its total count.""" raise NotImplementedError def get_unit_data(self, unit): """Return dict with data to import for a single unit.""" raise NotImplementedError class DBParser(BaseParser): def __init__(self, *args, **kwargs): super(DBParser, self).__init__(*args, **kwargs) self.exclude_disabled_projects = not kwargs.pop('disabled_projects') self.tp_pk = None def get_units(self): """Gets the units to import and its total count.""" units_qs = ( Unit.objects.exclude(target_f__isnull=True) .exclude(target_f__exact='') .filter(store__translation_project__pk=self.tp_pk) .filter(revision__gt=self.last_indexed_revision)) units_qs = units_qs.select_related( 'change__submitted_by', 'store', 'store__translation_project__project', 'store__translation_project__language') if self.exclude_disabled_projects: units_qs = units_qs.exclude( store__translation_project__project__disabled=True ).exclude(store__obsolete=True) units_qs = units_qs.values( 'id', 'revision', 'source_f', 'target_f', 'change__submitted_on', 'change__submitted_by__username', 'change__submitted_by__full_name', 'change__submitted_by__email', 'store__translation_project__project__fullname', 'store__pootle_path', 'store__translation_project__language__code' ).order_by() return units_qs.iterator(), units_qs.count() def get_unit_data(self, unit): """Return dict with data to import for a single unit.""" fullname = (unit['change__submitted_by__full_name'] or unit['change__submitted_by__username']) email_md5 = None if unit['change__submitted_by__email']: email_md5 = md5( force_bytes(unit['change__submitted_by__email'])).hexdigest() iso_submitted_on = unit.get('change__submitted_on', None) display_submitted_on = None if iso_submitted_on: display_submitted_on = dateformat.format( dateparse.parse_datetime(str(iso_submitted_on)) ) return { '_index': self.INDEX_NAME, '_type': unit['store__translation_project__language__code'], '_id': unit['id'], 'revision': int(unit['revision']), 'project': unit['store__translation_project__project__fullname'], 'path': unit['store__pootle_path'], 'username': unit['change__submitted_by__username'], 'fullname': fullname, 'email_md5': email_md5, 'source': unit['source_f'], 'target': unit['target_f'], 'iso_submitted_on': iso_submitted_on, 'display_submitted_on': display_submitted_on, } class FileParser(BaseParser): def __init__(self, *args, **kwargs): super(FileParser, self).__init__(*args, **kwargs) self.target_language = kwargs.pop('language', None) self.project = kwargs.pop('project', None) self.filenames = kwargs.pop('filenames') def get_units(self): """Gets the units to import and its total count.""" units = [] all_filenames = set() for filename in self.filenames: if not os.path.exists(filename): self.stdout.write("File %s doesn't exist. Skipping it." % filename) continue if os.path.isdir(filename): for dirpath, dirs_, fnames in os.walk(filename): if (os.path.basename(dirpath) in ["CVS", ".svn", "_darcs", ".git", ".hg", ".bzr"]): continue for f in fnames: all_filenames.add(os.path.join(dirpath, f)) else: all_filenames.add(filename) for filename in all_filenames: store = factory.getobject(filename) if not store.gettargetlanguage() and not self.target_language: raise CommandError("Unable to determine target language for " "'%s'. Try again specifying a fallback " "target language with --target-language" % filename) self.filename = filename units.extend([unit for unit in store.units if unit.istranslated()]) return units, len(units) def get_unit_data(self, unit): """Return dict with data to import for a single unit.""" target_language = unit.gettargetlanguage() if target_language is None: target_language = self.target_language return { '_index': self.INDEX_NAME, '_type': target_language, '_id': unit.getid(), 'revision': 0, 'project': self.project, 'path': self.filename, 'username': None, 'fullname': None, 'email_md5': None, 'source': unit.source, 'target': unit.target, 'iso_submitted_on': None, 'display_submitted_on': None, } class Command(BaseCommand): help = "Load Translation Memory with translations" def add_arguments(self, parser): parser.add_argument( '--refresh', action='store_true', dest='refresh', default=False, help='Process all items, not just the new ones, so ' 'existing translations are refreshed' ) parser.add_argument( '--rebuild', action='store_true', dest='rebuild', default=False, help='Drop the entire TM on start and update everything ' 'from scratch' ) parser.add_argument( '--dry-run', action='store_true', dest='dry_run', default=False, help='Report the number of translations to index and quit' ) # Local TM specific options. local = parser.add_argument_group('Local TM', 'Pootle Local ' 'Translation Memory') local.add_argument( '--include-disabled-projects', action='store_true', dest='disabled_projects', default=False, help='Add translations from disabled projects' ) # External TM specific options. external = parser.add_argument_group('External TM', 'Pootle External ' 'Translation Memory') external.add_argument( nargs='*', dest='files', help='Translation memory files', ) external.add_argument( '--tm', action='store', dest='tm', default='local', help="TM to use. TM must exist on settings. TM will be " "created on the server if it doesn't exist" ) external.add_argument( '--target-language', action='store', dest='target_language', default='', help="Target language to fallback to use in case it can't " "be guessed for any of the input files." ) external.add_argument( '--display-name', action='store', dest='project', default='', help='Name used when displaying TM matches for these ' 'translations.' ) def _parse_translations(self, **options): units, total = self.parser.get_units() if total == 0: self.stdout.write("No translations to index") return self.stdout.write("%s translations to index" % total) if options['dry_run']: return self.stdout.write("") i = 0 for i, unit in enumerate(units, start=1): if (i % 1000 == 0) or (i == total): percent = "%.1f" % (i * 100.0 / total) self.stdout.write("%s (%s%%)" % (i, percent), ending='\r') self.stdout.flush() yield self.parser.get_unit_data(unit) if i != total: self.stdout.write("Expected %d, loaded %d." % (total, i)) def _initialize(self, **options): if not settings.POOTLE_TM_SERVER: raise CommandError('POOTLE_TM_SERVER setting is missing.') try: self.tm_settings = settings.POOTLE_TM_SERVER[options['tm']] except KeyError: raise CommandError("Translation Memory '%s' is not defined in the " "POOTLE_TM_SERVER setting. Please ensure it " "exists and double-check you typed it " "correctly." % options['tm']) self.INDEX_NAME = self.tm_settings['INDEX_NAME'] self.is_local_tm = options['tm'] == 'local' self.es = Elasticsearch([ { 'host': self.tm_settings['HOST'], 'port': self.tm_settings['PORT'], }], retry_on_timeout=True ) # If files to import have been provided. if options['files']: if self.is_local_tm: raise CommandError('You cannot add translations from files to ' 'a local TM.') if not options['project']: raise CommandError('You must specify a project name with ' '--display-name.') self.parser = FileParser(stdout=self.stdout, index=self.INDEX_NAME, filenames=options['files'], language=options['target_language'], project=options['project']) elif not self.is_local_tm: raise CommandError('You cannot add translations from database to ' 'an external TM.') else: self.parser = DBParser( stdout=self.stdout, index=self.INDEX_NAME, disabled_projects=options['disabled_projects']) def _set_latest_indexed_revision(self, **options): self.last_indexed_revision = -1 if (not options['rebuild'] and not options['refresh'] and self.es.indices.exists(self.INDEX_NAME)): result = self.es.search( index=self.INDEX_NAME, body={ 'aggs': { 'max_revision': { 'max': { 'field': 'revision' } } } } ) self.last_indexed_revision = \ result['aggregations']['max_revision']['value'] or -1 self.parser.last_indexed_revision = self.last_indexed_revision self.stdout.write("Last indexed revision = %s" % self.last_indexed_revision) def handle(self, **options): self._initialize(**options) if (options['rebuild'] and not options['dry_run'] and self.es.indices.exists(self.INDEX_NAME)): self.es.indices.delete(index=self.INDEX_NAME) if (not options['dry_run'] and not self.es.indices.exists(self.INDEX_NAME)): self.es.indices.create(index=self.INDEX_NAME) if self.is_local_tm: self._set_latest_indexed_revision(**options) if isinstance(self.parser, FileParser): helpers.bulk(self.es, self._parse_translations(**options)) return # If we are parsing from DB. tp_qs = TranslationProject.objects.all() if options['disabled_projects']: tp_qs = tp_qs.exclude(project__disabled=True) for tp in tp_qs: self.parser.tp_pk = tp.pk helpers.bulk(self.es, self._parse_translations(**options))
13,500
Python
.py
316
29.901899
79
0.544962
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,236
initdb.py
translate_pootle/pootle/apps/pootle_app/management/commands/initdb.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import os # This must be run before importing Django. os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings' from django.core.management.base import BaseCommand from pootle.core.initdb import InitDB from . import SkipChecksMixin class Command(SkipChecksMixin, BaseCommand): help = 'Populates the database with initial values: users, projects, ...' skip_system_check_tags = ('data', ) def add_arguments(self, parser): parser.add_argument( '--no-projects', action='store_false', dest='create_projects', default=True, help="Do not create the default 'terminology' and 'tutorial' " "projects.", ) def handle(self, **options): self.stdout.write('Populating the database.') InitDB().init_db(options["create_projects"]) self.stdout.write('Successfully populated the database.') self.stdout.write("To create an admin user, use the `pootle " "createsuperuser` command.")
1,314
Python
.py
31
35.741935
77
0.67451
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,237
list_languages.py
translate_pootle/pootle/apps/pootle_app/management/commands/list_languages.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import os os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings' from django.core.management.base import BaseCommand class Command(BaseCommand): help = "List language codes." def add_arguments(self, parser): parser.add_argument( '--project', action='append', dest='projects', help='Limit to PROJECTS', ) parser.add_argument( "--modified-since", action="store", dest="modified_since", type=int, default=0, help="Only process translations newer than specified " "revision", ) def handle(self, **options): self.list_languages(**options) def list_languages(self, **options): """List all languages on the server or the given projects.""" from pootle_translationproject.models import TranslationProject tps = TranslationProject.objects.distinct() tps = tps.exclude( language__code='templates').order_by('language__code') if options['modified_since'] > 0: tps = tps.filter( submission__unit__revision__gt=options['modified_since']) if options['projects']: tps = tps.filter(project__code__in=options['projects']) for lang in tps.values_list('language__code', flat=True): self.stdout.write(lang)
1,687
Python
.py
43
30.72093
77
0.624235
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,238
revision.py
translate_pootle/pootle/apps/pootle_app/management/commands/revision.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import os os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings' from django.core.management.base import BaseCommand from pootle.core.models import Revision from . import SkipChecksMixin class Command(SkipChecksMixin, BaseCommand): help = "Print Pootle's current revision." skip_system_check_tags = ('data', ) def add_arguments(self, parser): parser.add_argument( '--restore', action='store_true', default=False, dest='restore', help='Restore the current revision number from the DB.', ) def handle(self, **options): if options['restore']: from pootle_store.models import Unit Revision.set(Unit.max_revision()) self.stdout.write('%s' % Revision.get())
1,070
Python
.py
28
32.178571
77
0.677638
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,239
flush_cache.py
translate_pootle/pootle/apps/pootle_app/management/commands/flush_cache.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import os import sys # This must be run before importing Django. os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings' from django.core.management.base import BaseCommand, CommandError from django_redis import get_redis_connection from pootle.core.models import Revision from pootle.core.utils.redis_rq import rq_workers_are_running from pootle_store.models import Unit class Command(BaseCommand): help = """Flush cache.""" def add_arguments(self, parser): parser.add_argument( '--django-cache', action='store_true', dest='flush_django_cache', default=False, help='Flush Django default cache.', ) parser.add_argument( '--rqdata', action='store_true', dest='flush_rqdata', default=False, help=("Flush revision counter and all RQ data (queues, pending or " "failed jobs). Revision counter is restores automatically."), ) parser.add_argument( '--lru', action='store_true', dest='flush_lru', default=False, help="Flush lru cache.", ) parser.add_argument( '--all', action='store_true', dest='flush_all', default=False, help='Flush all caches data.', ) def handle(self, **options): if (not options['flush_rqdata'] and not options['flush_lru'] and not options['flush_django_cache'] and not options['flush_all']): raise CommandError("No options were provided. Use one of " "--django-cache, --rqdata, --lru " "or --all.") if options['flush_rqdata'] or options['flush_all']: if rq_workers_are_running(): self.stdout.write("Nothing has been flushed. " "Stop RQ workers before running this " "command with --rqdata or --all option.") sys.exit() self.stdout.write('Flushing cache...') if options['flush_rqdata'] or options['flush_all']: # Flush all rq data, dirty counter and restore Pootle revision # value. r_con = get_redis_connection('redis') r_con.flushdb() self.stdout.write('RQ data removed.') Revision.set(Unit.max_revision()) self.stdout.write('Max unit revision restored.') if options['flush_django_cache'] or options['flush_all']: r_con = get_redis_connection('default') r_con.flushdb() self.stdout.write('All default Django cache data removed.') if options['flush_lru'] or options['flush_all']: r_con = get_redis_connection('lru') r_con.flushdb() self.stdout.write('All lru cache data removed.')
3,246
Python
.py
79
30.303797
79
0.577996
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,240
refresh_scores.py
translate_pootle/pootle/apps/pootle_app/management/commands/refresh_scores.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import os os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings' from django.contrib.auth import get_user_model from pootle.core.delegate import score_updater from pootle_translationproject.models import TranslationProject from . import PootleCommand class Command(PootleCommand): help = "Refresh score" def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument( '--reset', action='store_true', dest='reset', default=False, help='Reset all scores to zero', ) parser.add_argument( '--user', action='append', dest='users', help='User to refresh', ) def get_users(self, **options): return ( list(get_user_model().objects.filter( username__in=options["users"]).values_list("pk", flat=True)) if options["users"] else None) def handle_all_stores(self, translation_project, **options): users = self.get_users(**options) updater = score_updater.get(TranslationProject)(translation_project) if options["reset"]: updater.clear(users) else: updater.refresh_scores(users) def handle_all(self, **options): if not self.projects and not self.languages: users = self.get_users(**options) if options["reset"]: score_updater.get(get_user_model())(users=users).clear() else: score_updater.get(get_user_model())().refresh_scores(users) else: super(Command, self).handle_all(**options)
1,970
Python
.py
52
29.384615
77
0.622642
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,241
test_checks.py
translate_pootle/pootle/apps/pootle_app/management/commands/test_checks.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import logging import os os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings' from translate.filters.checks import FilterFailure, projectcheckers from django.core.management.base import CommandError, BaseCommand from pootle_checks.utils import get_qualitychecks from pootle_store.models import Unit class Command(BaseCommand): help = "Tests quality checks against string pairs." def add_arguments(self, parser): parser.add_argument( '--check', action='append', dest='checks', help='Check name to check for', ) parser.add_argument( '--source', dest='source', help='Source string', ) parser.add_argument( '--unit', dest='unit', help='Unit id', ) parser.add_argument( '--target', dest='target', help='Translation string', ) def handle(self, **options): # adjust debug level to the verbosity option debug_levels = { 0: logging.ERROR, 1: logging.WARNING, 2: logging.INFO, 3: logging.DEBUG } debug_level = debug_levels.get(options['verbosity'], logging.DEBUG) logging.getLogger().setLevel(debug_level) self.name = self.__class__.__module__.split('.')[-1] if ((options['unit'] is not None and (options['source'] or options['target'])) or (options['unit'] is None and not options['source'] and not options['target'])): raise CommandError("Either --unit or a pair of --source " "and --target must be provided.") if bool(options['source']) != bool(options['target']): raise CommandError("Use a pair of --source and --target.") checks = options.get('checks', []) if options['unit'] is not None: try: unit = Unit.objects.get(id=options['unit']) source = unit.source target = unit.target except Unit.DoesNotExist as e: raise CommandError(e) else: source = options['source'].decode('utf-8') target = options['target'].decode('utf-8') checkers = [checker() for checker in projectcheckers.values()] if not checks: checks = get_qualitychecks().keys() error_checks = [] for checker in checkers: for check in checks: filtermessage = '' filterresult = True if check in error_checks: continue try: if hasattr(checker, check): test = getattr(checker, check) try: filterresult = test(source, target) except AttributeError: continue except FilterFailure as e: filterresult = False filtermessage = unicode(e) message = "%s - %s" % (filterresult, check) if filtermessage: message += ": %s" % filtermessage logging.info(message) if not filterresult: error_checks.append(check) if error_checks: self.stdout.write('Failing checks: %s' % ', '.join(error_checks)) else: self.stdout.write('No errors found.')
3,853
Python
.py
99
26.838384
77
0.540541
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,242
calculate_checks.py
translate_pootle/pootle/apps/pootle_app/management/commands/calculate_checks.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import os # This must be run before importing Django. os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings' from pootle.core.signals import update_checks from pootle_translationproject.models import TranslationProject from . import PootleCommand class Command(PootleCommand): help = "Allow checks to be recalculated manually." process_disabled_projects = True def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument( '--check', action='append', dest='check_names', default=None, help='Check to recalculate', ) def update_checks(self, check_names, translation_project=None): update_checks.send( TranslationProject, check_names=check_names, instance=translation_project, clear_unknown=True, update_data_after=True) def handle_all_stores(self, translation_project, **options): self.stdout.write(u"Running %s for %s" % (self.name, translation_project)) self.update_checks(options["check_names"], translation_project) def handle_all(self, **options): if not self.projects and not self.languages: self.stdout.write(u"Running %s (noargs)" % self.name) self.update_checks(options["check_names"]) else: super(Command, self).handle_all(**options)
1,735
Python
.py
42
33.642857
77
0.666667
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,243
schema.py
translate_pootle/pootle/apps/pootle_app/management/commands/schema.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import os os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings' from django.core.management.base import CommandError from pootle.core.management.subcommands import CommandWithSubcommands from pootle.core.schema.base import SchemaTool, UnsupportedDBError from pootle.core.schema.dump import (SchemaAppDump, SchemaDump, SchemaTableDump) from .schema_commands import SchemaAppCommand, SchemaTableCommand class Command(CommandWithSubcommands): help = "Pootle schema state command." requires_system_checks = False subcommands = { "app": SchemaAppCommand, "table": SchemaTableCommand, } def add_arguments(self, parser): dump_or_tables = parser.add_mutually_exclusive_group() dump_or_tables.add_argument( '--dump', action='store_true', default=False, dest='dump', help='Print schema settings.', ) dump_or_tables.add_argument( '--tables', action='store_true', default=False, dest='tables', help='Print all table names.', ) super(Command, self).add_arguments(parser) def handle(self, **options): try: schema_tool = SchemaTool() except UnsupportedDBError as e: raise CommandError(e) result = SchemaDump() if options['tables']: result.set_table_list(schema_tool.get_tables()) self.stdout.write(str(result)) else: result.load({ 'defaults': schema_tool.get_defaults()}) for app_label in schema_tool.app_configs: app_dump = SchemaAppDump(app_label) table_names = schema_tool.get_app_tables(app_label) for table_name in table_names: table_dump = SchemaTableDump(table_name) table_dump.load({ 'fields': schema_tool.get_table_fields(table_name), 'indices': schema_tool.get_table_indices(table_name), 'constraints': schema_tool.get_table_constraints(table_name)}) app_dump.add_table(table_dump) if table_names: result.add_app(app_dump) self.stdout.write(str(result))
2,668
Python
.py
65
30.184615
77
0.603242
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,244
contributors.py
translate_pootle/pootle/apps/pootle_app/management/commands/contributors.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import os from argparse import ArgumentTypeError from dateutil.parser import parse as parse_datetime from email.utils import formataddr os.environ["DJANGO_SETTINGS_MODULE"] = "pootle.settings" from pootle.core.delegate import contributors from pootle.core.utils.timezone import make_aware from . import PootleCommand def get_aware_datetime(dt_string, tz=None): """Return an aware datetime parsed from a datetime or date string. :param dt_string: datetime or date string can be any format parsable by dateutil.parser.parse. :param tz: timezone in which `dt_string` should be considered. """ if not dt_string: return None try: return make_aware(parse_datetime(dt_string), tz=tz) except ValueError: raise ArgumentTypeError('The provided datetime/date string is not ' 'valid: "%s"' % dt_string) class Command(PootleCommand): help = "Print a list of contributors." requires_system_checks = False def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument( "--since", type=get_aware_datetime, action="store", dest="since", help=('ISO 8601 format: 2016-01-24T23:15:22+0000 or ' '"2016-01-24 23:15:22 +0000" or "2016-01-24"'), ) parser.add_argument( "--until", type=get_aware_datetime, action="store", dest="until", help=('ISO 8601 format: 2016-01-24T23:15:22+0000 or ' '"2016-01-24 23:15:22 +0000" or "2016-01-24"'), ) parser.add_argument( "--sort-by", default="username", choices=["username", "contributions"], dest="sort_by", help="Sort by specified item. Accepts: %(choices)s. " "Default: %(default)s", ) anon_or_mailmerge = parser.add_mutually_exclusive_group(required=False) anon_or_mailmerge.add_argument( "--include-anonymous", action="store_true", dest="include_anon", help="Include anonymous contributions.", ) anon_or_mailmerge.add_argument( "--mailmerge", action="store_true", dest="mailmerge", help="Output only names and email addresses. Contribution counts " "are excluded.", ) @property def contributors(self): return contributors.get() def contrib_kwargs(self, **options): kwargs = { k: v for k, v in options.items() if k in ["projects", "languages", "include_anon", "since", "until", "sort_by"]} kwargs["project_codes"] = kwargs.pop("projects", None) kwargs["language_codes"] = kwargs.pop("languages", None) return kwargs def handle(self, **options): contributors = self.contributors(**self.contrib_kwargs(**options)) for username, user in contributors.items(): name = user["full_name"].strip() or username if options["mailmerge"]: email = user["email"].strip() if email: self.stdout.write(formataddr((name, email))) else: self.stdout.write("%s (%s contributions)" % (name, user["contributions"]))
3,767
Python
.py
96
29.416667
79
0.589281
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,245
dump.py
translate_pootle/pootle/apps/pootle_app/management/commands/dump.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import os import sys reload(sys) sys.setdefaultencoding('utf-8') os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings' from django.core.management.base import CommandError from pootle_app.management.commands import PootleCommand from pootle_app.models import Directory from pootle_language.models import Language from pootle_project.models import Project from pootle_translationproject.models import TranslationProject DUMPED = { 'TranslationProject': ('pootle_path', 'disabled'), 'Store': ('translation_project', 'pootle_path', 'name', 'state'), 'Directory': ('name', 'parent', 'pootle_path'), 'Unit': ('source', 'target', 'target_wordcount', 'developer_comment', 'translator_comment', 'locations', 'isobsolete', 'isfuzzy', 'istranslated'), 'UnitSource': ('source_wordcount', ), 'Suggestion': ('target_f', 'user_id'), 'Language': ('code', 'fullname', 'pootle_path'), 'Project': ('code', 'fullname', 'checkstyle', 'source_language', 'ignoredfiles', 'screenshot_search_prefix', 'disabled') } class Command(PootleCommand): help = "Dump data." def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument( '--stats', action='store_true', dest='stats', default=False, help='Dump stats', ) parser.add_argument( '--data', action='store_true', dest='data', default=False, help='Data all data', ) parser.add_argument( '--stop-level', action='store', dest='stop_level', default=-1, type=int, help="Depth of data to retrieve", ) def handle_all(self, **options): if not self.projects and not self.languages: if options['stats']: self.dump_stats(stop_level=options['stop_level']) return if options['data']: self.dump_all(stop_level=options['stop_level']) return raise CommandError("Set --data or --stats option.") else: super(Command, self).handle_all(**options) def handle_translation_project(self, tp, **options): if options['stats']: res = {} self._dump_stats(tp.directory, res, stop_level=options['stop_level']) return if options['data']: self._dump_item(tp.directory, 0, stop_level=options['stop_level']) return raise CommandError("Set --data or --stats option.") def dump_stats(self, stop_level): res = {} for prj in Project.objects.all(): self._dump_stats(prj, res, stop_level=stop_level) def _dump_stats(self, item, res, stop_level): key = item.pootle_path item.initialize_children() if stop_level != 0 and item.children: if stop_level > 0: stop_level = stop_level - 1 for child in item.children: self._dump_stats(child, res, stop_level=stop_level) res[key] = (item.data_tool.get_stats(include_children=False)) if res[key]['last_submission']: if 'id' in res[key]['last_submission']: last_submission_id = res[key]['last_submission']['id'] else: last_submission_id = None else: last_submission_id = None if res[key]['last_created_unit']: if 'id' in res[key]['last_created_unit']: last_updated_id = res[key]['last_created_unit']['id'] else: last_updated_id = None else: last_updated_id = None out = u"%s %s,%s,%s,%s,%s,%s,%s" % \ (key, res[key]['total'], res[key]['translated'], res[key]['fuzzy'], res[key]['suggestions'], res[key]['critical'], last_submission_id, last_updated_id) self.stdout.write(out) def dump_all(self, stop_level): root = Directory.objects.root self._dump_item(root, 0, stop_level=stop_level) def _dump_item(self, item, level, stop_level): self.stdout.write(self.dumped(item)) if isinstance(item, Directory): pass elif isinstance(item, Language): self.stdout.write(self.dumped(item.language)) elif isinstance(item, TranslationProject): if hasattr(item, 'translationproject'): self.stdout.write(self.dumped(item.translationproject)) elif isinstance(item, Project): pass # self.stdout.write(self.dumped(item)) else: # item should be a Store for unit in item.units: self.stdout.write(self.dumped(unit)) for sg in unit.get_suggestions(): self.stdout.write(self.dumped(sg)) if stop_level != level: item.initialize_children() if item.children: for child in item.children: self._dump_item(child, level + 1, stop_level=stop_level) def dumped(self, item): def get_param(param): p = getattr(item, param) res = p() if callable(p) else p res = u"%s" % res res = res.replace('\n', '\\n') return (param, res) return u"%d:%s\t%s" % \ ( item.id, item._meta.object_name, "\t".join( u"%s=%s" % (k, v) for k, v in map(get_param, DUMPED[item._meta.object_name]) ) )
6,099
Python
.py
155
28.516129
78
0.555537
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,246
__init__.py
translate_pootle/pootle/apps/pootle_app/management/commands/schema_commands/__init__.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import os os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings' from django.core.management.base import BaseCommand, CommandError from pootle.core.schema.base import SchemaTool, UnsupportedDBError from pootle.core.schema.dump import (SchemaAppDump, SchemaDump, SchemaTableDump) class SchemaCommand(BaseCommand): def add_arguments(self, parser): parser.add_argument( '--fields', action='store_true', default=False, help='Table fields.', ) parser.add_argument( '--indices', action='store_true', default=False, help='Table indices.', ) parser.add_argument( '--constraints', action='store_true', default=False, help='Table constraints.', ) super(SchemaCommand, self).add_arguments(parser) def handle_table(self, table_name, **options): result = SchemaTableDump(table_name) all_options = ( not options['fields'] and not options['indices'] and not options['constraints'] ) if options['fields'] or all_options: result.load({ 'fields': self.schema_tool.get_table_fields(table_name)}) if options['indices'] or all_options: result.load({ 'indices': self.schema_tool.get_table_indices(table_name)}) if options['constraints'] or all_options: result.load({ 'constraints': self.schema_tool.get_table_constraints(table_name)}) return result class SchemaTableCommand(SchemaCommand): def add_arguments(self, parser): parser.add_argument( 'args', metavar='table_name', nargs='+', help='Table names.' ) super(SchemaTableCommand, self).add_arguments(parser) def handle(self, *args, **options): try: self.schema_tool = SchemaTool() except UnsupportedDBError as e: raise CommandError(e) all_tables = self.schema_tool.get_tables() if not set(args).issubset(set(all_tables)): raise CommandError("Unrecognized tables: %s" % list(set(args) - set(all_tables))) result = SchemaDump() for table_name in args: app_label = self.schema_tool.get_app_by_table(table_name) if not result.app_exists(app_label): app_result = SchemaAppDump(app_label) result.add_app(app_result) else: app_result = result.get_app(app_label) app_result.add_table( self.handle_table(table_name, **options)) self.stdout.write(str(result)) class SchemaAppCommand(SchemaCommand): def add_arguments(self, parser): parser.add_argument( 'args', metavar='app_label', nargs='+', help='Application labels.' ) parser.add_argument( '--tables', action='store_true', default=False, dest='tables', help='Print all table names.', ) super(SchemaAppCommand, self).add_arguments(parser) def handle(self, *args, **options): try: self.schema_tool = SchemaTool(*args) except (LookupError, ImportError) as e: raise CommandError("%s. Are you sure your INSTALLED_APPS " "setting is correct?" % e) except UnsupportedDBError as e: raise CommandError(e) if options['tables']: result = SchemaDump() for app_label in args: result.set_table_list( self.schema_tool.get_app_tables(app_label)) self.stdout.write(str(result)) else: result = SchemaDump() for app_label in args: app_result = SchemaAppDump(app_label) for table_name in self.schema_tool.get_app_tables(app_label): app_result.add_table( self.handle_table(table_name, **options)) result.add_app(app_result) self.stdout.write(str(result))
4,623
Python
.py
120
27.208333
77
0.569804
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,247
models.py
translate_pootle/pootle/apps/pootle_statistics/models.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django.conf import settings from django.contrib.auth import get_user_model from django.db import models from django.template.defaultfilters import truncatechars from django.urls import reverse from pootle.core.user import get_system_user from pootle.core.utils import dateformat from pootle.i18n.gettext import ugettext_lazy as _ from pootle_checks.constants import CHECK_NAMES from pootle_store.constants import FUZZY, TRANSLATED from pootle_store.fields import to_python MUTED = "0" SIMILARITY_THRESHOLD = 0.5 UNMUTED = "1" #: These are the values for the 'type' field of Submission class SubmissionTypes(object): # None/0 = no information WEB = 1 # Interactive web editing UPLOAD = 4 # Uploading an offline file SYSTEM = 5 # Batch actions performed offline # Combined types that rely on other types (useful for querying) # Please use the `_TYPES` suffix to make it clear they're not core # types that are stored in the DB EDIT_TYPES = [WEB, SYSTEM, UPLOAD] CONTRIBUTION_TYPES = [WEB, SYSTEM] #: Values for the 'field' field of Submission class SubmissionFields(object): NONE = 0 # non-field submission SOURCE = 1 # pootle_store.models.Unit.source TARGET = 2 # pootle_store.models.Unit.target STATE = 3 # pootle_store.models.Unit.state COMMENT = 4 # pootle_store.models.Unit.translator_comment CHECK = 5 TRANSLATION_FIELDS = [TARGET] NAMES_MAP = { NONE: "", SOURCE: _("Source"), TARGET: _("Target"), STATE: _("State"), COMMENT: _("Comment"), CHECK: (_("Check")), } class TranslationActionTypes(object): TRANSLATED = 0 EDITED = 1 PRE_TRANSLATED = 2 REMOVED = 3 REVIEWED = 4 NEEDS_WORK = 5 class SubmissionQuerySet(models.QuerySet): def _earliest_or_latest(self, field_name=None, direction="-"): """ Overrides QuerySet._earliest_or_latest to add pk for secondary ordering """ order_by = field_name or getattr(self.model._meta, 'get_latest_by') assert bool(order_by), "earliest() and latest() require either a "\ "field_name parameter or 'get_latest_by' in the model" assert self.query.can_filter(), \ "Cannot change a query once a slice has been taken." obj = self._clone() obj.query.set_limits(high=1) obj.query.clear_ordering(force_empty=True) # add pk as secondary ordering for Submissions obj.query.add_ordering('%s%s' % (direction, order_by), '%s%s' % (direction, "pk")) return obj.get() def earliest(self, field_name=None): return self._earliest_or_latest(field_name=field_name, direction="") def latest(self, field_name=None): return self._earliest_or_latest(field_name=field_name, direction="-") class SubmissionManager(models.Manager): def get_queryset(self): return SubmissionQuerySet(self.model, using=self._db) def get_unit_comments(self): """Submissions that change a `Unit`'s comment. :return: Queryset of `Submissions`s that change a `Unit`'s comment. """ return self.get_queryset().filter(field=SubmissionFields.COMMENT) def get_unit_edits(self): """`Submission`s that change a `Unit`'s `target`. :return: Queryset of `Submissions`s that change a `Unit`'s target. """ return ( self.get_queryset().exclude(new_value__isnull=True).filter( field__in=SubmissionFields.TRANSLATION_FIELDS, type__in=SubmissionTypes.EDIT_TYPES, ) ) def get_unit_state_changes(self): """Submissions that change a unit's STATE. :return: Queryset of `Submissions`s change a `Unit`'s `STATE` - ie FUZZY/TRANSLATED/UNTRANSLATED. """ return self.get_queryset().filter(field=SubmissionFields.STATE) def get_unit_suggestion_reviews(self): """Submissions that review (reject/accept) `Unit` suggestions. :return: Queryset of `Submissions`s that `REJECT`/`ACCEPT` `Suggestion`s. """ # reject_suggestion does not set field so we must exclude STATE reviews # and it seems there are submissions that use STATE and are in # REVIEW_TYPES return (self.get_queryset().exclude( field=SubmissionFields.STATE).filter( suggestion__isnull=False)) class Submission(models.Model): class Meta(object): ordering = ["creation_time", "pk"] index_together = ["submitter", "creation_time"] get_latest_by = "creation_time" db_table = 'pootle_app_submission' base_manager_name = 'objects' objects = SubmissionManager() creation_time = models.DateTimeField(db_index=True) translation_project = models.ForeignKey( 'pootle_translationproject.TranslationProject', db_index=True, on_delete=models.CASCADE) submitter = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, db_index=False, on_delete=models.SET(get_system_user)) suggestion = models.ForeignKey('pootle_store.Suggestion', blank=True, null=True, db_index=True, on_delete=models.CASCADE) unit = models.ForeignKey( 'pootle_store.Unit', db_index=True, on_delete=models.CASCADE) quality_check = models.ForeignKey('pootle_store.QualityCheck', blank=True, null=True, db_index=True, on_delete=models.CASCADE) #: The field in the unit that changed field = models.IntegerField(null=True, blank=True, db_index=True) # how did this submission come about? (one of the constants above) type = models.IntegerField(null=True, blank=True, db_index=True) # old_value and new_value can store string representations of multistrings # in the case where they store values for a unit's source or target. In # such cases, the strings might not be usable as is. Use the two helper # functions in pootle_store.fields to convert to and from this format. old_value = models.TextField(blank=True, default=u"") new_value = models.TextField(blank=True, default=u"") # Unit revision when submission was created if applicable revision = models.IntegerField( null=True, db_index=True, blank=True) def __unicode__(self): return u"%s (%s)" % (self.creation_time.strftime("%Y-%m-%d %H:%M"), unicode(self.submitter)) def get_submission_info(self): """Returns a dictionary describing the submission. The dict includes the user (with link to profile and gravatar), a type and translation_action_type describing the action performed, and when it was performed. """ result = {} if self.unit is not None: result.update({ 'unit_source': truncatechars(self.unit, 50), 'unit_url': self.unit.get_translate_url(), }) if self.quality_check is not None: check_name = self.quality_check.name result.update({ 'check_name': check_name, 'check_display_name': CHECK_NAMES.get(check_name, check_name), 'checks_url': reverse('pootle-checks-descriptions'), }) # Sadly we may not have submitter information in all the # situations yet # TODO check if it is true if self.submitter: displayuser = self.submitter else: User = get_user_model() displayuser = User.objects.get_nobody_user() result.update({ "profile_url": displayuser.get_absolute_url(), "email": displayuser.email_hash, "displayname": displayuser.display_name, "username": displayuser.username, "display_datetime": dateformat.format(self.creation_time), "type": self.type, "mtime": int(dateformat.format(self.creation_time, 'U')), }) # TODO Fix bug 3011 and remove the following code related to # TranslationActionTypes. if self.type in SubmissionTypes.EDIT_TYPES: translation_action_type = None try: if self.field == SubmissionFields.TARGET: if self.new_value != '': # Note that we analyze current unit state: # if this submission is not last unit state # can be changed if self.unit.state == TRANSLATED: if self.old_value == '': translation_action_type = \ TranslationActionTypes.TRANSLATED else: translation_action_type = \ TranslationActionTypes.EDITED elif self.unit.state == FUZZY: if self.old_value == '': translation_action_type = \ TranslationActionTypes.PRE_TRANSLATED else: translation_action_type = \ TranslationActionTypes.EDITED else: translation_action_type = \ TranslationActionTypes.REMOVED elif self.field == SubmissionFields.STATE: # Note that a submission where field is STATE # should be created before a submission where # field is TARGET translation_action_type = { TRANSLATED: TranslationActionTypes.REVIEWED, FUZZY: TranslationActionTypes.NEEDS_WORK }.get(int(to_python(self.new_value)), None) except AttributeError: return result if translation_action_type is not None: result['translation_action_type'] = translation_action_type return result def save(self, *args, **kwargs): if self.unit: self.revision = self.unit.revision super(Submission, self).save(*args, **kwargs)
10,870
Python
.py
238
34.323529
79
0.603251
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,248
getters.py
translate_pootle/pootle/apps/pootle_statistics/getters.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from pootle.core.delegate import contributors from pootle.core.plugin import getter from .utils import Contributors @getter(contributors) def get_contributors(**kwargs_): return Contributors
474
Python
.py
13
34.846154
77
0.789934
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,249
proxy.py
translate_pootle/pootle/apps/pootle_statistics/proxy.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django.template.defaultfilters import truncatechars from django.urls import reverse from django.utils.functional import cached_property from accounts.proxy import DisplayUser from pootle.core.primitives import PrefixedDict from pootle.core.url_helpers import get_editor_filter, split_pootle_path from pootle.core.utils import dateformat from pootle_checks.constants import CHECK_NAMES from pootle_store.constants import FUZZY, TRANSLATED from pootle_store.fields import to_python from .models import SubmissionFields, SubmissionTypes, TranslationActionTypes class SubmissionProxy(object): """Wraps a dictionary of submission values, which is useful for wrapping results from qs.values calls """ fields = ( "type", "old_value", "new_value", "creation_time", "field") qc_fields = ( "quality_check_id", "quality_check__name") submitter_fields = ( "submitter_id", "submitter__username", "submitter__email", "submitter__full_name") suggestion_fields = ( "suggestion_id", "suggestion__target_f", ) suggestion_reviewer_fields = ( "suggestion__reviewer__full_name", "suggestion__reviewer__email", "suggestion__reviewer__username") suggestion_user_fields = ( "suggestion__user__full_name", "suggestion__user__email", "suggestion__user__username") unit_fields = ( "unit_id", "unit__state", "unit__source_f", "unit__store__pootle_path") timeline_fields = ( fields + qc_fields + submitter_fields + suggestion_fields + suggestion_user_fields) info_fields = ( fields + qc_fields + submitter_fields + suggestion_fields + suggestion_reviewer_fields + unit_fields) def __init__(self, values, prefix=""): if prefix: self.values = PrefixedDict(values, prefix) else: self.values = values def __getattr__(self, k): try: return self.__dict__["values"][k] or "" except KeyError: return self.__getattribute__(k) @property def field(self): return self.values["field"] @property def field_name(self): return SubmissionFields.NAMES_MAP.get(self.field, None) @property def qc_name(self): return self.values['quality_check__name'] @property def suggestion(self): return self.values['suggestion_id'] @property def suggestion_full_name(self): return self.values.get('suggestion__user__full_name') @property def suggestion_username(self): return self.values.get('suggestion__user__username') @property def suggestion_target(self): return self.values.get('suggestion__target_f') @property def unit(self): return self.values.get('unit_id') @property def unit_state(self): return self.values.get('unit__state') @property def unit_source(self): return self.values.get('unit__source_f') @property def submitter_display(self): return DisplayUser( self.values["submitter__username"], self.values["submitter__full_name"], self.values["submitter__email"]) @property def suggestion_reviewer_display(self): return DisplayUser( self.values["suggestion__reviewer__username"], self.values["suggestion__reviewer__full_name"], self.values["suggestion__reviewer__email"]) @cached_property def display_user(self): return self.submitter_display @property def unit_pootle_path(self): return self.values.get("unit__store__pootle_path") @property def unit_translate_url(self): if not self.unit: return store_url = u''.join( [reverse("pootle-tp-store-translate", args=split_pootle_path(self.unit_pootle_path)), get_editor_filter()]) return ( "%s%s" % (store_url, '#unit=%s' % unicode(self.unit))) @property def unit_info(self): info = {} if self.unit is None: return info info.update( dict(unit_source=truncatechars(self.unit_source, 50), unit_url=self.unit_translate_url)) if self.qc_name is None: return info info.update( dict(check_name=self.qc_name, check_display_name=CHECK_NAMES.get(self.qc_name, self.qc_name), checks_url=reverse('pootle-checks-descriptions'))) return info @property def submission_info(self): return { "profile_url": self.display_user.get_absolute_url(), "email": self.display_user.email_hash, "displayname": self.display_user.display_name, "username": self.display_user.username, "display_datetime": dateformat.format(self.creation_time), "type": self.type, "mtime": int(dateformat.format(self.creation_time, 'U'))} @property def translation_action_type(self): if not self.unit: return if self.type not in SubmissionTypes.EDIT_TYPES: return if self.field == SubmissionFields.STATE: # Note that a submission where field is STATE # should be created before a submission where # field is TARGET state = int(to_python(self.new_value)) if state == TRANSLATED: return TranslationActionTypes.REVIEWED elif state == FUZZY: return TranslationActionTypes.NEEDS_WORK if self.field != SubmissionFields.TARGET: return if self.new_value == '': return TranslationActionTypes.REMOVED # Note that we analyze current unit state: # if this submission is not last unit state # can be changed if self.unit_state not in [TRANSLATED, FUZZY]: return if self.old_value != '': return TranslationActionTypes.EDITED return ( TranslationActionTypes.PRE_TRANSLATED if self.unit_state == FUZZY else TranslationActionTypes.TRANSLATED) def get_submission_info(self): result = self.unit_info result.update(self.submission_info) if self.translation_action_type is not None: result["translation_action_type"] = self.translation_action_type return result
6,942
Python
.py
196
26.903061
80
0.621855
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,250
urls.py
translate_pootle/pootle/apps/pootle_statistics/urls.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django.conf.urls import url from . import views urlpatterns = [ # XHR url(r'^xhr/stats/contributors/?$', views.TopContributorsJSON.as_view(), name='pootle-xhr-contributors'), ]
485
Python
.py
15
29.466667
77
0.723176
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,251
apps.py
translate_pootle/pootle/apps/pootle_statistics/apps.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import importlib from django.apps import AppConfig class PootleStatisticsConfig(AppConfig): name = "pootle_statistics" verbose_name = "Pootle Statistics" version = "0.1.2" def ready(self): importlib.import_module("pootle_statistics.getters")
547
Python
.py
15
33.466667
77
0.750951
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,252
utils.py
translate_pootle/pootle/apps/pootle_statistics/utils.py
# -*- coding: utf-8 -*- # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from collections import OrderedDict from django.contrib.auth import get_user_model from django.db.models import Count, Q from django.utils.functional import cached_property class Contributors(object): def __init__(self, include_anon=False, project_codes=None, language_codes=None, since=None, until=None, sort_by="username"): self.include_anon = include_anon self.project_codes = project_codes self.language_codes = language_codes self.since = since self.until = until self.sort_by = sort_by @property def user_qs(self): User = get_user_model() if self.include_anon: return User.objects.exclude(username__in=["system", "default"]) return User.objects.hide_meta() @property def user_filters(self): return Q(submission__gt=0) @property def site_filters(self): q = Q() tp_related = "submission__translation_project__" if self.project_codes: q = q & Q( **{"%sproject__code__in" % tp_related: self.project_codes}) if self.language_codes: q = q & Q( **{"%slanguage__code__in" % tp_related: self.language_codes}) return q @property def time_filters(self): q = Q() if self.since is not None: q = q & Q(submission__creation_time__gte=self.since) if self.until is not None: q = q & Q(submission__creation_time__lte=self.until) return q @property def filters(self): return self.user_filters & self.site_filters & self.time_filters def __iter__(self): for k in self.contributors: yield k def __getitem__(self, k): return self.contributors[k] def items(self): return self.contributors.items() @cached_property def contributors(self): qs = self.user_qs.filter(self.filters).annotate( contributions=Count("submission")) if self.sort_by == "contributions": qs = qs.order_by("-contributions", "username") else: qs = qs.order_by("username") return OrderedDict( [(user["username"], user) for user in qs.values("username", "full_name", "contributions", "email")])
2,623
Python
.py
70
29.242857
78
0.613627
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,253
__init__.py
translate_pootle/pootle/apps/pootle_statistics/__init__.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. default_app_config = 'pootle_statistics.apps.PootleStatisticsConfig'
345
Python
.py
8
42
77
0.77381
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,254
forms.py
translate_pootle/pootle/apps/pootle_statistics/forms.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. """Form fields required for handling translation files.""" from django import forms class StatsForm(forms.Form): offset = forms.IntegerField(required=False) path = forms.CharField(max_length=2048, required=True) def clean_path(self): return self.cleaned_data.get("path", "/") or "/"
584
Python
.py
14
38.857143
77
0.737589
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,255
views.py
translate_pootle/pootle/apps/pootle_statistics/views.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django.forms import ValidationError from django.http import Http404 from django.utils.functional import cached_property from pootle.core.delegate import scores from pootle.core.url_helpers import split_pootle_path from pootle.core.utils.stats import TOP_CONTRIBUTORS_CHUNK_SIZE from pootle.core.views.base import PootleJSON from pootle_app.models import Directory from pootle_language.models import Language from pootle_project.models import Project, ProjectSet from .forms import StatsForm class TopContributorsJSON(PootleJSON): form_class = StatsForm @cached_property def request_kwargs(self): stats_form = self.get_form() if not stats_form.is_valid(): raise Http404( ValidationError(stats_form.errors).messages) return stats_form.cleaned_data @cached_property def pootle_path(self): (language_code, project_code, dir_path, filename) = split_pootle_path(self.path) if language_code and project_code: return ( "/%s/%s/" % (language_code, project_code)) elif language_code: return "/%s/" % language_code elif project_code: return "/projects/%s/" % project_code @cached_property def object(self): return ( self.pootle_path and Directory.objects.get(pootle_path=self.pootle_path) or Directory.objects.projects) def get_object(self): return self.object def get_form(self): return self.form_class(self.request.GET) @property def path(self): return self.request_kwargs.get("path") @property def offset(self): return self.request_kwargs.get("offset") or 0 @property def limit(self): return TOP_CONTRIBUTORS_CHUNK_SIZE @cached_property def scores(self): return scores.get( self.score_context.__class__)( self.score_context) @property def score_context(self): (language_code, project_code, dir_path, filename) = split_pootle_path(self.path) if language_code and project_code: return self.object.translationproject elif language_code: return Language.objects.get(code=language_code) elif project_code: return Project.objects.get(code=project_code) return ProjectSet( Project.objects.for_user(self.request.user) .select_related("directory")) def get_context_data(self, **kwargs_): def scores_to_json(score): score["user"] = score["user"].to_dict() return score top_scorers = self.scores.display( offset=self.offset, limit=self.limit, formatter=scores_to_json) return dict( items=list(top_scorers), has_more_items=( len(self.scores.top_scorers) > (self.offset + self.limit)))
3,287
Python
.py
89
28.719101
77
0.648224
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,256
0014_truncate_source_subs.py
translate_pootle/pootle/apps/pootle_statistics/migrations/0014_truncate_source_subs.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-25 15:53 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pootle_statistics', '0013_remove_revert_flag'), ] operations = [ ]
300
Python
.py
10
26.1
57
0.684211
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,257
0020_convert_checks_subs.py
translate_pootle/pootle/apps/pootle_statistics/migrations/0020_convert_checks_subs.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-02 12:44 from __future__ import unicode_literals from django.db import migrations MUTE_FLAG = 6 UNMUTE_FLAG = 7 MUTED = 0 UNMUTED = 1 CHECK_FIELD_FLAG = 5 WEB_FLAG = 1 def convert_check_subs(apps, schema_editor): subs = apps.get_model("pootle_statistics.Submission").objects subs.filter(type=MUTE_FLAG).update( field=CHECK_FIELD_FLAG, type=WEB_FLAG, old_value=UNMUTED, new_value=MUTED) subs.filter(type=UNMUTE_FLAG).update( field=CHECK_FIELD_FLAG, type=WEB_FLAG, old_value=MUTED, new_value=UNMUTED) class Migration(migrations.Migration): dependencies = [ ('pootle_statistics', '0019_convert_accept_sugg_subs'), ] operations = [ migrations.RunPython(convert_check_subs), ]
855
Python
.py
29
24.37931
65
0.674847
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,258
0003_scorelog_translated_wordcount.py
translate_pootle/pootle/apps/pootle_statistics/migrations/0003_scorelog_translated_wordcount.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pootle_statistics', '0002_update_submission_ordering'), ] operations = [ migrations.AddField( model_name='scorelog', name='translated_wordcount', field=models.PositiveIntegerField(null=True), ), ]
441
Python
.py
14
24.714286
65
0.64218
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,259
0004_fill_translated_wordcount.py
translate_pootle/pootle/apps/pootle_statistics/migrations/0004_fill_translated_wordcount.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def set_translated_wordcount(apps, schema_editor): # this migration created some issues and has been removed pass class Migration(migrations.Migration): dependencies = [ ('pootle_statistics', '0003_scorelog_translated_wordcount'), ('pootle_store', '0008_flush_django_cache'), ] operations = [ migrations.RunPython(set_translated_wordcount), ]
494
Python
.py
14
30.428571
68
0.706751
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,260
0016_drop_add_suggestion_subs.py
translate_pootle/pootle/apps/pootle_statistics/migrations/0016_drop_add_suggestion_subs.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-28 11:10 from __future__ import unicode_literals from django.db import migrations SUGG_ADD_FLAG = 8 def drop_add_suggestion_subs(apps, schema_editor): subs = apps.get_model("pootle_statistics.Submission").objects.all() subs.filter(type=SUGG_ADD_FLAG).delete() class Migration(migrations.Migration): dependencies = [ ('pootle_statistics', '0015_remove_system_scorelogs'), ] operations = [ migrations.RunPython(drop_add_suggestion_subs), ]
551
Python
.py
15
32.466667
71
0.711575
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,261
0006_set_submission_base_manager_name.py
translate_pootle/pootle/apps/pootle_statistics/migrations/0006_set_submission_base_manager_name.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-01-20 08:21 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pootle_statistics', '0005_index_ordering'), ] operations = [ migrations.AlterModelOptions( name='submission', options={'base_manager_name': 'objects', 'get_latest_by': 'creation_time', 'ordering': ['creation_time', 'pk']}, ), ]
501
Python
.py
14
29.857143
124
0.636929
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,262
0023_remove_scorelog.py
translate_pootle/pootle/apps/pootle_statistics/migrations/0023_remove_scorelog.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-18 12:41 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pootle_statistics', '0022_set_suggestion_submitters'), ] operations = [ migrations.AlterUniqueTogether( name='scorelog', unique_together=set([]), ), migrations.RemoveField( model_name='scorelog', name='submission', ), migrations.RemoveField( model_name='scorelog', name='user', ), migrations.DeleteModel( name='ScoreLog', ), ]
708
Python
.py
25
20.24
64
0.576696
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,263
0017_drop_reject_suggestion_subs.py
translate_pootle/pootle/apps/pootle_statistics/migrations/0017_drop_reject_suggestion_subs.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-28 13:11 from __future__ import unicode_literals from django.db import migrations SUGG_REJECT_FLAG = 9 def drop_reject_suggestion_subs(apps, schema_editor): subs = apps.get_model("pootle_statistics.Submission").objects.all() subs.filter(type=SUGG_REJECT_FLAG).delete() class Migration(migrations.Migration): dependencies = [ ('pootle_statistics', '0016_drop_add_suggestion_subs'), ] operations = [ migrations.RunPython(drop_reject_suggestion_subs), ]
564
Python
.py
15
33.333333
71
0.716667
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,264
0011_cleanup_submissions_squashed_0023_remove_scorelog.py
translate_pootle/pootle/apps/pootle_statistics/migrations/0011_cleanup_submissions_squashed_0023_remove_scorelog.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-05-11 04:59 from __future__ import unicode_literals from django.conf import settings from django.db import migrations from pootle.core.batch import Batch # Old types REVERT_TYPE = 2 SUGG_ACCEPT_TYPE = 3 SUGG_ADD_TYPE = 8 SUGG_REJECT_TYPE = 9 UNIT_CREATE_TYPE = 10 # Fields TARGET_FIELD = 2 STATE_FIELD = 3 # Remaining types MUTE_TYPE = 6 UNMUTE_TYPE = 7 NEW_MUTED = 0 NEW_UNMUTED = 1 NEW_CHECK_FIELD = 5 NEW_WEB_TYPE = 1 # 2, 3, 8, 9, 10 OLD_TYPES = [ REVERT_TYPE, SUGG_ACCEPT_TYPE, SUGG_ADD_TYPE, SUGG_REJECT_TYPE, UNIT_CREATE_TYPE] CLEANUP_STORE_DATA_SQL = ( "UPDATE `pootle_store_data` " " INNER JOIN `pootle_app_submission` " " ON `pootle_app_submission`.`id` = `pootle_store_data`.`last_submission_id` " " SET `last_submission_id` = NULL" " WHERE `pootle_app_submission`.`type` in (%s)") CLEANUP_TP_DATA_SQL = ( "UPDATE `pootle_tp_data` " " INNER JOIN `pootle_app_submission` " " ON `pootle_app_submission`.`id` = `pootle_tp_data`.`last_submission_id` " " SET `last_submission_id` = NULL" " WHERE `pootle_app_submission`.`type` in (%s)") CLEANUP_SQL = ( "DELETE FROM `pootle_app_submission` " " WHERE (`unit_id` IS NULL" " OR `pootle_app_submission`.`type` in (%s))") def cleanup_subs_with_sql(schema_editor): cursor = schema_editor.connection.cursor() _old_types = ", ".join(str(t) for t in OLD_TYPES) # remove any fks to submissions that are to be deleted cursor.execute(CLEANUP_STORE_DATA_SQL % _old_types) cursor.execute(CLEANUP_TP_DATA_SQL % _old_types) cursor.execute(CLEANUP_SQL % _old_types) def cleanup_subs_with_orm(apps): subs = apps.get_model("pootle_statistics.Submission").objects.all() to_delete = ( subs.filter(unit_id__isnull=True) | subs.filter(type__in=OLD_TYPES)) to_delete.delete() def cleanup_subs(apps, schema_editor): if schema_editor.connection.vendor == "mysql" and settings.POOTLE_SQL_MIGRATIONS: cleanup_subs_with_sql(schema_editor) else: cleanup_subs_with_orm(apps) def _cleanup_accept_suggestion_subs(apps): # state/target changes that happened from suggestion had type=3, # and state change subs did not have their suggestion associated # They also credited the reviewer not the submitter # we need to: # - associate any state change subs with relevant suggestions # - set the suggester as submitter for all type=3 submissions # - update type to WEB for all type=3 subs that have suggestions # any remaining submissions of this type are likely dupes and will be deleted Submission = apps.get_model("pootle_statistics.Submission") subs = Submission.objects.all() suggestions = apps.get_model("pootle_store.Suggestion").objects # assoc state change subs with suggestions and update the sub to_update = [] accepted_suggestions = suggestions.filter(state__name="accepted").values( "review_time", "pk", "unit_id", "reviewer_id", "user_id") accept_sugg_state_subs = subs.filter( type=SUGG_ACCEPT_TYPE).filter(field=STATE_FIELD) accept_subs_for_update = accept_sugg_state_subs.select_related( "suggestion").only("id", "type", "submitter_id", "suggestion_id") for suggestion in accepted_suggestions.iterator(): suggestion["submitter_id"] = suggestion["reviewer_id"] suggestion["creation_time"] = suggestion["review_time"] suggestion_id = suggestion["pk"] suggestion_user = suggestion["user_id"] del suggestion["review_time"] del suggestion["reviewer_id"] del suggestion["pk"] del suggestion["user_id"] matching_sub = accept_subs_for_update.filter(**suggestion).first() if matching_sub: matching_sub.type = NEW_WEB_TYPE matching_sub.suggestion_id = suggestion_id matching_sub.submitter_id = suggestion_user to_update.append(matching_sub) if to_update: Batch(Submission.objects, batch_size=5000).update( to_update, update_fields=["type", "suggestion_id", "submitter_id"], reduces=False) # all remaining valid sugg_accept subs should be field=target and have a suggestion to_update = [] accept_sugg_subs = subs.filter(type=SUGG_ACCEPT_TYPE).filter(field=TARGET_FIELD).exclude(suggestion__isnull=True) accept_subs_for_update = accept_sugg_subs.select_related( "suggestion").only("id", "type", "submitter_id", "suggestion__user_id") for sub in accept_subs_for_update.iterator(): sub.submitter_id = sub.suggestion.user_id sub.type = NEW_WEB_TYPE to_update.append(sub) if to_update: Batch(Submission.objects, batch_size=5000).update( to_update, update_fields=["type", "submitter_id"], reduces=False) def _cleanup_checks(apps): subs = apps.get_model("pootle_statistics.Submission").objects subs.filter(type=MUTE_TYPE).update( old_value=NEW_UNMUTED, new_value=NEW_MUTED, type=NEW_WEB_TYPE, field=NEW_CHECK_FIELD) subs.filter(type=UNMUTE_TYPE).update( old_value=NEW_MUTED, new_value=NEW_UNMUTED, type=NEW_WEB_TYPE, field=NEW_CHECK_FIELD) def update_subs(apps, schema_editor): _cleanup_checks(apps) _cleanup_accept_suggestion_subs(apps) class Migration(migrations.Migration): replaces = [ (b'pootle_statistics', '0011_cleanup_submissions'), (b'pootle_statistics', '0012_remove_create_subs'), (b'pootle_statistics', '0013_remove_revert_flag'), (b'pootle_statistics', '0014_truncate_source_subs'), (b'pootle_statistics', '0015_remove_system_scorelogs'), (b'pootle_statistics', '0016_drop_add_suggestion_subs'), (b'pootle_statistics', '0017_drop_reject_suggestion_subs'), (b'pootle_statistics', '0018_remove_submission_store'), (b'pootle_statistics', '0019_convert_accept_sugg_subs'), (b'pootle_statistics', '0020_convert_checks_subs'), (b'pootle_statistics', '0021_remove_paid_rates'), (b'pootle_statistics', '0022_set_suggestion_submitters'), (b'pootle_statistics', '0023_remove_scorelog')] dependencies = [ ('pootle_store', '0045_remove_suggestion_tmp_state'), ('pootle_statistics', '0010_submission_on_delete_user')] operations = [ migrations.DeleteModel( name='ScoreLog', ), migrations.RunPython(update_subs), migrations.RunPython(cleanup_subs), migrations.RemoveField( model_name='submission', name='store', )]
6,748
Python
.py
160
35.88125
117
0.669056
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,265
0008_set_submission_revisions.py
translate_pootle/pootle/apps/pootle_statistics/migrations/0008_set_submission_revisions.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-01-26 17:02 from __future__ import unicode_literals from django.db import migrations def set_submission_revisions(apps, schema_editor): units = apps.get_model("pootle_store.Unit").objects.all() submissions = apps.get_model("pootle_statistics.Submission").objects # if unit has 0 revision then so does all of its submissions submissions.filter(unit__in=units.filter(revision=0)).update(revision=0) revisions = units.filter(revision__gt=0).exclude(submission__isnull=True).values_list("revision", flat=True).distinct() for revision in revisions.iterator(): seen_units = set() subs = set() # find the latest submission for each unit at the given revision matched_subs = submissions.filter( unit__revision=revision).order_by("-creation_time", "-id").values_list("unit", "id") for unit, sub in matched_subs.iterator(): if unit in seen_units: continue seen_units.add(unit) subs.add(sub) submissions.filter(id__in=subs).update(revision=revision) class Migration(migrations.Migration): dependencies = [ ('pootle_statistics', '0007_submission_revision'), ] operations = [ migrations.RunPython(set_submission_revisions), ]
1,355
Python
.py
29
39.482759
123
0.677075
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,266
0009_rm_similarity.py
translate_pootle/pootle/apps/pootle_statistics/migrations/0009_rm_similarity.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-01 17:00 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pootle_statistics', '0008_set_submission_revisions'), ] operations = [ migrations.RemoveField( model_name='scorelog', name='similarity', ), migrations.RemoveField( model_name='submission', name='mt_similarity', ), migrations.RemoveField( model_name='submission', name='similarity', ), ]
640
Python
.py
22
21.318182
63
0.59217
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,267
0012_remove_create_subs.py
translate_pootle/pootle/apps/pootle_statistics/migrations/0012_remove_create_subs.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-17 17:54 from __future__ import unicode_literals import logging import time from django.db import migrations logger = logging.getLogger(__name__) def remove_create_subs(apps, schema_editor): subs = apps.get_model("pootle_statistics.Submission").objects.all() # type 10 is the now deleted SubmissionTypes.UNIT_CREATE to_delete = subs.filter(type=10) total = to_delete.count() offset = 0 step = 10000 start = time.time() while True: subs_chunk = to_delete[:step] to_delete.filter( id__in=set( subs_chunk.values_list("id", flat=True))).delete() logger.debug( "deleted %s/%s in %s seconds" % (offset + step, total, (time.time() - start))) if offset > total: break offset = offset + step class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0035_set_created_by_again'), ('pootle_statistics', '0011_cleanup_submissions'), ] operations = [ migrations.RunPython(remove_create_subs), ]
1,149
Python
.py
34
27.294118
71
0.629529
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,268
0001_initial.py
translate_pootle/pootle/apps/pootle_statistics/migrations/0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('pootle_translationproject', '0001_initial'), ('pootle_store', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Submission', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('creation_time', models.DateTimeField(db_index=True)), ('field', models.IntegerField(db_index=True, null=True, blank=True)), ('type', models.IntegerField(db_index=True, null=True, blank=True)), ('old_value', models.TextField(default='', blank=True)), ('new_value', models.TextField(default='', blank=True)), ('similarity', models.FloatField(null=True, blank=True)), ('mt_similarity', models.FloatField(null=True, blank=True)), ('quality_check', models.ForeignKey(blank=True, to='pootle_store.QualityCheck', null=True, on_delete=models.CASCADE)), ('store', models.ForeignKey(blank=True, to='pootle_store.Store', null=True, on_delete=models.CASCADE)), ('submitter', models.ForeignKey(to=settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)), ('suggestion', models.ForeignKey(blank=True, to='pootle_store.Suggestion', null=True, on_delete=models.CASCADE)), ('translation_project', models.ForeignKey(to='pootle_translationproject.TranslationProject', on_delete=models.CASCADE)), ('unit', models.ForeignKey(blank=True, to='pootle_store.Unit', null=True, on_delete=models.CASCADE)), ], options={ 'ordering': ['creation_time'], 'db_table': 'pootle_app_submission', 'get_latest_by': 'creation_time', }, bases=(models.Model,), ), migrations.CreateModel( name='ScoreLog', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('creation_time', models.DateTimeField(db_index=True)), ('rate', models.FloatField(default=0)), ('review_rate', models.FloatField(default=0)), ('wordcount', models.PositiveIntegerField()), ('similarity', models.FloatField()), ('score_delta', models.FloatField()), ('action_code', models.IntegerField()), ('submission', models.ForeignKey(to='pootle_statistics.Submission', on_delete=models.CASCADE)), ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)), ], options={ }, bases=(models.Model,), ), migrations.AlterUniqueTogether( name='scorelog', unique_together=set([('submission', 'action_code')]), ), ]
3,210
Python
.py
59
41.661017
136
0.590273
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,269
0015_remove_system_scorelogs.py
translate_pootle/pootle/apps/pootle_statistics/migrations/0015_remove_system_scorelogs.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-25 19:51 from __future__ import unicode_literals from django.db import migrations from pootle.core.user import get_system_user_id def remove_system_scorelogs(apps, schema_editor): scorelogs = apps.get_model("pootle_statistics.ScoreLog").objects.all() scorelogs.filter(user_id=get_system_user_id()).delete() class Migration(migrations.Migration): dependencies = [ ('pootle_statistics', '0014_truncate_source_subs'), ] operations = [ migrations.RunPython(remove_system_scorelogs), ]
594
Python
.py
15
35.333333
74
0.724561
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,270
0010_submission_on_delete_user.py
translate_pootle/pootle/apps/pootle_statistics/migrations/0010_submission_on_delete_user.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-02 15:10 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import pootle.core.user class Migration(migrations.Migration): dependencies = [ ('pootle_statistics', '0009_rm_similarity'), ] operations = [ migrations.AlterField( model_name='submission', name='submitter', field=models.ForeignKey(null=True, on_delete=models.SET(pootle.core.user.get_system_user), to=settings.AUTH_USER_MODEL), ), ]
602
Python
.py
17
29.647059
132
0.677586
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,271
0013_remove_revert_flag.py
translate_pootle/pootle/apps/pootle_statistics/migrations/0013_remove_revert_flag.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-25 14:15 from __future__ import unicode_literals from django.db import migrations # this was the value of SubmissionTypes.REVERT REVERT_FLAG = 2 def remove_revert_flag(apps, schema_editor): subs = apps.get_model("pootle_statistics.Submission").objects.all() subs.filter(type=REVERT_FLAG).delete() class Migration(migrations.Migration): dependencies = [ ('pootle_statistics', '0012_remove_create_subs'), ] operations = [ migrations.RunPython(remove_revert_flag), ]
575
Python
.py
16
32
71
0.717391
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,272
0002_update_submission_ordering.py
translate_pootle/pootle/apps/pootle_statistics/migrations/0002_update_submission_ordering.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('pootle_statistics', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='submission', options={'ordering': ['creation_time', 'pk'], 'get_latest_by': 'creation_time'}, ), ]
421
Python
.py
13
26.076923
92
0.620347
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,273
0005_index_ordering.py
translate_pootle/pootle/apps/pootle_statistics/migrations/0005_index_ordering.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.10 on 2016-10-23 12:28 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pootle_statistics', '0004_fill_translated_wordcount'), ] operations = [ migrations.AlterIndexTogether( name='submission', index_together=set([('submitter', 'creation_time', 'id')]), ), ]
460
Python
.py
14
26.928571
71
0.641723
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,274
0019_convert_accept_sugg_subs.py
translate_pootle/pootle/apps/pootle_statistics/migrations/0019_convert_accept_sugg_subs.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-01 08:04 from __future__ import unicode_literals from django.db import migrations from django.db.models import F WEB_FLAG = 1 SUGG_ACCEPT_FLAG = 3 STATE_FIELD_FLAG = 3 def _assoc_state_accept_suggestion_subs(apps): subs = apps.get_model("pootle_statistics.Submission").objects.all() suggestions = apps.get_model("pootle_store.Suggestion").objects accepted = suggestions.filter(state__name="accepted").values( "review_time", "pk", "unit_id", "reviewer") state_acc = subs.filter( type=SUGG_ACCEPT_FLAG).filter(field=STATE_FIELD_FLAG) for suggestion in accepted.iterator(): suggestion["submitter"] = suggestion["reviewer"] suggestion["creation_time"] = suggestion["review_time"] suggestion_id = suggestion["pk"] del suggestion["review_time"] del suggestion["reviewer"] del suggestion["pk"] state_acc.filter(**suggestion).update(suggestion_id=suggestion_id) def _delete_redundant_accept_sugg_subs(apps): subs = apps.get_model("pootle_statistics.Submission").objects sugg_acc = subs.filter(type=SUGG_ACCEPT_FLAG) # these appear to be caused by dupes # no suggestion sugg_acc.filter(suggestion__isnull=True).delete() # review time doesnt match sugg_acc.exclude( creation_time=F("suggestion__review_time")).delete() # reviewer doesnt match sugg_acc.exclude( submitter=F("suggestion__reviewer")).delete() def convert_accept_suggestion_subs(apps, schema_editor): subs = apps.get_model("pootle_statistics.Submission").objects # clear up existing subs first _assoc_state_accept_suggestion_subs(apps) _delete_redundant_accept_sugg_subs(apps) # convert to SubmissionTypes.WEB subs.filter(type=SUGG_ACCEPT_FLAG).update(type=WEB_FLAG) class Migration(migrations.Migration): dependencies = [ ('pootle_statistics', '0018_remove_submission_store'), ('pootle_store', '0045_remove_suggestion_tmp_state'), ] operations = [ migrations.RunPython(convert_accept_suggestion_subs), ]
2,150
Python
.py
50
37.44
74
0.705769
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,275
0012_drop_stale_scorelog_ctype.py
translate_pootle/pootle/apps/pootle_statistics/migrations/0012_drop_stale_scorelog_ctype.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-05-17 12:21 from __future__ import unicode_literals from django.db import migrations def drop_scorelog_ctype(apps, schema_editor): ContentType = apps.get_model('contenttypes.ContentType') ContentType.objects.filter(app_label='pootle_statistics', model='scorelog').delete() class Migration(migrations.Migration): dependencies = [ ('pootle_statistics', '0011_cleanup_submissions_squashed_0023_remove_scorelog'), ] operations = [ migrations.RunPython(drop_scorelog_ctype), ]
611
Python
.py
15
34.533333
88
0.692699
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,276
0021_remove_paid_rates.py
translate_pootle/pootle/apps/pootle_statistics/migrations/0021_remove_paid_rates.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-03 20:51 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pootle_statistics', '0020_convert_checks_subs'), ] operations = [ migrations.RemoveField( model_name='scorelog', name='rate', ), migrations.RemoveField( model_name='scorelog', name='review_rate', ), ]
514
Python
.py
18
21.5
58
0.598778
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,277
0018_remove_submission_store.py
translate_pootle/pootle/apps/pootle_statistics/migrations/0018_remove_submission_store.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-02 08:36 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pootle_statistics', '0017_drop_reject_suggestion_subs'), ] operations = [ migrations.RemoveField( model_name='submission', name='store', ), ]
415
Python
.py
14
23.714286
66
0.636364
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,278
0007_submission_revision.py
translate_pootle/pootle/apps/pootle_statistics/migrations/0007_submission_revision.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-01-26 19:33 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pootle_statistics', '0006_set_submission_base_manager_name'), ] operations = [ migrations.AddField( model_name='submission', name='revision', field=models.IntegerField(blank=True, db_index=True, null=True), ), ]
505
Python
.py
15
27.266667
76
0.645361
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,279
0022_set_suggestion_submitters.py
translate_pootle/pootle/apps/pootle_statistics/migrations/0022_set_suggestion_submitters.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-14 11:01 from __future__ import unicode_literals from django.db import migrations from django.db.models import F def set_suggestion_submitters(apps, schema_editor): subs = apps.get_model("pootle_statistics.Submission").objects accepted_subs = subs.filter(suggestion__state__name="accepted").values_list( "pk", "suggestion__user_id") for pk, user in accepted_subs.iterator(): subs.filter(pk=pk).update(submitter_id=user) class Migration(migrations.Migration): dependencies = [ ('pootle_statistics', '0021_remove_paid_rates'), ] operations = [ migrations.RunPython(set_suggestion_submitters), ]
724
Python
.py
18
35.5
80
0.708155
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,280
0013_remove_extra_indeces.py
translate_pootle/pootle/apps/pootle_statistics/migrations/0013_remove_extra_indeces.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-06-02 16:12 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import pootle.core.user class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('pootle_statistics', '0012_drop_stale_scorelog_ctype'), ] operations = [ migrations.AlterField( model_name='submission', name='submitter', field=models.ForeignKey(db_index=False, null=True, on_delete=models.SET(pootle.core.user.get_system_user), to=settings.AUTH_USER_MODEL), ), migrations.AlterIndexTogether( name='submission', index_together=set([('submitter', 'creation_time')]), ), ]
844
Python
.py
22
31.5
148
0.665851
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,281
0014_submission_unit_notnull.py
translate_pootle/pootle/apps/pootle_statistics/migrations/0014_submission_unit_notnull.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-09-06 08:52 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('pootle_statistics', '0013_remove_extra_indeces'), ] operations = [ migrations.AlterField( model_name='submission', name='unit', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='pootle_store.Unit'), ), ]
553
Python
.py
16
28.5
105
0.663534
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,282
0011_cleanup_submissions.py
translate_pootle/pootle/apps/pootle_statistics/migrations/0011_cleanup_submissions.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-10 21:45 from __future__ import unicode_literals from django.db import migrations def cleanup_submissions(apps, schema_editor): subs = apps.get_model("pootle_statistics.Submission").objects.all() subs.filter(unit__isnull=True).delete() class Migration(migrations.Migration): dependencies = [ ('pootle_statistics', '0010_submission_on_delete_user'), ] operations = [ migrations.RunPython(cleanup_submissions), ]
522
Python
.py
14
32.928571
71
0.712575
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,283
0001_initial.py
translate_pootle/pootle/apps/reports/migrations/0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='PaidTask', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('task_type', models.PositiveSmallIntegerField(default=0, db_index=True, verbose_name='Type', choices=[(0, 'Translation'), (1, 'Review'), (2, 'Hourly Work'), (3, 'Correction')])), ('amount', models.FloatField(default=0, verbose_name='Amount')), ('rate', models.FloatField(default=0)), ('datetime', models.DateTimeField(verbose_name='Date', db_index=True)), ('description', models.TextField(null=True, verbose_name='Description')), ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)), ], options={ }, bases=(models.Model,), ), ]
1,207
Python
.py
25
38.12
195
0.604928
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,284
0002_rm_paid_task.py
translate_pootle/pootle/apps/reports/migrations/0002_rm_paid_task.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.10 on 2016-10-12 16:23 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('reports', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='paidtask', name='user', ), migrations.DeleteModel( name='PaidTask', ), ]
454
Python
.py
17
20
48
0.592593
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,285
versioned.py
translate_pootle/pootle/apps/pootle_store/versioned.py
from pootle.core.proxy import BaseProxy from pootle_statistics.models import Submission, SubmissionFields class StoreVersion(BaseProxy): pass class VersionedStore(object): version_class = StoreVersion def __init__(self, store): self.store = store @property def current_store(self): return StoreVersion( self.store.deserialize( self.store.serialize( include_obsolete=True, raw=True))) def _revert_state(self, unit, sub): if sub.old_value == "50": unit.markfuzzy() if sub.old_value == "-100": unit.makeobsolete() if sub.old_value in ["0", "200"]: if sub.new_value == "50": unit.markfuzzy(False) if sub.new_value == "-100": unit.resurrect() def at_revision(self, revision): store = self.current_store subs = Submission.objects.filter( unit__store=self.store).filter( revision__gt=revision).order_by( "revision", "creation_time") checking = dict(target=[], state=[]) unit_creation = self.store.unit_set.filter( unit_source__creation_revision__gt=revision).values_list( "unitid", flat=True) for unit in unit_creation: del store.units[store.units.index(store.findid(unit))] del store.id_index[unit] for sub in subs.iterator(): unit = store.findid(sub.unit.getid()) if not unit: continue if sub.field == SubmissionFields.TARGET: if sub.unit.pk in checking["target"]: continue checking["target"].append(sub.unit.pk) unit.target = sub.old_value if sub.field == SubmissionFields.STATE: if sub.unit.pk in checking["state"]: continue checking["state"].append(sub.unit.pk) self._revert_state(unit, sub) return store
2,085
Python
.py
53
27.358491
69
0.55638
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,286
models.py
translate_pootle/pootle/apps/pootle_store/models.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import logging import operator from hashlib import md5 from translate.filters.decorators import Category from django.contrib.auth import get_user_model from django.db import models from django.db.models import F from django.template.defaultfilters import truncatechars from django.urls import reverse from django.utils.encoding import force_bytes from django.utils.functional import cached_property from django.utils.http import urlquote from pootle.core.delegate import ( data_tool, format_syncers, format_updaters, frozen, states, terminology_matcher, wordcount) from pootle.core.log import STORE_DELETED, STORE_OBSOLETE, store_log from pootle.core.models import Revision from pootle.core.search import SearchBroker from pootle.core.signals import toggle, update_checks, update_data from pootle.core.url_helpers import ( get_editor_filter, split_pootle_path, to_tp_relative_path) from pootle.core.utils import dateformat from pootle.core.utils.aggregate import max_column from pootle.core.utils.multistring import PLURAL_PLACEHOLDER from pootle.core.utils.timezone import datetime_min from pootle_checks.constants import CHECK_NAMES from pootle_statistics.models import SubmissionFields, SubmissionTypes from .abstracts import ( AbstractQualityCheck, AbstractStore, AbstractSuggestion, AbstractSuggestionState, AbstractUnit, AbstractUnitChange, AbstractUnitSource) from .constants import ( DEFAULT_PRIORITY, FUZZY, OBSOLETE, POOTLE_WINS, TRANSLATED, UNTRANSLATED) from .managers import SuggestionManager, UnitManager from .store.deserialize import StoreDeserialization from .store.serialize import StoreSerialization from .util import vfolders_installed logger = logging.getLogger(__name__) TM_BROKER = None def get_tm_broker(): global TM_BROKER if TM_BROKER is None: TM_BROKER = SearchBroker() return TM_BROKER # # # # # # # # Quality Check # # # # # # # class QualityCheck(AbstractQualityCheck): """Database cache of results of qualitychecks on unit.""" class Meta(AbstractQualityCheck.Meta): abstract = False db_table = "pootle_store_qualitycheck" def __unicode__(self): return self.name @property def display_name(self): return CHECK_NAMES.get(self.name, self.name) @classmethod def delete_unknown_checks(cls): unknown_checks = ( QualityCheck.objects.exclude( name__in=CHECK_NAMES.keys())) unknown_checks.delete() # # # # # # # # # Suggestion # # # # # # # # class SuggestionState(AbstractSuggestionState): class Meta(AbstractSuggestionState.Meta): abstract = False db_table = "pootle_store_suggestion_state" class Suggestion(AbstractSuggestion): """Suggested translation for a :cls:`~pootle_store.models.Unit`, provided by users or automatically generated after a merge. """ class Meta(AbstractSuggestion.Meta): abstract = False db_table = "pootle_store_suggestion" objects = SuggestionManager() # # # # # # # # # # # # # # Properties # # # # # # # # # # # # # # # # # # @cached_property def states(self): return states.get(self.__class__) @property def is_accepted(self): return self.state_id == self.states["accepted"] @property def is_pending(self): return self.state_id == self.states["pending"] @property def is_rejected(self): return self.state_id == self.states["rejected"] @property def _target(self): return self.target_f @_target.setter def _target(self, value): self.target_f = value self.target_hash = md5(force_bytes(self.target_f)).hexdigest() @property def _source(self): return self.unit._source # # # # # # # # # # # # # # Methods # # # # # # # # # # # # # # # # # # # def __unicode__(self): return unicode(self.target) # # # # # # # # Unit # # # # # # # # # # def stringcount(string): try: return len(string.strings) except AttributeError: return 1 class UnitChange(AbstractUnitChange): class Meta(AbstractUnit.Meta): abstract = False db_table = "pootle_store_unit_change" class UnitSource(AbstractUnitSource): class Meta(AbstractUnit.Meta): abstract = False db_table = "pootle_store_unit_source" class Unit(AbstractUnit): objects = UnitManager() class Meta(AbstractUnit.Meta): abstract = False db_table = "pootle_store_unit" unique_together = ( ('store', 'unitid_hash'), ("store", "state", "index", "unitid_hash")) get_latest_by = 'mtime' index_together = [ ["store", "index"], ["store", "revision"], ["store", "mtime"]] # # # # # # # # # # # # # # Properties # # # # # # # # # # # # # # # # # # @property def _source(self): return self.source_f @_source.setter def _source(self, value): self.source_f = value @property def _target(self): return self.target_f @_target.setter def _target(self, value): self.target_f = value # # # # # # # # # # # # # Class & static methods # # # # # # # # # # # # # @classmethod def max_revision(cls): """Returns the max revision number across all units.""" return max_column(cls.objects.all(), 'revision', 0) # # # # # # # # # # # # # # Methods # # # # # # # # # # # # # # # # # # # def __unicode__(self): # FIXME: consider using unit id instead? return unicode(self.source) def __str__(self): return str(self.convert()) def __init__(self, *args, **kwargs): super(Unit, self).__init__(*args, **kwargs) self._rich_source = None self._rich_target = None self._encoding = 'UTF-8' if hasattr(self, "source_f") and hasattr(self, "target_f"): self._frozen = frozen.get(Unit)(self) @cached_property def counter(self): return wordcount.get(Unit) @property def comment_updated(self): return ( self.translator_comment != self._frozen.translator_comment) @property def revision_updated(self): return self.revision != self._frozen.revision @property def source_updated(self): return self.source != self._frozen.source @property def state_updated(self): return self.state != self._frozen.state @property def target_updated(self): return self.target != self._frozen.target @property def context_updated(self): return self.context != self._frozen.context @property def updated(self): created = self._frozen.pk is None return ( (self.source_updated and not created) or self.target_updated or (self.state_updated and not created) or (self.comment_updated and not created)) @property def changed(self): try: self.change return True except UnitChange.DoesNotExist: return False def refresh_from_db(self, *args, **kwargs): super(Unit, self).refresh_from_db(*args, **kwargs) if kwargs.get("fields") and "change" not in kwargs["fields"]: return field = self._meta.get_field("change") # Throw away stale empty references to unit.change. should_expire_cache = ( field.get_cache_name() in self.__dict__ and self.__dict__[field.get_cache_name()] is None) if should_expire_cache: del self.__dict__[field.get_cache_name()] self._frozen = frozen.get(Unit)(self) def save(self, *args, **kwargs): created = self.id is None user = ( kwargs.pop("user", None) or get_user_model().objects.get_system_user()) reviewed_by = kwargs.pop("reviewed_by", None) or user changed_with = kwargs.pop("changed_with", None) or SubmissionTypes.SYSTEM super(Unit, self).save(*args, **kwargs) timestamp = self.mtime if created: unit_source = UnitSource(unit=self) unit_source.created_by = user unit_source.created_with = changed_with timestamp = self.creation_time elif self.source_updated: unit_source = self.unit_source if created or self.source_updated: unit_source.save() if self.updated and (created or not self.changed): self.change = UnitChange( unit=self, changed_with=changed_with) if self.updated or reviewed_by != user: if changed_with is not None: self.change.changed_with = changed_with if self.comment_updated: self.change.commented_by = user self.change.commented_on = timestamp update_submit = ( (self.target_updated or self.source_updated) or not self.change.submitted_on) if update_submit: self.change.submitted_by = user self.change.submitted_on = timestamp is_review = ( reviewed_by != user or (self.state_updated and not self.target_updated) or (self.state_updated and self.state == UNTRANSLATED)) if is_review: self.change.reviewed_by = reviewed_by self.change.reviewed_on = timestamp self.change.save() update_data.send( self.store.__class__, instance=self.store) def get_absolute_url(self): return self.store.get_absolute_url() def get_translate_url(self): return ( "%s%s" % (self.store.get_translate_url(), '#unit=%s' % unicode(self.id))) def get_search_locations_url(self): (proj_code, dir_path, filename) = split_pootle_path(self.store.pootle_path)[1:] return u''.join([ reverse('pootle-project-translate', args=[proj_code, dir_path, filename]), get_editor_filter(search=self.locations, sfields='locations'), ]) def get_screenshot_url(self): prefix = self.store.translation_project.\ project.screenshot_search_prefix if prefix: return prefix + urlquote(self.source_f) def is_accessible_by(self, user): """Returns `True` if the current unit is accessible by `user`.""" if user.is_superuser: return True from pootle_project.models import Project user_projects = Project.accessible_by_user(user) return self.store.translation_project.project.code in user_projects @cached_property def unit_syncer(self): return self.store.syncer.unit_sync_class(self) def convert(self, unitclass=None): """Convert to a unit of type :param:`unitclass` retaining as much information from the database as the target format can support. """ return self.unit_syncer.convert(unitclass) def sync(self, unit, unitclass=None): """Sync in file unit with translations from the DB.""" changed = False if not self.isobsolete() and unit.isobsolete(): unit.resurrect() changed = True target = ( unitclass(self).target if unitclass else unit.target) if unit.target != target: if unit.hasplural(): nplurals = self.store.translation_project.language.nplurals target_plurals = len(target.strings) strings = target.strings if target_plurals < nplurals: strings.extend([u'']*(nplurals - target_plurals)) if unit.target.strings != strings: unit.target = strings changed = True else: unit.target = target changed = True self_notes = self.getnotes(origin="translator") unit_notes = unit.getnotes(origin="translator") if unit_notes != (self_notes or ''): if self_notes != '': unit.addnote(self_notes, origin="translator", position="replace") else: unit.removenotes() changed = True if unit.isfuzzy() != self.isfuzzy(): unit.markfuzzy(self.isfuzzy()) changed = True if self.isobsolete() and not unit.isobsolete(): unit.makeobsolete() changed = True return changed def update(self, unit, user=None): """Update in-DB translation from the given :param:`unit`. :param user: User to attribute updates to. :rtype: bool :return: True if the new :param:`unit` differs from the current unit. Two units differ when any of the fields differ (source, target, translator/developer comments, locations, context, status...). """ changed = False if user is None: User = get_user_model() user = User.objects.get_system_user() update_source = ( self.source != unit.source or (len(self.source.strings) != stringcount(unit.source)) or (self.hasplural() != unit.hasplural())) if update_source: if unit.hasplural() and len(unit.source.strings) == 1: self.source = [unit.source, PLURAL_PLACEHOLDER] else: self.source = unit.source changed = True update_target = ( self.target != unit.target or (len(self.target.strings) != stringcount(unit.target))) if update_target: notempty = filter(None, self.target_f.strings) self.target = unit.target if filter(None, self.target_f.strings) or notempty: # FIXME: we need to do this cause we discard nplurals for empty # plurals changed = True notes = unit.getnotes(origin="developer") if (self.developer_comment != notes and (self.developer_comment or notes)): self.developer_comment = notes or None changed = True notes = unit.getnotes(origin="translator") if (self.translator_comment != notes and (self.translator_comment or notes)): self.translator_comment = notes or None changed = True locations = "\n".join(unit.getlocations()) if self.locations != locations and (self.locations or locations): self.locations = locations or None changed = True context = unit.getcontext() if self.context != unit.getcontext() and (self.context or context): self.context = context or None changed = True if self.isfuzzy() != unit.isfuzzy(): self.markfuzzy(unit.isfuzzy()) changed = True if self.isobsolete() != unit.isobsolete(): if unit.isobsolete(): self.makeobsolete() else: self.resurrect(unit.isfuzzy()) changed = True # this is problematic - it compares getid, but then sets getid *or* source if self.unitid != unit.getid(): self.unitid = unicode(unit.getid()) or unicode(unit.source) self.unitid_hash = md5(force_bytes(self.unitid)).hexdigest() changed = True return changed def update_qualitychecks(self, keep_false_positives=False): """Run quality checks and store result in the database. :param keep_false_positives: when set to `False`, it will activate (unmute) any existing false positive checks. :return: `True` if quality checks were updated or `False` if they left unchanged. """ unmute_list = [] result = False checks = self.qualitycheck_set.all() existing = {} for check in checks.values('name', 'false_positive', 'id'): existing[check['name']] = { 'false_positive': check['false_positive'], 'id': check['id'], } # no checks if unit is untranslated if not self.target: if existing: self.qualitycheck_set.all().delete() return True return False checker = self.store.translation_project.checker qc_failures = checker.run_filters(self, categorised=True) checks_to_add = [] for name in qc_failures.iterkeys(): if name in existing: # keep false-positive checks if check is active if (existing[name]['false_positive'] and not keep_false_positives): unmute_list.append(name) del existing[name] continue message = qc_failures[name]['message'] category = qc_failures[name]['category'] checks_to_add.append( QualityCheck( unit=self, name=name, message=message, category=category)) result = True if checks_to_add: self.qualitycheck_set.bulk_create(checks_to_add) if not keep_false_positives and unmute_list: self.qualitycheck_set.filter(name__in=unmute_list) \ .update(false_positive=False) # delete inactive checks if existing: self.qualitycheck_set.filter(name__in=existing).delete() changed = result or bool(unmute_list) or bool(existing) return changed def get_qualitychecks(self): return self.qualitycheck_set.all() def get_critical_qualitychecks(self): return self.get_qualitychecks().filter(category=Category.CRITICAL) def get_active_critical_qualitychecks(self): return self.get_active_qualitychecks().filter( category=Category.CRITICAL) def get_warning_qualitychecks(self): return self.get_qualitychecks().exclude(category=Category.CRITICAL) def get_active_qualitychecks(self): return self.qualitycheck_set.filter(false_positive=False) # # # # # # # # # # # Related Submissions # # # # # # # # # # # # def get_edits(self): return self.submission_set.get_unit_edits() def get_comments(self): return self.submission_set.get_unit_comments() def get_state_changes(self): return self.submission_set.get_unit_state_changes() # # # # # # # # # # # TranslationUnit # # # # # # # # # # # # # # def update_tmserver(self): obj = { 'id': self.id, # 'revision' must be an integer for statistical queries to work 'revision': self.revision, 'project': self.store.translation_project.project.fullname, 'path': self.store.pootle_path, 'source': self.source, 'target': self.target, 'username': '', 'fullname': '', 'email_md5': '', } if self.changed and self.change.submitted_on: obj.update({ 'iso_submitted_on': self.change.submitted_on.isoformat(), 'display_submitted_on': dateformat.format(self.change.submitted_on), }) if self.changed and self.change.submitted_by: obj.update({ 'username': self.change.submitted_by.username, 'fullname': self.change.submitted_by.full_name, 'email_md5': md5( force_bytes(self.change.submitted_by.email)).hexdigest(), }) get_tm_broker().update(self.store.translation_project.language.code, obj) def get_tm_suggestions(self): return get_tm_broker().search(self) # # # # # # # # # # # TranslationUnit # # # # # # # # # # # # # # def getnotes(self, origin=None): if origin is None: notes = '' if self.translator_comment is not None: notes += self.translator_comment if self.developer_comment is not None: notes += self.developer_comment return notes elif origin == "translator": return self.translator_comment or '' elif origin in ["programmer", "developer", "source code"]: return self.developer_comment or '' else: raise ValueError("Comment type not valid") def addnote(self, text, origin=None, position="append"): if not (text and text.strip()): return if origin in ["programmer", "developer", "source code"]: self.developer_comment = text else: self.translator_comment = text def getid(self): return self.unitid def setid(self, value): self.unitid = value self.unitid_hash = md5(force_bytes(self.unitid)).hexdigest() def getlocations(self): if self.locations is None: return [] return filter(None, self.locations.split('\n')) def addlocation(self, location): if self.locations is None: self.locations = '' self.locations += location + "\n" def getcontext(self): return self.context def setcontext(self, value): self.context = value def isfuzzy(self): return self.state == FUZZY def markfuzzy(self, value=True): if self.state <= OBSOLETE: return if value: self.state = FUZZY elif self.state <= FUZZY: if filter(None, self.target_f.strings): self.state = TRANSLATED else: self.state = UNTRANSLATED def hasplural(self): return (self.source is not None and (len(self.source.strings) > 1 or hasattr(self.source, "plural") and self.source.plural)) def isobsolete(self): return self.state == OBSOLETE def makeobsolete(self): self.state = OBSOLETE self.index = 0 def resurrect(self, is_fuzzy=False): if self.state > OBSOLETE: return if filter(None, self.target_f.strings): # when Unit toggles its OBSOLETE state the number of translated # words or fuzzy words also changes if is_fuzzy: self.state = FUZZY else: self.state = TRANSLATED else: self.state = UNTRANSLATED update_checks.send(self.__class__, instance=self, keep_false_positives=True) self.index = self.store.max_index() + 1 def istranslated(self): return self.state >= TRANSLATED # # # # # # # # # # # Suggestions # # # # # # # # # # # # # # # # # def get_suggestions(self): return self.suggestion_set.pending().select_related('user').all() def get_latest_target_submission(self): return (self.submission_set.select_related('suggestion__user') .filter(field=SubmissionFields.TARGET) .order_by('-creation_time', '-id') .first()) def has_critical_checks(self): return self.qualitycheck_set.filter( category=Category.CRITICAL, ).exists() def toggle_qualitycheck(self, check_id, false_positive, user): check = self.qualitycheck_set.get(id=check_id) if check.false_positive == false_positive: return self.revision = Revision.incr() self.save(reviewed_by=user) toggle.send(check.__class__, instance=check, false_positive=false_positive) def get_terminology(self): """get terminology suggestions""" results = terminology_matcher.get(self.__class__)(self).matches return [m[1] for m in results] def get_last_created_unit_info(self): return { "display_datetime": dateformat.format(self.creation_time), "creation_time": int(dateformat.format(self.creation_time, 'U')), "unit_source": truncatechars(self, 50), "unit_url": self.get_translate_url(), } # # # # # # # # # # # Store # # # # # # # # # # # # # # class Store(AbstractStore): """A model representing a translation store (i.e. a PO or XLIFF file).""" UnitClass = Unit Name = "Model Store" is_dir = False class Meta(AbstractStore.Meta): abstract = False db_table = "pootle_store_store" # # # # # # # # # # # # # # Properties # # # # # # # # # # # # # # # # # # @property def code(self): return self.name.replace('.', '-') @property def tp(self): return self.translation_project @property def has_terminology(self): """is this a project specific terminology store?""" # TODO: Consider if this should check if the store belongs to a # terminology project. Probably not, in case this might be called over # several files in a project. return self.name.startswith('pootle-terminology') @property def units(self): if self.obsolete: return self.unit_set.none() return self.unit_set.filter(state__gt=OBSOLETE).order_by( 'index').select_related("change") @units.setter def units(self, value): """Null setter to avoid tracebacks if :meth:`TranslationStore.__init__` is called. """ pass # # # # # # # # # # # # # # Methods # # # # # # # # # # # # # # # # # # # @cached_property def path(self): """Returns just the path part omitting language and project codes. If the `pootle_path` of a :cls:`Store` object `store` is `/af/project/dir1/dir2/file.po`, `store.path` will return `dir1/dir2/file.po`. """ return to_tp_relative_path(self.pootle_path) def __init__(self, *args, **kwargs): super(Store, self).__init__(*args, **kwargs) def __unicode__(self): return unicode(self.pootle_path) def __str__(self): return str(self.syncer.convert()) def save(self, *args, **kwargs): self.pootle_path = self.parent.pootle_path + self.name self.tp_path = self.parent.tp_path + self.name # Force validation of required fields. self.full_clean( validate_unique=False, exclude=[ "translation_project", "parent", "filetype"]) super(Store, self).save(*args, **kwargs) def delete(self, *args, **kwargs): store_log(user='system', action=STORE_DELETED, path=self.pootle_path, store=self.id) super(Store, self).delete(*args, **kwargs) def calculate_priority(self): if not vfolders_installed(): return DEFAULT_PRIORITY from virtualfolder.models import VirtualFolder vfolders = VirtualFolder.objects priority = ( vfolders.filter(stores=self) .aggregate(priority=models.Max("priority"))["priority"]) if priority is None: return DEFAULT_PRIORITY return priority def set_priority(self, priority=None): priority = ( self.calculate_priority() if priority is None else priority) if priority != self.priority: Store.objects.filter(pk=self.pk).update(priority=priority) def makeobsolete(self): """Make this store and all its units obsolete.""" store_log( user='system', action=STORE_OBSOLETE, path=self.pootle_path, store=self.id) self.obsolete = True self.save() update_data.send(self.__class__, instance=self) def resurrect(self, save=True): self.obsolete = False self.file_mtime = datetime_min if self.last_sync_revision is None: self.last_sync_revision = self.data.max_unit_revision if save: self.save() update_data.send(self.__class__, instance=self) def get_absolute_url(self): return reverse( 'pootle-tp-store-browse', args=split_pootle_path(self.pootle_path)) def get_translate_url(self, **kwargs): return u''.join( [reverse("pootle-tp-store-translate", args=split_pootle_path(self.pootle_path)), get_editor_filter(**kwargs)]) def findid_bulk(self, ids, unit_set=None): chunks = 200 for i in xrange(0, len(ids), chunks): units = (unit_set or self.unit_set).filter(id__in=ids[i:i+chunks]) for unit in units.iterator(): yield unit def update_index(self, start, delta): Unit.objects.filter(store_id=self.id, index__gte=start).update( index=operator.add(F('index'), delta)) @cached_property def data_tool(self): return data_tool.get(self.__class__)(self) @cached_property def updater(self): updaters = format_updaters.gather() updater_class = ( updaters.get(self.filetype.name) or updaters.get("default")) return updater_class(self) @cached_property def syncer(self): syncers = format_syncers.gather() syncer_class = ( syncers.get(self.filetype.name) or syncers.get("default")) return syncer_class(self) def update(self, store, user=None, store_revision=None, submission_type=None, resolve_conflict=POOTLE_WINS, allow_add_and_obsolete=True): """Update DB with units from a ttk Store. :param store: a source `Store` instance from TTK. :param store_revision: revision at which the source `Store` was last synced. :param user: User to attribute updates to. :param submission_type: Submission type of saved updates. :param allow_add_and_obsolete: allow to add new units and make obsolete existing units """ return self.updater.update( store, user=user, store_revision=store_revision, submission_type=submission_type, resolve_conflict=resolve_conflict, allow_add_and_obsolete=allow_add_and_obsolete) def deserialize(self, data): return StoreDeserialization(self).deserialize(data) def serialize(self, include_obsolete=False, raw=False): return StoreSerialization(self).serialize( include_obsolete=include_obsolete, raw=raw) # # # # # # # # # # # # TranslationStore # # # # # # # # # # # # # suggestions_in_format = True def max_index(self): """Largest unit index""" return max_column(self.unit_set.all(), 'index', -1) def addunit(self, unit, index=None, user=None, update_revision=None, changed_with=None): if index is None: index = self.max_index() + 1 newunit = self.UnitClass( store=self, index=index) newunit.update(unit, user=user) if self.id: newunit.revision = update_revision newunit.save( user=user, changed_with=changed_with) return newunit def findid(self, id): unitid_hash = md5(force_bytes(id)).hexdigest() try: return self.unit_set.get(unitid_hash=unitid_hash) except Unit.DoesNotExist: return None def header(self): # FIXME: we should store some metadata in db if self.file and hasattr(self.file.store, 'header'): return self.file.store.header() def get_max_unit_revision(self): return max_column(self.unit_set.all(), 'revision', 0) # # # TreeItem def get_parents(self): if self.parent.is_translationproject(): return [self.translation_project] return [self.parent] # # # /TreeItem # # # # # # # # # # # # # # # # Translation # # # # # # # # # # # # # # #
32,799
Python
.py
806
30.80273
84
0.591221
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,287
getters.py
translate_pootle/pootle/apps/pootle_store/getters.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django.conf import settings from django.core.exceptions import ValidationError from pootle.core.delegate import ( comparable_event, deserializers, frozen, grouped_events, lifecycle, review, search_backend, serializers, states, uniqueid, versioned, wordcount) from pootle.core.plugin import getter from pootle_config.delegate import ( config_should_not_be_appended, config_should_not_be_set) from pootle_misc.util import import_func from .models import Store, Suggestion, SuggestionState, Unit from .unit.search import DBSearchBackend from .unit.timeline import ( ComparableUnitTimelineLogEvent, UnitTimelineGroupedEvents, UnitTimelineLog) from .utils import ( FrozenUnit, SuggestionsReview, UnitLifecycle, UnitUniqueId, UnitWordcount) from .versioned import VersionedStore wordcounter = None suggestion_states = None @getter(states, sender=Suggestion) def get_suggestion_states(**kwargs_): global suggestion_states if not suggestion_states: suggestion_states = dict(SuggestionState.objects.values_list("name", "pk")) return suggestion_states @getter(wordcount, sender=Unit) def get_unit_wordcount(**kwargs_): global wordcounter if not wordcounter: wordcounter = UnitWordcount( import_func(settings.POOTLE_WORDCOUNT_FUNC)) return wordcounter @getter(frozen, sender=Unit) def get_frozen_unit(**kwargs_): return FrozenUnit @getter(search_backend, sender=Unit) def get_search_backend(**kwargs_): return DBSearchBackend @getter(review, sender=Suggestion) def get_suggestions_review(**kwargs_): return SuggestionsReview @getter(uniqueid, sender=Unit) def get_unit_uniqueid(**kwargs_): return UnitUniqueId @getter(lifecycle, sender=Unit) def get_unit_lifecylcle(**kwargs_): return UnitLifecycle @getter(comparable_event, sender=UnitTimelineLog) def get_unit_timeline_log_comparable_event(**kwargs_): return ComparableUnitTimelineLogEvent @getter(grouped_events, sender=UnitTimelineLog) def get_unit_timeline_log_grouped_events(**kwargs_): return UnitTimelineGroupedEvents @getter([config_should_not_be_set, config_should_not_be_appended]) def serializer_should_not_be_saved(**kwargs): if kwargs["key"] == "pootle.core.serializers": if not isinstance(kwargs["value"], list): return ValidationError( "pootle.core.serializers must be a list") available_serializers = serializers.gather(kwargs["sender"]).keys() for k in kwargs["value"]: if k not in available_serializers: return ValidationError( "Unrecognised pootle.core.serializers: '%s'" % k) elif kwargs["key"] == "pootle.core.deserializers": if not isinstance(kwargs["value"], list): return ValidationError( "pootle.core.deserializers must be a list") available_deserializers = deserializers.gather(kwargs["sender"]).keys() for k in kwargs["value"]: if k not in available_deserializers: return ValidationError( "Unrecognised pootle.core.deserializers: '%s'" % k) @getter(versioned, sender=Store) def get_versioned_store(**kwargs_): return VersionedStore
3,525
Python
.py
83
37.301205
83
0.738277
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,288
util.py
translate_pootle/pootle/apps/pootle_store/util.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django.conf import settings from .constants import STATES_NAMES, TRANSLATED from .unit.altsrc import AltSrcUnits def find_altsrcs(unit, alt_src_langs, store=None, project=None): from pootle_store.models import Unit if not alt_src_langs: return [] store = store or unit.store project = project or store.translation_project.project altsrcs_qs = Unit.objects.filter( unitid_hash=unit.unitid_hash, store__translation_project__project=project, store__translation_project__language__in=alt_src_langs, state=TRANSLATED) return AltSrcUnits(altsrcs_qs).units def get_change_str(changes): """Returns a formatted string for the non-zero items of a `changes` dictionary. If all elements are zero, `nothing changed` is returned. """ res = [u'%s %d' % (key, changes[key]) for key in changes if changes[key] > 0] if res: return ", ".join(res) return "no changed" def parse_pootle_revision(store): if hasattr(store, "parseheader"): pootle_revision = store.parseheader().get("X-Pootle-Revision", None) if pootle_revision is not None: return int(pootle_revision) return None def get_state_name(code, default="untranslated"): return STATES_NAMES.get(code, default) def vfolders_installed(): return "virtualfolder" in settings.INSTALLED_APPS
1,725
Python
.py
43
33.930233
77
0.689303
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,289
syncer.py
translate_pootle/pootle/apps/pootle_store/syncer.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import logging import os from collections import namedtuple from translate.storage.factory import getclass from django.utils.functional import cached_property from pootle.core.delegate import format_classes from .models import Unit logger = logging.getLogger(__name__) class UnitSyncer(object): def __init__(self, unit, raw=False): self.unit = unit self.raw = raw @property def context(self): return self.unit.getcontext() @property def developer_notes(self): return self.unit.getnotes(origin="developer") @property def isfuzzy(self): return self.unit.isfuzzy() @property def isobsolete(self): return self.unit.isobsolete() @property def locations(self): return self.unit.getlocations() @property def source(self): return self.unit.source @property def target(self): return self.unit.target @property def translator_notes(self): return self.unit.getnotes(origin="translator") @property def unitid(self): return self.unit.getid() @property def unit_class(self): return self.unit.store.syncer.unit_class def convert(self, unitclass=None): newunit = self.create_unit( unitclass or self.unit_class) self.set_target(newunit) self.set_fuzzy(newunit) self.set_locations(newunit) self.set_developer_notes(newunit) self.set_translator_notes(newunit) self.set_unitid(newunit) self.set_context(newunit) self.set_obsolete(newunit) return newunit def create_unit(self, unitclass): return unitclass(self.source) def set_context(self, newunit): newunit.setcontext(self.context) def set_developer_notes(self, newunit): notes = self.developer_notes if notes: newunit.addnote(notes, origin="developer") def set_fuzzy(self, newunit): newunit.markfuzzy(self.isfuzzy) def set_locations(self, newunit): locations = self.locations if locations: newunit.addlocations(locations) def set_obsolete(self, newunit): if self.isobsolete: newunit.makeobsolete() def set_target(self, newunit): newunit.target = self.target def set_translator_notes(self, newunit): notes = self.translator_notes if notes: newunit.addnote(notes, origin="translator") def set_unitid(self, newunit): newunit.setid(self.unitid) class StoreSyncer(object): unit_sync_class = UnitSyncer def __init__(self, store): self.store = store @property def translation_project(self): return self.store.translation_project @property def language(self): return self.translation_project.language @property def project(self): return self.translation_project.project @property def source_language(self): return self.project.source_language @property def unit_class(self): return self.file_class.UnitClass @cached_property def file_class(self): # get a plugin adapted file_class fileclass = format_classes.gather().get( str(self.store.filetype.extension)) if fileclass: return fileclass if self.store.is_template: # namedtuple is equiv here of object() with name attr return self._getclass( namedtuple("instance", "name")( name=".".join( [os.path.splitext(self.store.name)[0], str(self.store.filetype.extension)]))) return self._getclass(self.store) def convert(self, fileclass=None, include_obsolete=False, raw=False): """export to fileclass""" fileclass = fileclass or self.file_class logger.debug( u"[sync] Converting: %s to %s", self.store.pootle_path, fileclass) output = fileclass() output.settargetlanguage(self.language.code) # FIXME: we should add some headers units = ( self.store.unit_set if include_obsolete else self.store.units) for unit in units.iterator(): output.addunit( self.unit_sync_class(unit, raw=raw).convert(output.UnitClass)) return output def _getclass(self, obj): try: return getclass(obj) except ValueError: raise ValueError( "Unable to find conversion class for Store '%s'" % self.store.name) def get_new_units(self, old_ids, new_ids): return self.store.findid_bulk( [self.dbid_index.get(uid) for uid in new_ids - old_ids]) def get_units_to_obsolete(self, disk_store, old_ids, new_ids): for uid in old_ids - new_ids: unit = disk_store.findid(uid) if unit and not unit.isobsolete(): yield unit def obsolete_unit(self, unit, conservative): deleted = not unit.istranslated() obsoleted = ( not deleted and not conservative) if obsoleted: unit.makeobsolete() deleted = not unit.isobsolete() if deleted: del unit return obsoleted, deleted def update_structure(self, disk_store, obsolete_units, new_units, conservative): obsolete = 0 deleted = 0 added = 0 for unit in obsolete_units: _obsolete, _deleted = self.obsolete_unit(unit, conservative) if _obsolete: obsolete += 1 if _deleted: deleted += 1 for unit in new_units: newunit = unit.convert(disk_store.UnitClass) disk_store.addunit(newunit) added += 1 return obsolete, deleted, added @cached_property def dbid_index(self): """build a quick mapping index between unit ids and database ids""" return dict( self.store.unit_set.live().values_list('unitid', 'id')) def sync(self, disk_store, last_revision, update_structure=False, conservative=True): logger.debug(u"[sync] Syncing: %s", self.store.pootle_path) old_ids = set(disk_store.getids()) new_ids = set(self.dbid_index.keys()) file_changed = False changes = {} if update_structure: obsolete_units = self.get_units_to_obsolete( disk_store, old_ids, new_ids) new_units = self.get_new_units(old_ids, new_ids) if obsolete_units or new_units: file_changed = True (changes['obsolete'], changes['deleted'], changes['added']) = self.update_structure( disk_store, obsolete_units, new_units, conservative=conservative) changes["updated"] = self.sync_units( disk_store, self.get_common_units( set(self.dbid_index.get(uid) for uid in old_ids & new_ids), last_revision, conservative)) return bool(file_changed or any(changes.values())), changes def get_revision_filters(self, last_revision): # Get units modified after last sync and before this sync started filter_by = { 'revision__lte': last_revision, 'store': self.store} # Sync all units if first sync if self.store.last_sync_revision is not None: filter_by.update({'revision__gt': self.store.last_sync_revision}) return filter_by def get_modified_units(self, last_revision): return set( Unit.objects.filter(**self.get_revision_filters(last_revision)) .values_list('id', flat=True).distinct() if last_revision > self.store.last_sync_revision else []) def get_common_units(self, common_dbids, last_revision, conservative): if conservative: # Sync only modified units common_dbids &= self.get_modified_units(last_revision) return self.store.findid_bulk(list(common_dbids)) def sync_units(self, disk_store, units): updated = 0 for unit in units: match = disk_store.findid(unit.getid()) if match is not None: changed = unit.sync(match, unitclass=self.unit_sync_class) if changed: updated += 1 return updated def update_store_header(self, disk_store, **kwargs_): disk_store.settargetlanguage(self.language.code) disk_store.setsourcelanguage(self.source_language.code)
9,184
Python
.py
247
27.477733
84
0.608666
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,290
abstracts.py
translate_pootle/pootle/apps/pootle_store/abstracts.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from translate.filters.decorators import Category from translate.storage import base from django.conf import settings from django.core.validators import MaxLengthValidator, MinValueValidator from django.db import models from pootle.core.mixins import CachedTreeItem from pootle.core.user import get_system_user, get_system_user_id from pootle.core.utils.timezone import datetime_min from pootle.i18n.gettext import ugettext_lazy as _ from pootle_format.models import Format from pootle_statistics.models import SubmissionTypes from .constants import NEW, UNTRANSLATED from .fields import MultiStringField from .managers import StoreManager from .validators import validate_no_slashes class AbstractUnitChange(models.Model): class Meta(object): abstract = True unit = models.OneToOneField( "pootle_store.Unit", db_index=True, null=False, blank=False, related_name="change", on_delete=models.CASCADE) changed_with = models.IntegerField( null=False, blank=False, db_index=True) # unit translator submitted_by = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, related_name='submitted', db_index=True, on_delete=models.SET(get_system_user)) submitted_on = models.DateTimeField(db_index=True, null=True) commented_by = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, related_name='commented', db_index=True, on_delete=models.SET(get_system_user)) commented_on = models.DateTimeField(db_index=True, null=True) # reviewer: who has accepted suggestion or removed FUZZY # None if translation has been submitted by approved translator reviewed_by = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='reviewed', null=True, db_index=True, on_delete=models.SET(get_system_user)) reviewed_on = models.DateTimeField(db_index=True, null=True) class AbstractUnitSource(models.Model): class Meta(object): abstract = True unit = models.OneToOneField( "pootle_store.Unit", db_index=True, null=False, blank=False, related_name="unit_source", on_delete=models.CASCADE) created_by = models.ForeignKey( settings.AUTH_USER_MODEL, null=False, blank=False, db_index=True, related_name='created_units', default=get_system_user_id, on_delete=models.SET(get_system_user)) created_with = models.IntegerField( null=False, blank=False, default=SubmissionTypes.SYSTEM, db_index=True) creation_revision = models.IntegerField( null=False, default=0, db_index=True, blank=True) source_hash = models.CharField( null=True, max_length=32, editable=False) source_wordcount = models.SmallIntegerField( default=0, editable=False) source_length = models.SmallIntegerField( default=0, editable=False) class AbstractUnit(models.Model, base.TranslationUnit): store = models.ForeignKey( "pootle_store.Store", db_index=False, on_delete=models.CASCADE) index = models.IntegerField(db_index=True) unitid = models.TextField(editable=False) unitid_hash = models.CharField(max_length=32, db_index=True, editable=False) source_f = MultiStringField(null=True) target_f = MultiStringField(null=True, blank=True) target_wordcount = models.SmallIntegerField(default=0, editable=False) target_length = models.SmallIntegerField(db_index=True, default=0, editable=False) developer_comment = models.TextField( null=True, blank=True, validators=[MaxLengthValidator(4096)]) translator_comment = models.TextField( null=True, blank=True, validators=[MaxLengthValidator(4096)]) locations = models.TextField( null=True, editable=False, validators=[MaxLengthValidator(4096)]) context = models.TextField( null=True, editable=False, validators=[MaxLengthValidator(4096)]) state = models.IntegerField(null=False, default=UNTRANSLATED, db_index=True) revision = models.IntegerField(null=False, default=0, db_index=True, blank=True) # Metadata creation_time = models.DateTimeField(auto_now_add=True, db_index=True, editable=False, null=True) mtime = models.DateTimeField(auto_now=True, db_index=True, editable=False) class Meta(object): abstract = True class AbstractQualityCheck(models.Model): """Database cache of results of qualitychecks on unit.""" class Meta(object): abstract = True name = models.CharField(max_length=64, db_index=True) unit = models.ForeignKey( "pootle_store.Unit", db_index=True, on_delete=models.CASCADE) category = models.IntegerField(null=False, default=Category.NO_CATEGORY) message = models.TextField(validators=[MaxLengthValidator(4096)]) false_positive = models.BooleanField(default=False, db_index=True) class AbstractStore(models.Model, CachedTreeItem, base.TranslationStore): parent = models.ForeignKey( 'pootle_app.Directory', related_name='child_stores', editable=False, db_index=False, on_delete=models.CASCADE) translation_project_fk = 'pootle_translationproject.TranslationProject' translation_project = models.ForeignKey( translation_project_fk, related_name='stores', editable=False, db_index=False, on_delete=models.CASCADE) filetype = models.ForeignKey( Format, related_name='stores', null=True, blank=True, db_index=True, on_delete=models.CASCADE) is_template = models.BooleanField(default=False) # any changes to the `pootle_path` field may require updating the schema # see migration 0007_case_sensitive_schema.py pootle_path = models.CharField( max_length=255, null=False, unique=True, db_index=True, verbose_name=_("Path")) tp_path = models.CharField( max_length=255, null=True, blank=True, db_index=True, verbose_name=_("Path")) # any changes to the `name` field may require updating the schema # see migration 0007_case_sensitive_schema.py name = models.CharField( max_length=128, null=False, editable=False, validators=[validate_no_slashes]) file_mtime = models.DateTimeField(default=datetime_min) state = models.IntegerField( null=False, default=NEW, editable=False, db_index=True) creation_time = models.DateTimeField( auto_now_add=True, db_index=True, editable=False, null=True) last_sync_revision = models.IntegerField( db_index=True, null=True, blank=True) obsolete = models.BooleanField(default=False) # this is calculated from virtualfolders if installed and linked priority = models.FloatField( db_index=True, default=1, validators=[MinValueValidator(0)]) objects = StoreManager() class Meta(object): ordering = ['pootle_path'] index_together = [ ["translation_project", "is_template"], ["translation_project", "pootle_path", "is_template", "filetype"]] unique_together = ( ('parent', 'name'), ("obsolete", "translation_project", "tp_path")) base_manager_name = "objects" abstract = True class AbstractSuggestion(models.Model, base.TranslationUnit): """Abstract suggestion""" class Meta(object): abstract = True target_f = MultiStringField() target_hash = models.CharField(max_length=32, db_index=True) unit = models.ForeignKey('pootle_store.Unit', on_delete=models.CASCADE) user = models.ForeignKey( settings.AUTH_USER_MODEL, null=False, related_name='suggestions', db_index=True, on_delete=models.SET(get_system_user)) reviewer = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, related_name='reviews', db_index=True, on_delete=models.SET(get_system_user)) creation_time = models.DateTimeField(db_index=True, null=True) review_time = models.DateTimeField(null=True, db_index=True) state = models.ForeignKey( "pootle_store.SuggestionState", null=True, related_name='suggestions', db_index=True, on_delete=models.SET_NULL) class AbstractSuggestionState(models.Model): """Database cache of results of qualitychecks on unit.""" class Meta(object): abstract = True name = models.CharField( max_length=16, null=False, db_index=True)
9,471
Python
.py
260
28.688462
78
0.662698
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,291
urls.py
translate_pootle/pootle/apps/pootle_store/urls.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django.conf.urls import url from . import views get_units_urlpatterns = [ url(r'^xhr/units/?$', views.get_units, name='pootle-xhr-units')] unit_xhr_urlpatterns = [ # XHR url(r'^xhr/units/(?P<uid>[0-9]+)/?$', views.UnitSubmitJSON.as_view(), name='pootle-xhr-units-submit'), url(r'^xhr/units/(?P<uid>[0-9]+)/comment/?$', views.comment, name='pootle-xhr-units-comment'), url(r'^xhr/units/(?P<uid>[0-9]+)/context/?$', views.get_more_context, name='pootle-xhr-units-context'), url(r'^xhr/units/(?P<uid>[0-9]+)/edit/?$', views.UnitEditJSON.as_view(), name='pootle-xhr-units-edit'), url(r'^xhr/units/(?P<uid>[0-9]+)/timeline/?$', views.UnitTimelineJSON.as_view(), name='pootle-xhr-units-timeline'), url(r'^xhr/units/(?P<uid>[0-9]+)/suggestions/?$', views.UnitAddSuggestionJSON.as_view(), name='pootle-xhr-units-suggest'), url(r'^xhr/units/(?P<uid>[0-9]+)/suggestions/(?P<sugg_id>[0-9]+)/?$', views.UnitSuggestionJSON.as_view(), name='pootle-xhr-units-suggest-manage'), url(r'^xhr/units/(?P<uid>[0-9]+)/checks/(?P<check_id>[0-9]+)/toggle/?$', views.toggle_qualitycheck, name='pootle-xhr-units-checks-toggle'), ] urlpatterns = ( [url(r'^unit/(?P<uid>[0-9]+)/?$', views.permalink_redirect, name='pootle-unit-permalink')] + get_units_urlpatterns + unit_xhr_urlpatterns)
1,762
Python
.py
46
32.456522
77
0.618043
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,292
constants.py
translate_pootle/pootle/apps/pootle_store/constants.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from pootle.i18n.gettext import ugettext_lazy as _ #: Mapping of allowed sorting criteria. #: Keys are supported query strings, values are the field + order that #: will be used against the DB. ALLOWED_SORTS = { 'units': { 'priority': '-store__priority', 'oldest': 'change__submitted_on', 'newest': '-change__submitted_on', }, 'suggestions': { 'oldest': 'suggestion__creation_time', 'newest': '-suggestion__creation_time', }, 'submissions': { 'oldest': 'submission__creation_time', 'newest': '-submission__creation_time', }, } #: List of fields from `ALLOWED_SORTS` that can be sorted by simply using #: `order_by(field)` SIMPLY_SORTED = ['units'] # # Store States # # Store just created, not parsed yet NEW = 0 # Store just parsed, units added but no quality checks were run PARSED = 1 # Quality checks run CHECKED = 2 # Resolve conflict flags for Store.update POOTLE_WINS = 1 SOURCE_WINS = 2 LANGUAGE_REGEX = r"[^/]{2,255}" PROJECT_REGEX = r"[^/]{1,255}" # Unit States #: Unit is no longer part of the store OBSOLETE = -100 #: Empty unit UNTRANSLATED = 0 #: Marked as fuzzy, typically means translation needs more work FUZZY = 50 #: Unit is fully translated TRANSLATED = 200 # Map for retrieving natural names for unit states STATES_MAP = { OBSOLETE: _("Obsolete"), UNTRANSLATED: _("Untranslated"), FUZZY: _("Needs work"), TRANSLATED: _("Translated"), } STATES_NAMES = { OBSOLETE: "obsolete", UNTRANSLATED: "untranslated", FUZZY: "fuzzy", TRANSLATED: "translated"} # Default store priority - used by vfolders atm # - valid range = 0 < n <= 999.99 DEFAULT_PRIORITY = 1.0
1,972
Python
.py
67
26.58209
77
0.690438
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,293
apps.py
translate_pootle/pootle/apps/pootle_store/apps.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import importlib from django.apps import AppConfig class PootleStoreConfig(AppConfig): name = "pootle_store" verbose_name = "Pootle Store" def ready(self): importlib.import_module("pootle_store.getters") importlib.import_module("pootle_store.providers") importlib.import_module("pootle_store.receivers")
621
Python
.py
16
35.1875
77
0.746244
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,294
receivers.py
translate_pootle/pootle/apps/pootle_store/receivers.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from hashlib import md5 from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from django.utils.encoding import force_bytes from pootle.core.delegate import lifecycle, uniqueid from pootle.core.models import Revision from pootle.core.signals import update_checks, update_data from .constants import FUZZY, TRANSLATED, UNTRANSLATED from .models import Suggestion, Unit, UnitChange, UnitSource @receiver(post_save, sender=Suggestion) def handle_suggestion_added(**kwargs): created = kwargs.get("created") if not created: return store = kwargs["instance"].unit.store update_data.send(store.__class__, instance=store) @receiver(post_save, sender=Suggestion) def handle_suggestion_accepted(**kwargs): created = kwargs.get("created") suggestion = kwargs["instance"] if created or not suggestion.is_accepted: return update_data.send( suggestion.unit.store.__class__, instance=suggestion.unit.store) @receiver(pre_save, sender=UnitSource) def handle_unit_source_pre_save(**kwargs): unit_source = kwargs["instance"] created = not unit_source.pk unit = unit_source.unit if created: unit_source.creation_revision = unit.revision if created or unit.source_updated: unit_source.source_hash = md5(force_bytes(unit.source_f)).hexdigest() unit_source.source_length = len(unit.source_f) unit_source.source_wordcount = ( unit.counter.count_words(unit.source_f.strings) or 0) @receiver(pre_save, sender=Unit) def handle_unit_pre_save(**kwargs): unit = kwargs["instance"] auto_translated = False if unit.source_updated: # update source related fields wc = unit.counter.count_words(unit.source_f.strings) if not wc and not bool(filter(None, unit.target_f.strings)): # auto-translate untranslated strings unit.target = unit.source unit.state = FUZZY auto_translated = True if unit.target_updated: # update target related fields unit.target_wordcount = unit.counter.count_words( unit.target_f.strings) unit.target_length = len(unit.target_f) if filter(None, unit.target_f.strings): if unit.state == UNTRANSLATED: unit.state = TRANSLATED else: # if it was TRANSLATED then set to UNTRANSLATED if unit.state > FUZZY: unit.state = UNTRANSLATED # Updating unit from the .po file set its revision property to # a new value (the same for all units during its store updated) # since that change doesn't require further sync but note that # auto_translated units require further sync update_revision = ( unit.revision is None or (not unit.revision_updated and (unit.updated and not auto_translated))) if update_revision: unit.revision = Revision.incr() if unit.index is None: unit.index = unit.store.max_index() + 1 unitid = uniqueid.get(unit.__class__)(unit) if unitid.changed: unit.setid(unitid.getid()) @receiver(post_save, sender=UnitChange) def handle_unit_change(**kwargs): unit_change = kwargs["instance"] unit = unit_change.unit created = not unit._frozen.pk if not created: lifecycle.get(Unit)(unit).change() if not unit.source_updated and not unit.target_updated: return new_untranslated = (created and unit.state == UNTRANSLATED) if not new_untranslated: update_checks.send(unit.__class__, instance=unit) if unit.istranslated(): unit.update_tmserver()
3,964
Python
.py
98
34.163265
77
0.692048
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,295
utils.py
translate_pootle/pootle/apps/pootle_store/utils.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from collections import OrderedDict from django.conf import settings from django.contrib.auth import get_user_model from django.template import loader from django.utils import timezone from django.utils.functional import cached_property from pootle.core.delegate import site, states, unitid from pootle.core.mail import send_mail from pootle.core.signals import update_data, update_scores from pootle.core.utils.timezone import datetime_min, localdate, make_aware from pootle.i18n.gettext import ugettext as _ from pootle_statistics.models import ( MUTED, UNMUTED, SubmissionFields, SubmissionTypes) from .constants import TRANSLATED from .models import Suggestion User = get_user_model() class UnitWordcount(object): def __init__(self, counter): self.counter = counter def count(self, string): return self.counter(string) def count_words(self, strings): return sum(self.count(string) for string in strings) class DefaultUnitid(object): def __init__(self, unit): self.unit = unit @property def changed(self): return ( self.unit.source_updated or self.unit.context_updated) @property def unit_sync_class(self): return self.unit.store.syncer.unit_sync_class def getid(self): return self.unit_sync_class( self.unit).convert().getid() class UnitUniqueId(object): def __init__(self, unit): self.unit = unit @property def format_name(self): return self.unit.store.filetype.name @property def format_unitid(self): format_unitids = unitid.gather(self.unit.__class__) return ( format_unitids[self.format_name](self.unit) if self.format_name in format_unitids else format_unitids["default"](self.unit)) @property def changed(self): return self.format_unitid.changed def getid(self): return self.format_unitid.getid() class FrozenUnit(object): """Freeze unit vars for comparison""" def __init__(self, unit): self.unit = dict( source_f=unit.source_f, target_f=unit.target_f, context=unit.context, revision=unit.revision, state=unit.state, pk=unit.pk, translator_comment=unit.translator_comment) @property def context(self): return self.unit["context"] @property def pk(self): return self.unit["pk"] @property def revision(self): return self.unit["revision"] @property def source(self): return self.unit["source_f"] @property def state(self): return self.unit["state"] @property def submitter(self): return self.unit["submitter"] @property def target(self): return self.unit["target_f"] @property def translator_comment(self): return self.unit["translator_comment"] class SuggestionsReview(object): accept_email_template = 'editor/email/suggestions_accepted_with_comment.txt' accept_email_subject = _(u"Suggestion accepted with comment") reject_email_template = 'editor/email/suggestions_rejected_with_comment.txt' reject_email_subject = _(u"Suggestion rejected with comment") def __init__(self, suggestions=None, reviewer=None, review_type=None): self.suggestions = suggestions self.reviewer = reviewer or User.objects.get_system_user() self._review_type = review_type @property def review_type(self): return ( SubmissionTypes.SYSTEM if self._review_type is None else self._review_type) @property def users_and_suggestions(self): users = {} for suggestion in self.suggestions: users[suggestion.user] = users.get(suggestion.user, []) users[suggestion.user].append(suggestion) return users @cached_property def states(self): return states.get(Suggestion) def add(self, unit, translation, user=None): """Adds a new suggestion to the unit. :param translation: suggested translation text :param user: user who is making the suggestion. If it's ``None``, the ``system`` user will be used. :return: a tuple ``(suggestion, created)`` where ``created`` is a boolean indicating if the suggestion was successfully added. If the suggestion already exists it's returned as well. """ dont_add = ( not filter(None, translation) or translation == unit.target or unit.get_suggestions().filter(target_f=translation).exists()) if dont_add: return (None, False) if isinstance(user, User): user = user.id user = user or User.objects.get_system_user().id try: suggestion = Suggestion.objects.pending().get( unit=unit, user_id=user, target_f=translation) return (suggestion, False) except Suggestion.DoesNotExist: suggestion = Suggestion.objects.create( unit=unit, user_id=user, state_id=self.states["pending"], target=translation, creation_time=make_aware(timezone.now())) return (suggestion, True) def update_unit_on_accept(self, suggestion, target=None): unit = suggestion.unit unit.target = target or suggestion.target if unit.isfuzzy(): unit.state = TRANSLATED unit.save( user=suggestion.user, changed_with=self.review_type, reviewed_by=self.reviewer) def accept_suggestion(self, suggestion, target=None): suggestion.state_id = self.states["accepted"] suggestion.reviewer = self.reviewer old_revision = suggestion.unit.revision self.update_unit_on_accept(suggestion, target=target) if suggestion.unit.revision > old_revision: suggestion.submission_set.add( *suggestion.unit.submission_set.filter( revision=suggestion.unit.revision)) suggestion.review_time = suggestion.unit.mtime else: suggestion.review_time = timezone.now() suggestion.save() def reject_suggestion(self, suggestion): store = suggestion.unit.store suggestion.state_id = self.states["rejected"] suggestion.review_time = make_aware(timezone.now()) suggestion.reviewer = self.reviewer suggestion.save() unit = suggestion.unit if unit.changed: # if the unit is translated and suggestion was rejected # set the reviewer info unit.change.reviewed_by = self.reviewer unit.change.reviewed_on = suggestion.review_time unit.change.save() update_data.send(store.__class__, instance=store) def accept_suggestions(self, target=None): for suggestion in self.suggestions: self.accept_suggestion(suggestion, target=target) def accept(self, comment="", target=None): self.accept_suggestions(target=target) if self.should_notify(comment): self.notify_suggesters(rejected=False, comment=comment) def build_absolute_uri(self, url): return site.get().build_absolute_uri(url) def get_email_message(self, suggestions, comment, template): for suggestion in suggestions: suggestion.unit_url = ( self.build_absolute_uri( suggestion.unit.get_translate_url())) return loader.render_to_string( template, context=dict(suggestions=suggestions, comment=comment)) def notify_suggesters(self, rejected=True, comment=""): for suggester, suggestions in self.users_and_suggestions.items(): if rejected: template = self.reject_email_template subject = self.reject_email_subject else: template = self.accept_email_template subject = self.accept_email_subject self.send_mail(template, subject, suggester, suggestions, comment) def reject_suggestions(self): for suggestion in self.suggestions: self.reject_suggestion(suggestion) def reject(self, comment=""): self.reject_suggestions() if self.should_notify(comment): self.notify_suggesters(rejected=True, comment=comment) def send_mail(self, template, subject, suggester, suggestions, comment): send_mail( subject, self.get_email_message( suggestions, comment, template), from_email=None, recipient_list=[suggester.email], fail_silently=True) def should_notify(self, comment): return ( comment and settings.POOTLE_EMAIL_FEEDBACK_ENABLED) class UnitLifecycle(object): def __init__(self, unit): self.unit = unit @property def original(self): return self.unit._frozen @property def submission_model(self): return self.unit.submission_set.model def create_submission(self, **kwargs): _kwargs = dict( translation_project=self.unit.store.translation_project, unit=self.unit, revision=self.unit.revision) _kwargs.update(kwargs) return self.submission_model(**_kwargs) def sub_mute_qc(self, **kwargs): quality_check = kwargs["quality_check"] submitter = kwargs["submitter"] _kwargs = dict( creation_time=make_aware(timezone.now()), submitter=submitter, field=SubmissionFields.CHECK, type=SubmissionTypes.WEB, old_value=UNMUTED, new_value=MUTED, quality_check=quality_check) _kwargs.update(kwargs) return self.create_submission(**_kwargs) def sub_unmute_qc(self, **kwargs): quality_check = kwargs["quality_check"] submitter = kwargs["submitter"] _kwargs = dict( creation_time=make_aware(timezone.now()), submitter=submitter, field=SubmissionFields.CHECK, type=SubmissionTypes.WEB, old_value=MUTED, new_value=UNMUTED, quality_check=quality_check) _kwargs.update(kwargs) return self.create_submission(**_kwargs) def save_subs(self, subs): subs = list(subs) if not subs: return self.unit.submission_set.bulk_create(subs) update_scores.send( self.unit.store.__class__, instance=self.unit.store, users=[sub.submitter_id for sub in subs], date=localdate(self.unit.mtime)) def sub_comment_update(self, **kwargs): _kwargs = dict( creation_time=self.unit.mtime, unit=self.unit, submitter=self.unit.change.commented_by, field=SubmissionFields.COMMENT, type=self.unit.change.changed_with, old_value=self.original.translator_comment or "", new_value=self.unit.translator_comment or "") _kwargs.update(kwargs) return self.create_submission(**_kwargs) def sub_source_update(self, **kwargs): _kwargs = dict( creation_time=self.unit.mtime, unit=self.unit, submitter=self.unit.change.submitted_by, field=SubmissionFields.SOURCE, type=self.unit.change.changed_with, old_value=self.original.source or "", new_value=self.unit.source_f) _kwargs.update(kwargs) return self.create_submission(**_kwargs) def sub_target_update(self, **kwargs): submitter = ( self.unit.change.submitted_by if self.unit.change.submitted_by else self.unit.change.reviewed_by) _kwargs = dict( creation_time=self.unit.mtime, unit=self.unit, submitter=submitter, field=SubmissionFields.TARGET, type=self.unit.change.changed_with, old_value=self.original.target or "", new_value=self.unit.target_f) _kwargs.update(kwargs) return self.create_submission(**_kwargs) def sub_state_update(self, **kwargs): reviewed_on = self.unit.change.reviewed_on submitted_on = ( self.unit.change.submitted_on or datetime_min) is_review = ( reviewed_on and (reviewed_on > submitted_on)) if is_review: submitter = self.unit.change.reviewed_by else: submitter = self.unit.change.submitted_by _kwargs = dict( creation_time=self.unit.mtime, unit=self.unit, submitter=submitter, field=SubmissionFields.STATE, type=self.unit.change.changed_with, old_value=self.original.state, new_value=self.unit.state) _kwargs.update(kwargs) return self.create_submission(**_kwargs) def update(self, updates): self.save_subs(self.create_subs(updates)) def create_subs(self, updates): for name, update in updates.items(): yield getattr(self, "sub_%s" % name)(**update) def calculate_change(self, **kwargs): updates = OrderedDict() if self.unit.comment_updated: updates["comment_update"] = kwargs if self.unit.source_updated: updates["source_update"] = kwargs if self.unit.target_updated: updates["target_update"] = kwargs if self.unit.state_updated: updates["state_update"] = kwargs return updates def change(self, **kwargs): self.update(self.calculate_change(**kwargs))
14,335
Python
.py
367
29.498638
80
0.626556
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,296
__init__.py
translate_pootle/pootle/apps/pootle_store/__init__.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. default_app_config = 'pootle_store.apps.PootleStoreConfig'
335
Python
.py
8
40.75
77
0.766871
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,297
validators.py
translate_pootle/pootle/apps/pootle_store/validators.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django.core.exceptions import ValidationError def validate_no_slashes(value): if '/' in value: raise ValidationError('Store name cannot contain "/" characters') if '\\' in value: raise ValidationError('Store name cannot contain "\\" characters')
554
Python
.py
13
39.461538
77
0.733706
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,298
updater.py
translate_pootle/pootle/apps/pootle_store/updater.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import logging from django.contrib.auth import get_user_model from django.utils.functional import cached_property from pootle.core.delegate import frozen, review, versioned from pootle.core.models import Revision from pootle_store.contextmanagers import update_store_after from .constants import OBSOLETE, PARSED, POOTLE_WINS from .diff import StoreDiff from .models import Suggestion from .util import get_change_str logger = logging.getLogger(__name__) class StoreUpdate(object): """Wraps either a db or file store with instructions for updating a target db store """ def __init__(self, source_store, target_store, **kwargs): self.source_store = source_store self.target_store = target_store self.kwargs = kwargs def find_source_unit(self, uid): return self.source_store.findid(uid) def get_index(self, uid): return self.indices[uid]['index'] @property def uids(self): return list(self.kwargs["uids"]) @property def change_indices(self): return self.kwargs["change_indices"] @property def indices(self): return self.kwargs["indices"] @property def store_revision(self): return self.kwargs["store_revision"] @property def submission_type(self): return self.kwargs["submission_type"] @property def update_revision(self): return self.kwargs["update_revision"] @property def resolve_conflict(self): return self.kwargs["resolve_conflict"] @property def user(self): return self.kwargs["user"] @property def suggest_on_conflict(self): return self.kwargs.get("suggest_on_conflict", True) @property def versioned_store(self): return versioned.get( self.target_store.__class__)(self.target_store) @cached_property def last_sync_store(self): return self.versioned_store.at_revision( self.store_revision or 0) class UnitUpdater(object): """Updates a unit from a source with configuration""" def __init__(self, db_unit, update): self.db_unit = db_unit self.update = update self.original = frozen.get(db_unit.__class__)(db_unit) self.original_submitter = ( db_unit.changed and db_unit.change.submitted_by) @cached_property def old_unit(self): return self.update.last_sync_store.findid( self.db_unit.getid()) @property def uid(self): return self.db_unit.getid() @cached_property def newunit(self): return self.update.find_source_unit(self.uid) @cached_property def db_comment_updated(self): if not self.old_unit: return True return (self.db_unit.translator_comment or "" != self.old_unit.getnotes(origin="translator")) @cached_property def db_state_updated(self): if not self.old_unit: return True return not ( self.db_unit.isfuzzy() == self.old_unit.isfuzzy() and self.db_unit.istranslated() == self.old_unit.istranslated() and self.db_unit.isobsolete() == self.old_unit.isobsolete()) @cached_property def db_target_updated(self): if not self.old_unit: return True return self.db_unit.target != self.old_unit.target @cached_property def fs_comment_updated(self): if not self.old_unit and self.newunit: return True return ( self.old_unit and self.newunit and (self.newunit.getnotes(origin="translator") != self.old_unit.getnotes(origin="translator"))) @cached_property def fs_state_updated(self): if not self.old_unit and self.newunit: return True return not ( self.newunit.isfuzzy() == self.old_unit.isfuzzy() and self.newunit.istranslated() == self.old_unit.istranslated() and self.newunit.isobsolete() == self.old_unit.isobsolete()) @cached_property def fs_target_updated(self): if not self.old_unit and self.newunit: return True return ( self.newunit and self.newunit.target != self.old_unit.target) @cached_property def comment_conflict_found(self): return ( self.fs_comment_updated and self.db_comment_updated) @cached_property def state_conflict_found(self): return ( self.fs_state_updated and self.db_state_updated) @cached_property def target_conflict_found(self): return ( self.fs_target_updated and self.db_target_updated and self.newunit.target != self.db_unit.target) @property def should_create_suggestion(self): return ( self.update.suggest_on_conflict and self.target_conflict_found) @property def should_update_comment(self): return ( self.newunit and self.fs_comment_updated and not ( self.comment_conflict_found and self.update.resolve_conflict == POOTLE_WINS)) @property def should_update_index(self): return ( self.update.change_indices and self.uid in self.update.indices and self.db_unit.index != self.update.get_index(self.uid)) @cached_property def should_update_source(self): return ( self.newunit and (self.db_unit.source != self.newunit.source)) @property def should_update_state(self): return ( self.newunit and self.fs_state_updated and not ( self.db_target_updated and not self.should_update_target) and not ( self.state_conflict_found and self.update.resolve_conflict == POOTLE_WINS)) @property def should_update_target(self): return ( self.newunit and self.fs_target_updated and self.newunit.target != self.db_unit.target and not ( self.target_conflict_found and self.update.resolve_conflict == POOTLE_WINS)) @property def should_unobsolete(self): return ( self.newunit and self.resurrected and self.update.store_revision is not None and not ( self.db_unit.revision > self.update.store_revision and self.update.resolve_conflict == POOTLE_WINS)) @cached_property def resurrected(self): return ( self.newunit and not self.newunit.isobsolete() and self.db_unit.isobsolete()) def create_suggestion(self): suggestion_review = review.get(Suggestion)() return bool( suggestion_review.add( self.db_unit, self.newunit.target, self.update.user)[1] if self.update.resolve_conflict == POOTLE_WINS else suggestion_review.add( self.db_unit, self.original.target, self.original_submitter)[1]) def save_unit(self): self.db_unit.revision = self.update.update_revision self.db_unit.save( user=self.update.user, changed_with=self.update.submission_type) def update_unit(self): reordered = False suggested = False updated = False need_update = ( self.should_unobsolete or self.should_update_target or self.should_update_source or self.should_update_state or self.should_update_comment) if need_update: updated = self.db_unit.update( self.newunit, user=self.update.user) if self.should_update_index: self.db_unit.index = self.update.get_index(self.uid) reordered = True if not updated: self.db_unit.save(user=self.update.user) if self.should_create_suggestion: suggested = self.create_suggestion() if updated: self.save_unit() return (updated or reordered), suggested class StoreUpdater(object): unit_updater_class = UnitUpdater def __init__(self, target_store): self.target_store = target_store def increment_unsynced_unit_revision(self, store_revision, update_revision): filter_by = { 'revision__gt': store_revision or 0, 'revision__lt': update_revision, 'state__gt': OBSOLETE} return self.target_store.unit_set.filter( **filter_by).update( revision=Revision.incr()) def units(self, uids): unit_set = self.target_store.unit_set.select_related( "change", "change__submitted_by") for unit in self.target_store.findid_bulk(uids, unit_set): unit.store = self.target_store yield unit def update(self, *args, **kwargs): with update_store_after(self.target_store): return self._update(*args, **kwargs) def _update(self, store, user=None, store_revision=None, submission_type=None, resolve_conflict=POOTLE_WINS, allow_add_and_obsolete=True): old_state = self.target_store.state if user is None: User = get_user_model() user = User.objects.get_system_user() update_revision = None changes = {} try: diff = StoreDiff(self.target_store, store, store_revision).diff() if diff is not None: update_revision = Revision.incr() changes = self.update_from_diff( store, store_revision, diff, update_revision, user, submission_type, resolve_conflict, allow_add_and_obsolete) finally: if old_state < PARSED: self.target_store.state = PARSED self.target_store.save() has_changed = any(x > 0 for x in changes.values()) if has_changed: logger.info( u"[update] %s units in %s [revision: %d]", get_change_str(changes), self.target_store.pootle_path, (self.target_store.data.max_unit_revision or 0)) return update_revision, changes def mark_units_obsolete(self, uids_to_obsolete, update): """Marks a bulk of units as obsolete. :param uids_to_obsolete: UIDs of the units to be marked as obsolete. :return: The number of units marked as obsolete. """ obsoleted = 0 old_store = update.last_sync_store for unit in self.target_store.findid_bulk(uids_to_obsolete): # Use the same (parent) object since units will # accumulate the list of cache attributes to clear # in the parent Store object added_since_sync = not bool(old_store.findid(unit.getid())) pootle_wins = ( (unit.revision > update.store_revision or 0) and update.resolve_conflict == POOTLE_WINS) if added_since_sync or pootle_wins: continue unit.store = self.target_store if not unit.isobsolete(): unit.makeobsolete() unit.revision = update.update_revision unit.save(user=update.user) obsoleted += 1 return obsoleted def update_from_diff(self, store, store_revision, to_change, update_revision, user, submission_type, resolve_conflict=POOTLE_WINS, allow_add_and_obsolete=True): changes = {} update_dbids, uid_index_map = to_change['update'] update = StoreUpdate( store, self.target_store, user=user, submission_type=submission_type, resolve_conflict=resolve_conflict, change_indices=allow_add_and_obsolete, uids=update_dbids, indices=uid_index_map, store_revision=store_revision, update_revision=update_revision) if resolve_conflict == POOTLE_WINS: to_change["obsolete"] = [ x for x in to_change["obsolete"] if x not in to_change["update"][0]] if allow_add_and_obsolete: # Update indexes for start, delta in to_change["index"]: self.target_store.update_index(start=start, delta=delta) # Add new units for unit, new_unit_index in to_change["add"]: self.target_store.addunit( unit, new_unit_index, user=user, changed_with=submission_type, update_revision=update_revision) changes["added"] = len(to_change["add"]) # Obsolete units changes["obsoleted"] = self.mark_units_obsolete( to_change["obsolete"], update) # Update units changes['updated'], changes['suggested'] = self.update_units(update) self.increment_unsynced_unit_revision( update.store_revision, update.update_revision) return changes def update_units(self, update): update_count = 0 suggestion_count = 0 if not update.uids: return update_count, suggestion_count for unit in self.units(update.uids): updated, suggested = self.unit_updater_class( unit, update).update_unit() if updated: update_count += 1 if suggested: suggestion_count += 1 return update_count, suggestion_count
14,381
Python
.py
376
27.566489
80
0.591405
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,299
providers.py
translate_pootle/pootle/apps/pootle_store/providers.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from pootle.core.delegate import ( event_formatters, format_diffs, format_syncers, format_updaters, unitid) from pootle.core.plugin import provider from pootle_log.utils import LogEvent from pootle_store.unit import timeline from .diff import DiffableStore from .models import Unit from .syncer import StoreSyncer from .updater import StoreUpdater from .utils import DefaultUnitid @provider(format_diffs) def register_format_diffs(**kwargs_): return dict(default=DiffableStore) @provider(format_syncers) def register_format_syncers(**kwargs_): return dict( default=StoreSyncer) @provider(format_updaters) def register_format_updaters(**kwargs_): return dict(default=StoreUpdater) @provider(unitid, sender=Unit) def gather_unitid_providers(**kwargs_): return dict(default=DefaultUnitid) @provider(event_formatters, sender=LogEvent) def gather_event_formatters(**kwargs_): return dict( suggestion_created=timeline.SuggestionAddedEvent, suggestion_accepted=timeline.SuggestionAcceptedEvent, suggestion_rejected=timeline.SuggestionRejectedEvent, target_updated=timeline.TargetUpdatedEvent, state_changed=timeline.UnitStateChangedEvent, unit_created=timeline.UnitCreatedEvent, comment_updated=timeline.CommentUpdatedEvent, check_muted=timeline.CheckMutedEvent, check_unmuted=timeline.CheckUnmutedEvent)
1,689
Python
.py
42
36.452381
77
0.787156
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)