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,300
form_fields.py
translate_pootle/pootle/apps/pootle_store/form_fields.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.utils.datastructures import MultiValueDict from pootle.core.dateparse import parse_datetime from pootle_checks.constants import CATEGORY_IDS class CommaSeparatedCheckboxSelectMultiple(forms.CheckboxSelectMultiple): def value_from_datadict(self, data, files, name): # Accept `sfields` to be a comma-separated string of fields (#46) if "," in data.get(name, ""): return data.get(name).split(u',') if isinstance(data, MultiValueDict): return data.getlist(name) return data.get(name, None) class MultipleValueWidget(forms.TextInput): def value_from_datadict(self, data, files, name): if hasattr(data, "getlist"): return data.getlist(name) return [] class MultipleArgsField(forms.Field): widget = MultipleValueWidget def __init__(self, *args, **kwargs): self.field = kwargs.pop("field") super(MultipleArgsField, self).__init__(*args, **kwargs) def clean(self, value): if len(value) == 1 and "," in value[0]: value = value[0].split(",") return [self.field.clean(x) for x in value] class ISODateTimeField(forms.DateTimeField): def to_python(self, value): if value is not None: return parse_datetime(value) class CategoryChoiceField(forms.ChoiceField): def to_python(self, value): if value is not None: return CATEGORY_IDS.get(value)
1,752
Python
.py
41
36.512195
77
0.69049
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,301
contextmanagers.py
translate_pootle/pootle/apps/pootle_store/contextmanagers.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 contextlib import contextmanager from django.dispatch import receiver from pootle.core.contextmanagers import bulk_operations, keep_data from pootle.core.signals import ( update_checks, update_data, update_revisions, update_scores) from pootle_data.models import StoreChecksData, StoreData, TPChecksData, TPData from pootle_score.models import UserStoreScore from .models import Unit class Updated(object): data = False scores = None checks = None revisions = False def _callback_handler(sender, updated, **kwargs): bulk_pootle = bulk_operations( models=( UserStoreScore, TPData, TPChecksData, StoreData, StoreChecksData)) with keep_data(signals=(update_revisions, )): with bulk_pootle: @receiver(update_revisions) def handle_update_revisions(**kwargs): updated.revisions = True if updated.checks: update_checks.send( sender.__class__, instance=sender, units=updated.checks, **kwargs) if updated.data: update_data.send( sender.__class__, instance=sender, **kwargs) if updated.scores: update_scores.send( sender.__class__, instance=sender, users=updated.scores, **kwargs) if updated.revisions: update_revisions.send( sender.__class__, instance=sender, keys=["stats", "checks"]) @contextmanager def update_store_after(sender, **kwargs): signals = [ update_checks, update_data, update_revisions, update_scores] with keep_data(signals=signals): updated = Updated() @receiver(update_checks, sender=Unit) def handle_update_checks(**kwargs): if updated.checks is None: updated.checks = set() updated.checks.add(kwargs["instance"].id) @receiver(update_data, sender=sender.__class__) def handle_update_data(**kwargs): updated.data = True update_data.disconnect( handle_update_data, sender=sender.__class__) @receiver(update_scores, sender=sender.__class__) def handle_update_scores(**kwargs): if updated.scores is None: updated.scores = set() updated.scores = ( updated.scores | set(kwargs.get("users") or [])) yield if "kwargs" in kwargs: kwargs.update(kwargs.pop("kwargs")) kwargs.get("callback", _callback_handler)( sender, updated, **kwargs)
3,128
Python
.py
87
25.632184
79
0.585705
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,302
diff.py
translate_pootle/pootle/apps/pootle_store/diff.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 difflib import logging from collections import OrderedDict from django.db import models from django.utils.functional import cached_property from pootle.core.delegate import format_diffs from .constants import FUZZY, OBSOLETE, TRANSLATED, UNTRANSLATED from .fields import to_python as multistring_to_python from .unit import UnitProxy logger = logging.getLogger(__name__) class UnitDiffProxy(UnitProxy): """Wraps File/DB Unit dicts used by StoreDiff for equality comparison""" match_attrs = ["context", "developer_comment", "locations", "source", "state", "target", "translator_comment"] def __eq__(self, other): return all(getattr(self, k) == getattr(other, k) for k in self.match_attrs) def __ne__(self, other): return not self == other def hasplural(self): return ( self.source is not None and (len(self.source.strings) > 1 or getattr(self.source, "plural", None))) def getnotes(self, origin=None): return self.unit.get("%s_comment" % origin, "") def getcontext(self): return self.unit["context"] def isfuzzy(self): return self.unit["state"] == FUZZY def isobsolete(self): return self.unit["state"] == OBSOLETE def getid(self): return self.unit["unitid"] class DBUnit(UnitDiffProxy): pass class FileUnit(UnitDiffProxy): @property def locations(self): return "\n".join(self.unit["locations"]) @property def source(self): return multistring_to_python(self.unit["source"]) @property def target(self): return multistring_to_python(self.unit["target"]) def hasplural(self): return self.unit["hasplural"] class DiffableStore(object): """Default Store representation for diffing this can be customized per-format using `format_diffs` provider """ file_unit_class = FileUnit db_unit_class = DBUnit unit_fields = ( "unitid", "state", "id", "index", "revision", "source_f", "target_f", "developer_comment", "translator_comment", "locations", "context") def __init__(self, target_store, source_store): self.target_store = target_store self.source_store = source_store def get_db_units(self, unit_qs): diff_units = OrderedDict() units = unit_qs.values(*self.unit_fields).order_by("index") for unit in units: diff_units[unit["unitid"]] = unit return diff_units def get_file_unit(self, unit): state = UNTRANSLATED if unit.isobsolete(): state = OBSOLETE elif unit.istranslated(): state = TRANSLATED elif unit.isfuzzy(): state = FUZZY return { "unitid": unit.getid(), "context": unit.getcontext(), "locations": unit.getlocations(), "source": unit.source, "target": unit.target, "state": state, "hasplural": unit.hasplural(), "developer_comment": unit.getnotes(origin="developer"), "translator_comment": unit.getnotes(origin="translator")} def get_file_units(self, units): diff_units = OrderedDict() for unit in units: if unit.isheader(): continue if unit.getid() in diff_units: unitid = unit.getid() logger.warning( "[diff] Duplicate unit found: %s %s", self.target_store.name, (unitid if len(unitid) <= 20 else "%s..." % unitid[:17])) diff_units[unit.getid()] = self.get_file_unit(unit) return diff_units @cached_property def target_units(self): return self.get_db_units(self.target_store.unit_set) @cached_property def source_units(self): if isinstance(self.source_store, models.Model): return self.get_db_units(self.source_store.unit_set.live()) return self.get_file_units(self.source_store.units) @property def target_unit_class(self): return self.db_unit_class @property def source_unit_class(self): if isinstance(self.source_store, models.Model): return self.db_unit_class return self.file_unit_class class StoreDiff(object): """Compares 2 DBStores""" def __init__(self, target_store, source_store, source_revision): self.target_store = target_store self.source_store = source_store self.source_revision = source_revision self.target_revision = self.get_target_revision() @property def diff_class(self): diffs = format_diffs.gather() differ = diffs.get( self.target_store.filetype.name) if differ: return differ return diffs["default"] def get_target_revision(self): return self.target_store.data.max_unit_revision or 0 @cached_property def active_target_units(self): return [unitid for unitid, unit in self.target_units.items() if unit['state'] != OBSOLETE] @cached_property def diffable(self): return self.diff_class(self.target_store, self.source_store) @cached_property def target_units(self): """All of the db units regardless of state or revision""" return self.diffable.target_units @cached_property def source_units(self): """All of the db units regardless of state or revision""" return self.diffable.source_units @cached_property def insert_points(self): """Returns a list of insert points with update index info. :return: a list of tuples ``(insert_at, uids_to_add, next_index, update_index_delta)`` where ``insert_at`` is the point for inserting ``uids_to_add`` are the units to be inserted ``update_index_delta`` is the offset for index updating ``next_index`` is the starting point after which ``update_index_delta`` should be applied. """ inserts = [] new_unitid_list = self.new_unit_list for (tag, i1, i2, j1, j2) in self.opcodes: if tag == 'insert': update_index_delta = 0 insert_at = 0 if i1 > 0: insert_at = ( self.target_units[ self.active_target_units[i1 - 1]]['index']) next_index = insert_at + 1 if i1 < len(self.active_target_units): next_index = self.target_units[ self.active_target_units[i1]]["index"] update_index_delta = ( j2 - j1 - next_index + insert_at + 1) inserts.append((insert_at, new_unitid_list[j1:j2], next_index, update_index_delta)) elif tag == 'replace': insert_at = self.target_units[ self.active_target_units[max(i1 - 1, 0)]]['index'] next_index = self.target_units[ self.active_target_units[i2 - 1]]['index'] inserts.append((insert_at, new_unitid_list[j1:j2], next_index, j2 - j1 - insert_at + next_index)) return inserts @cached_property def new_unit_list(self): # If source_revision is gte than the target_revision then new unit list # will be exactly what is in the file if self.source_revision >= self.target_revision: return self.source_units.keys() # These units are kept as they have been updated since source_revision # but do not appear in the file new_units = [u for u in self.updated_target_units if u not in self.source_units] # These unit are either present in both or only in the file so are # kept in the file order new_units += [u for u in self.source_units.keys() if u not in self.obsoleted_target_units] return new_units @cached_property def obsoleted_target_units(self): return [unitid for unitid, unit in self.target_units.items() if (unit['state'] == OBSOLETE and unit["revision"] > self.source_revision)] @cached_property def opcodes(self): sm = difflib.SequenceMatcher(None, self.active_target_units, self.new_unit_list) return sm.get_opcodes() @cached_property def updated_target_units(self): return [unitid for unitid, unit in self.target_units.items() if (unit['revision'] > self.source_revision and unit["state"] != OBSOLETE)] def diff(self): """Return a dictionary of change actions or None if there are no changes to be made. """ diff = {"index": self.get_indexes_to_update(), "obsolete": self.get_units_to_obsolete(), "add": self.get_units_to_add(), "update": self.get_units_to_update()} if self.has_changes(diff): return diff return None def get_indexes_to_update(self): offset = 0 index_updates = [] for (insert_at_, uids_add_, next_index, delta) in self.insert_points: if delta > 0: index_updates += [(next_index + offset, delta)] offset += delta return index_updates def get_units_to_add(self): offset = 0 to_add = [] proxy = ( isinstance(self.source_store, models.Model) and DBUnit or FileUnit) for (insert_at, uids_add, next_index_, delta) in self.insert_points: for index, uid in enumerate(uids_add): source_unit = self.source_units.get(uid) if source_unit and uid not in self.target_units: new_unit_index = insert_at + index + 1 + offset to_add += [(proxy(source_unit), new_unit_index)] if delta > 0: offset += delta return to_add def get_units_to_obsolete(self): return [unit['id'] for unitid, unit in self.target_units.items() if ((unitid not in self.source_units or self.source_units[unitid]['state'] == OBSOLETE) and unitid in self.active_target_units)] def get_units_to_update(self): uid_index_map = {} offset = 0 for (insert_at, uids_add, next_index_, delta) in self.insert_points: for index, uid in enumerate(uids_add): new_unit_index = insert_at + index + 1 + offset if uid in self.target_units: uid_index_map[uid] = { 'dbid': self.target_units[uid]['id'], 'index': new_unit_index} if delta > 0: offset += delta update_ids = self.get_updated_sourceids() update_ids.update({x['dbid'] for x in uid_index_map.values()}) return (update_ids, uid_index_map) def get_updated_sourceids(self): """Returns a set of unit DB ids to be updated. """ update_ids = set() for (tag, i1, i2, j1_, j2_) in self.opcodes: if tag != 'equal': continue update_ids.update( set(self.target_units[uid]['id'] for uid in self.active_target_units[i1:i2] if (uid in self.source_units and ( self.diffable.target_unit_class( self.target_units[uid]) != self.diffable.source_unit_class( self.source_units[uid]))))) return update_ids def has_changes(self, diff): for k, v in diff.items(): if k == "update": if len(v[0]) > 0: return True else: if len(v) > 0: return True return False
12,733
Python
.py
307
29.980456
79
0.565013
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,303
fields.py
translate_pootle/pootle/apps/pootle_store/fields.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. """Fields required for handling translation files""" from translate.misc.multistring import multistring from django.db import models from pootle.core.utils.multistring import (parse_multistring, unparse_multistring) # # # # # # # # # String # # # # # # # # # # # # # # # def to_db(value): """Flatten the given value (string, list of plurals or multistring) into the database string representation. """ if value is None: return None return unparse_multistring(value) def to_python(value): """Reconstruct a multistring from the database string representation.""" if not value: return multistring("", encoding="UTF-8") elif isinstance(value, multistring): return value elif isinstance(value, basestring): return parse_multistring(value) elif isinstance(value, dict): return multistring([val for __, val in sorted(value.items())], encoding="UTF-8") else: return multistring(value, encoding="UTF-8") class CastOnAssignDescriptor(object): """ A property descriptor which ensures that `field.to_python()` is called on _every_ assignment to the field. This used to be provided by the `django.db.models.subclassing.Creator` class, which in turn was used by the deprecated-in-Django-1.10 `SubfieldBase` class, hence the reimplementation here. """ def __init__(self, field): self.field = field def __get__(self, obj, type=None): if obj is None: return self return obj.__dict__[self.field.name] def __set__(self, obj, value): obj.__dict__[self.field.name] = self.field.to_python(value) class MultiStringField(models.Field): description = \ "a field imitating translate.misc.multistring used for plurals" def __init__(self, *args, **kwargs): super(MultiStringField, self).__init__(*args, **kwargs) def get_internal_type(self): return "TextField" def to_python(self, value): return to_python(value) def from_db_value(self, value, expression, connection, context): return to_python(value) def get_prep_value(self, value): return to_db(value) def get_prep_lookup(self, lookup_type, value): if (lookup_type in ('exact', 'iexact') or not isinstance(value, basestring)): value = self.get_prep_value(value) return super(MultiStringField, self).get_prep_lookup(lookup_type, value) def contribute_to_class(self, cls, name): super(MultiStringField, self).contribute_to_class(cls, name) setattr(cls, name, CastOnAssignDescriptor(self))
3,056
Python
.py
71
35.450704
79
0.650676
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,304
decorators.py
translate_pootle/pootle/apps/pootle_store/decorators.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 functools import wraps from django.core.exceptions import PermissionDenied from django.shortcuts import get_object_or_404 from pootle.i18n.gettext import ugettext as _ from pootle_app.models.permissions import (check_permission, get_matching_permissions) from .models import Unit def get_permission_message(permission_code): """Returns a human-readable message when `permission_code` is not met by the current context. """ default_message = _("Insufficient rights to access this directory.") return { 'suggest': _('Insufficient rights to access suggestion mode.'), 'translate': _('Insufficient rights to access translation mode.'), 'review': _('Insufficient rights to access review mode.'), }.get(permission_code, default_message) def get_unit_context(permission_code=None): def wrap_f(f): @wraps(f) def decorated_f(request, uid, *args, **kwargs): unit = get_object_or_404( Unit.objects.select_related("store__translation_project", "store__parent"), id=uid, ) tp = unit.store.translation_project request.translation_project = tp request.permissions = get_matching_permissions(request.user, tp.directory) if (permission_code is not None and not check_permission(permission_code, request)): raise PermissionDenied(get_permission_message(permission_code)) request.unit = unit request.store = unit.store request.directory = unit.store.parent return f(request, unit, *args, **kwargs) return decorated_f return wrap_f
2,120
Python
.py
46
35.782609
79
0.635214
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,305
forms.py
translate_pootle/pootle/apps/pootle_store/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 translate.misc.multistring import multistring from django import forms from django.contrib.auth import get_user_model from django.urls import Resolver404, resolve from django.utils.translation import get_language from pootle.core.delegate import review from pootle.core.url_helpers import split_pootle_path from pootle.i18n.gettext import ugettext as _ from pootle_app.models import Directory from pootle_app.models.permissions import ( check_permission, check_user_permission) from pootle_checks.constants import CATEGORY_CODES, CHECK_NAMES from pootle_comment.forms import UnsecuredCommentForm from pootle_misc.util import get_date_interval from pootle_project.models import Project from pootle_statistics.models import SubmissionFields, SubmissionTypes from .constants import ALLOWED_SORTS, FUZZY, OBSOLETE, TRANSLATED, UNTRANSLATED from .contextmanagers import update_store_after from .fields import to_db from .form_fields import ( CategoryChoiceField, CommaSeparatedCheckboxSelectMultiple, ISODateTimeField, MultipleArgsField) from .models import Suggestion, Unit UNIT_SEARCH_FILTER_CHOICES = ( ("all", "all"), ("translated", "translated"), ("untranslated", "untranslated"), ("fuzzy", "fuzzy"), ("incomplete", "incomplete"), ("suggestions", "suggestions"), ("my-suggestions", "my-suggestions"), ("user-suggestions", "user-suggestions"), ("user-suggestions-accepted", "user-suggestions-accepted"), ("user-suggestions-rejected", "user-suggestions-rejected"), ("my-submissions", "my-submissions"), ("user-submissions", "user-submissions"), ("my-submissions-overwritten", "my-submissions-overwritten"), ("user-submissions-overwritten", "user-submissions-overwritten"), ("checks", "checks")) UNIT_SEARCH_SORT_CHOICES = ( ('priority', 'priority'), ('oldest', 'oldest'), ('newest', 'newest')) # # # # # # # text cleanup and highlighting # # # # # # # # # # # # # class MultiStringWidgetMixin(object): def decompress(self, value): if value is None: return [None] * len(self.widgets) elif isinstance(value, multistring): return [string for string in value.strings] elif isinstance(value, list): return value elif isinstance(value, basestring): return [value] raise ValueError class MultiStringWidget(MultiStringWidgetMixin, forms.MultiWidget): """Custom Widget for editing multistrings, expands number of text area based on number of plural forms. """ def __init__(self, attrs=None, nplurals=1, textarea=True): if textarea: widget = forms.Textarea else: widget = forms.TextInput widgets = [widget(attrs=attrs) for i_ in xrange(nplurals)] super(MultiStringWidget, self).__init__(widgets, attrs) def format_output(self, rendered_widgets): from django.utils.safestring import mark_safe if len(rendered_widgets) == 1: return mark_safe(rendered_widgets[0]) output = '' for i, widget in enumerate(rendered_widgets): output += '<div lang="%s" title="%s">' % \ (get_language(), _('Plural Form %d', i)) output += widget output += '</div>' return mark_safe(output) class HiddenMultiStringWidget(MultiStringWidgetMixin, forms.MultiWidget): """Uses hidden input instead of textareas.""" def __init__(self, attrs=None, nplurals=1): widgets = [forms.HiddenInput(attrs=attrs) for i_ in xrange(nplurals)] super(HiddenMultiStringWidget, self).__init__(widgets, attrs) def format_output(self, rendered_widgets): return super( HiddenMultiStringWidget, self).format_output(rendered_widgets) def __call__(self): # HACKISH: Django is inconsistent in how it handles Field.widget and # Field.hidden_widget, it expects widget to be an instantiated object # and hidden_widget to be a class, since we need to specify nplurals at # run time we can let django instantiate hidden_widget. # # making the object callable let's us get away with forcing an object # where django expects a class return self class MultiStringFormField(forms.MultiValueField): def __init__(self, nplurals=1, attrs=None, textarea=True, *args, **kwargs): self.widget = MultiStringWidget(nplurals=nplurals, attrs=attrs, textarea=textarea) self.hidden_widget = HiddenMultiStringWidget(nplurals=nplurals) fields = [forms.CharField(strip=False) for i_ in range(nplurals)] super(MultiStringFormField, self).__init__(fields=fields, *args, **kwargs) def compress(self, data_list): return data_list def unit_form_factory(language, snplurals=None, request=None): if snplurals is not None: tnplurals = language.nplurals else: tnplurals = 1 action_disabled = False if request is not None: cantranslate = check_permission("translate", request) cansuggest = check_permission("suggest", request) if not (cansuggest or cantranslate): action_disabled = True target_attrs = { 'lang': language.code, 'dir': language.direction, 'class': 'translation expanding focusthis js-translation-area', 'rows': 2, 'tabindex': 10, } fuzzy_attrs = { 'accesskey': 'f', 'class': 'fuzzycheck', 'tabindex': 13, } if action_disabled: target_attrs['disabled'] = 'disabled' fuzzy_attrs['disabled'] = 'disabled' class UnitForm(forms.ModelForm): class Meta(object): model = Unit fields = ('target_f', ) target_f = MultiStringFormField( nplurals=tnplurals, required=False, attrs=target_attrs, ) is_fuzzy = forms.BooleanField( required=False, label=_("Needs work"), widget=forms.CheckboxInput(attrs=fuzzy_attrs)) suggestion = forms.ModelChoiceField( queryset=Suggestion.objects.all(), required=False) comment = forms.CharField(required=False) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) self.user = self.request.user super(UnitForm, self).__init__(*args, **kwargs) self._updated_fields = [] self.fields['target_f'].widget.attrs['data-translation-aid'] = \ self['target_f'].value() self.initial.update(dict(is_fuzzy=(self.instance.state == FUZZY))) @property def updated_fields(self): order_dict = { SubmissionFields.STATE: 0, SubmissionFields.TARGET: 1, } return sorted(self._updated_fields, key=lambda x: order_dict[x[0]]) def clean_target_f(self): value = self.cleaned_data['target_f'] if self.instance.target != multistring(value or [u'']): self._updated_fields.append((SubmissionFields.TARGET, to_db(self.instance.target), to_db(value))) return value def clean_is_fuzzy(self): return self.data.get("is_fuzzy", None) and True or False def clean(self): old_state = self.instance.state # Integer is_fuzzy = self.cleaned_data['is_fuzzy'] # Boolean new_target = self.cleaned_data['target_f'] # If suggestion is provided set `old_state` should be `TRANSLATED`. if self.cleaned_data['suggestion']: old_state = TRANSLATED # Skip `TARGET` field submission if suggestion value is equal # to submitted translation if new_target == self.cleaned_data['suggestion'].target_f: self._updated_fields = [] not_cleared = ( self.request is not None and not check_permission('administrate', self.request) and is_fuzzy) if not_cleared: self.add_error( 'is_fuzzy', forms.ValidationError( _('Needs work flag must be cleared'))) if new_target: if is_fuzzy: new_state = FUZZY else: new_state = TRANSLATED else: new_state = UNTRANSLATED if old_state not in [new_state, OBSOLETE]: self._updated_fields.append((SubmissionFields.STATE, old_state, new_state)) self.cleaned_data['state'] = new_state else: self.cleaned_data['state'] = old_state return super(UnitForm, self).clean() def save(self, *args, **kwargs): if not self.updated_fields: return changed_with = kwargs.pop("changed_with", None) suggestion = self.cleaned_data["suggestion"] with update_store_after(self.instance.store): user = ( suggestion.user if suggestion else self.user) self.instance.save( user=user, changed_with=changed_with) return self.instance return UnitForm def unit_comment_form_factory(language): comment_attrs = { 'lang': language.code, 'dir': language.direction, 'class': 'comments expanding focusthis', 'rows': 1, 'tabindex': 15, } class UnitCommentForm(forms.ModelForm): class Meta(object): fields = ('translator_comment',) model = Unit translator_comment = forms.CharField( required=True, label=_("Translator comment"), widget=forms.Textarea(attrs=comment_attrs), ) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) self.previous_value = '' super(UnitCommentForm, self).__init__(*args, **kwargs) if self.request.method == 'DELETE': self.fields['translator_comment'].required = False def clean_translator_comment(self): # HACKISH: Setting empty string when `DELETE` is being used if self.request.method == 'DELETE': self.previous_value = self.instance.translator_comment return '' return self.cleaned_data['translator_comment'] def save(self, *args, **kwargs): self.instance.save(user=self.request.user) return UnitCommentForm class UnitSearchForm(forms.Form): offset = forms.IntegerField(required=False) path = forms.CharField( max_length=2048, required=True) previous_uids = MultipleArgsField( field=forms.IntegerField(), required=False) uids = MultipleArgsField( field=forms.IntegerField(), required=False) filter = forms.ChoiceField( required=False, choices=UNIT_SEARCH_FILTER_CHOICES) checks = forms.MultipleChoiceField( required=False, widget=CommaSeparatedCheckboxSelectMultiple, choices=CHECK_NAMES.items()) category = CategoryChoiceField( required=False, choices=CATEGORY_CODES.items()) month = forms.DateField( required=False, input_formats=['%Y-%m']) sort = forms.ChoiceField( required=False, choices=UNIT_SEARCH_SORT_CHOICES) user = forms.ModelChoiceField( queryset=get_user_model().objects.all(), required=False, to_field_name="username") search = forms.CharField(required=False) soptions = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=( ('exact', _('Phrase match')), ('case', _('Case-sensitive match')))) sfields = forms.MultipleChoiceField( required=False, widget=CommaSeparatedCheckboxSelectMultiple, choices=( ('source', _('Source Text')), ('target', _('Target Text')), ('notes', _('Comments')), ('locations', _('Locations'))), initial=['source', 'target']) def __init__(self, *args, **kwargs): self.request_user = kwargs.pop("user") super(UnitSearchForm, self).__init__(*args, **kwargs) self.fields["modified-since"] = ISODateTimeField(required=False) def clean(self): if "checks" in self.errors: del self.errors["checks"] self.cleaned_data["checks"] = None if "user" in self.errors: del self.errors["user"] self.cleaned_data["user"] = self.request_user if self.errors: return self.cleaned_data['count'] = self.request_user.get_unit_rows() self.cleaned_data["vfolder"] = None pootle_path = self.cleaned_data.get("path") path_keys = [ "project_code", "language_code", "dir_path", "filename"] try: path_kwargs = { k: v for k, v in resolve(pootle_path).kwargs.items() if k in path_keys} except Resolver404: raise forms.ValidationError('Unrecognised path') self.cleaned_data.update(path_kwargs) sort_on = "units" if "filter" in self.cleaned_data: unit_filter = self.cleaned_data["filter"] if unit_filter in ('suggestions', 'user-suggestions'): sort_on = 'suggestions' elif unit_filter in ('user-submissions', ): sort_on = 'submissions' sort_by_param = self.cleaned_data["sort"] self.cleaned_data["sort_by"] = ALLOWED_SORTS[sort_on].get(sort_by_param) self.cleaned_data["sort_on"] = sort_on def clean_month(self): if self.cleaned_data["month"]: return get_date_interval(self.cleaned_data["month"].strftime("%Y-%m")) def clean_user(self): return self.cleaned_data["user"] or self.request_user def clean_path(self): lang_code, proj_code = split_pootle_path( self.cleaned_data["path"])[:2] if not (lang_code or proj_code): permission_context = Directory.objects.projects elif proj_code and not lang_code: try: permission_context = Project.objects.select_related( "directory").get(code=proj_code).directory except Project.DoesNotExist: raise forms.ValidationError("Unrecognized path") else: # no permission checking on lang translate views return self.cleaned_data["path"] if self.request_user.is_superuser: return self.cleaned_data["path"] can_view_path = check_user_permission( self.request_user, "administrate", permission_context) if can_view_path: return self.cleaned_data["path"] raise forms.ValidationError("Unrecognized path") class BaseSuggestionForm(UnsecuredCommentForm): should_save = lambda self: True def __init__(self, *args, **kwargs): kwargs["request_user"] = kwargs.get("request_user") or self.request_user super(BaseSuggestionForm, self).__init__(**kwargs) self.fields["comment"].required = False @property def review_type(self): return SubmissionTypes.WEB @property def suggestion_review(self): return review.get(self.target_object.__class__)( [self.target_object], self.request_user, review_type=self.review_type) class SuggestionReviewForm(BaseSuggestionForm): action = forms.ChoiceField( required=True, choices=( ("accept", "Accept"), ("reject", "Reject"))) def clean_action(self): if not self.target_object.is_pending: self.add_error( "action", forms.ValidationError( _("Suggestion '%s' has already been accepted or rejected.", self.target_object))) return self.data["action"] def clean(self): self_review = ( self.request_user == self.target_object.user and self.cleaned_data.get("action") == "reject") permission = ( "view" if self_review else "review") has_permission = check_user_permission( self.request_user, permission, self.target_object.unit.store.parent) if not has_permission: raise forms.ValidationError( _("Insufficient rights to access this page.")) if not self.errors: super(SuggestionReviewForm, self).clean() def save(self): if self.cleaned_data["action"] == "accept": self.suggestion_review.accept( target=self.cleaned_data.get("target_f")) else: self.suggestion_review.reject() if self.cleaned_data["comment"]: super(SuggestionReviewForm, self).save() class SubmitFormMixin(object): def __init__(self, *args, **kwargs): self.unit = kwargs.pop("unit") self.request_user = kwargs.pop("request_user") super(SubmitFormMixin, self).__init__(*args, **kwargs) snplurals = ( len(self.unit.source.strings) if self.unit.hasplural() else None) nplurals = ( self.unit.store.translation_project.language.nplurals if snplurals else 1) self.fields["target_f"].widget = MultiStringWidget( nplurals=nplurals, attrs={ 'lang': self.unit.store.translation_project.language.code, 'dir': self.unit.store.translation_project.language.direction, 'class': 'translation expanding focusthis js-translation-area', 'rows': 2, 'tabindex': 10}) self.fields['target_f'].widget.attrs[ 'data-translation-aid'] = self['target_f'].value() self.fields[ "target_f"].hidden_widget = HiddenMultiStringWidget(nplurals=nplurals) self.fields["target_f"].fields = [ forms.CharField(strip=False, required=False) for i in range(nplurals)] for k in ["user", "name", "email"]: if k in self.fields: self.fields[k].required = False class SuggestionSubmitForm(SubmitFormMixin, BaseSuggestionForm): target_f = MultiStringFormField(required=False, require_all_fields=False) def save_unit(self): self.suggestion_review.accept(target=self.cleaned_data["target_f"]) def save(self): with update_store_after(self.unit.store): self.save_unit() if self.cleaned_data['comment']: super(SuggestionSubmitForm, self).save() class AddSuggestionForm(SubmitFormMixin, forms.Form): target_f = MultiStringFormField(required=False, require_all_fields=False) def clean_target_f(self): target = multistring(self.cleaned_data["target_f"] or [u'']) if self.unit.get_suggestions().filter(target_f=target).exists(): self.add_error( "target_f", forms.ValidationError( _("Suggestion '%s' already exists.", target))) elif target == self.unit.target: self.add_error( "target_f", forms.ValidationError( _("Suggestion '%s' equals to current unit target value.", target))) else: return self.cleaned_data["target_f"] def save_unit(self): user = self.request_user review.get(Suggestion)().add( self.unit, self.cleaned_data["target_f"], user=user) def save(self): with update_store_after(self.unit.store): self.save_unit() class SubmitForm(SubmitFormMixin, forms.Form): is_fuzzy = forms.BooleanField( initial=False, label=_("Needs work")) target_f = MultiStringFormField(required=False, require_all_fields=False) def clean_is_fuzzy(self): return self.data["is_fuzzy"] != "0" def save_unit(self): user = self.request_user target = multistring(self.cleaned_data["target_f"] or [u'']) if target != self.unit.target: self.unit.target = self.cleaned_data["target_f"] if self.unit.target: if self.cleaned_data["is_fuzzy"]: self.unit.state = FUZZY else: self.unit.state = TRANSLATED else: self.unit.state = UNTRANSLATED self.unit.save( user=user, changed_with=SubmissionTypes.WEB) def save(self): with update_store_after(self.unit.store): self.save_unit()
21,684
Python
.py
514
31.729572
82
0.602146
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,306
views.py
translate_pootle/pootle/apps/pootle_store/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. import calendar import unicodedata from collections import OrderedDict from translate.lang import data from django import forms from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.http import Http404, QueryDict from django.shortcuts import get_object_or_404, redirect from django.template import loader from django.utils.functional import cached_property from django.utils.lru_cache import lru_cache from django.utils.translation import to_locale from django.utils.translation.trans_real import parse_accept_lang_header from django.views.decorators.http import require_http_methods from django.views.generic import FormView from pootle.core.delegate import search_backend from pootle.core.exceptions import Http400 from pootle.core.http import JsonResponse, JsonResponseBadRequest from pootle.core.utils import dateformat from pootle.core.views import PootleJSON from pootle.core.views.decorators import requires_permission, set_permissions from pootle.core.views.mixins import GatherContextMixin, PootleJSONMixin from pootle.i18n.dates import timesince from pootle.i18n.gettext import ugettext as _ from pootle_app.models.permissions import check_user_permission from pootle_language.models import Language from pootle_misc.util import ajax_required from .decorators import get_unit_context from .forms import ( AddSuggestionForm, SubmitForm, SuggestionReviewForm, SuggestionSubmitForm, UnitSearchForm, unit_comment_form_factory, unit_form_factory) from .models import Suggestion, Unit from .templatetags.store_tags import pluralize_source, pluralize_target from .unit.results import GroupedResults from .unit.timeline import Timeline from .util import find_altsrcs def get_alt_src_langs(request, user, translation_project): if request.user.is_anonymous: return language = translation_project.language project = translation_project.project source_language = project.source_language langs = list( user.alt_src_langs.exclude( id__in=(language.id, source_language.id) ).filter( translationproject__project=project)) if langs: return langs accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '') for accept_lang, __ in parse_accept_lang_header(accept): if accept_lang == '*': continue normalized = to_locale( data.normalize_code( data.simplify_to_common(accept_lang))) code = to_locale(accept_lang) is_source_lang = any( langcode in ('en', 'en_US', source_language.code, language.code) for langcode in [code, normalized]) if is_source_lang: continue langs = list( Language.objects.filter( code__in=(normalized, code), translationproject__project=project)) if langs: return langs # # Views used with XMLHttpRequest requests. # def _filter_ctx_units(units_qs, unit, how_many, gap=0): """Returns ``how_many``*2 units that are before and after ``index``.""" result = {'before': [], 'after': []} if how_many and unit.index - gap > 0: before = units_qs.filter(store=unit.store_id, index__lt=unit.index) \ .order_by('-index')[gap:how_many+gap] result['before'] = _build_units_list(before, reverse=True) result['before'].reverse() # FIXME: can we avoid this query if length is known? if how_many: after = units_qs.filter(store=unit.store_id, index__gt=unit.index)[gap:how_many+gap] result['after'] = _build_units_list(after) return result def _prepare_unit(unit): """Constructs a dictionary with relevant `unit` data.""" return { 'id': unit.id, 'url': unit.get_translate_url(), 'isfuzzy': unit.isfuzzy(), 'source': [source[1] for source in pluralize_source(unit)], 'target': [target[1] for target in pluralize_target(unit)], } def _build_units_list(units, reverse=False): """Given a list/queryset of units, builds a list with the unit data contained in a dictionary ready to be returned as JSON. :return: A list with unit id, source, and target texts. In case of having plural forms, a title for the plural form is also provided. """ return_units = [] for unit in iter(units): return_units.append(_prepare_unit(unit)) return return_units def _get_critical_checks_snippet(request, unit): """Retrieves the critical checks snippet. :param request: an `HttpRequest` object :param unit: a `Unit` instance for which critical checks need to be rendered. :return: rendered HTML snippet with the failing checks, or `None` if there are no critical failing checks. """ if not unit.has_critical_checks(): return None can_review = check_user_permission(request.user, 'review', unit.store.parent) ctx = { 'canreview': can_review, 'unit': unit, 'critical_checks': list(unit.get_critical_qualitychecks()), 'warning_checks': list(unit.get_warning_qualitychecks()), } template = loader.get_template('editor/units/xhr_checks.html') return template.render(context=ctx, request=request) @ajax_required def get_units(request, **kwargs_): """Gets source and target texts and its metadata. :return: A JSON-encoded string containing the source and target texts grouped by the store they belong to. The optional `count` GET parameter defines the chunk size to consider. The user's preference will be used by default. When the `initial` GET parameter is present, a sorted list of the result set ids will be returned too. """ search_form = UnitSearchForm(request.GET, user=request.user) if not search_form.is_valid(): errors = search_form.errors.as_data() if "path" in errors: for error in errors["path"]: if error.code == "max_length": raise Http400(_('Path too long.')) elif error.code == "required": raise Http400(_('Arguments missing.')) raise Http404(forms.ValidationError(search_form.errors).messages) total, start, end, units_qs = search_backend.get(Unit)( request.user, **search_form.cleaned_data).search() return JsonResponse( {'start': start, 'end': end, 'total': total, 'unitGroups': GroupedResults(units_qs).data}) @ajax_required @get_unit_context('view') def get_more_context(request, unit, **kwargs_): """Retrieves more context units. :return: An object in JSON notation that contains the source and target texts for units that are in the context of unit ``uid``. """ store = request.store json = {} gap = int(request.GET.get('gap', 0)) qty = int(request.GET.get('qty', 1)) json["ctx"] = _filter_ctx_units(store.units, unit, qty, gap) return JsonResponse(json) @ajax_required @require_http_methods(['POST', 'DELETE']) @get_unit_context('translate') def comment(request, unit, **kwargs_): """Dispatches the comment action according to the HTTP verb.""" if request.method == 'DELETE': return delete_comment(request, unit) elif request.method == 'POST': return save_comment(request, unit) def delete_comment(request, unit, **kwargs_): """Deletes a comment by blanking its contents and records a new submission. """ unit.change.commented_by = None unit.change.commented_on = None language = request.translation_project.language comment_form_class = unit_comment_form_factory(language) form = comment_form_class({}, instance=unit, request=request) if form.is_valid(): form.save() return JsonResponse({}) return JsonResponseBadRequest({'msg': _("Failed to remove comment.")}) def save_comment(request, unit): """Stores a new comment for the given ``unit``. :return: If the form validates, the cleaned comment is returned. An error message is returned otherwise. """ language = request.translation_project.language form = unit_comment_form_factory(language)(request.POST, instance=unit, request=request) if form.is_valid(): form.save() user = request.user directory = unit.store.parent ctx = { 'unit': unit, 'language': language, 'cantranslate': check_user_permission(user, 'translate', directory), 'cansuggest': check_user_permission(user, 'suggest', directory), } t = loader.get_template('editor/units/xhr_comment.html') return JsonResponse({'comment': t.render(context=ctx, request=request)}) return JsonResponseBadRequest({'msg': _("Comment submission failed.")}) class PootleUnitJSON(PootleJSON): model = Unit pk_url_kwarg = "uid" @cached_property def permission_context(self): self.object = self.get_object() return self.store.parent @property def pootle_path(self): return self.store.pootle_path @cached_property def tp(self): return self.store.translation_project @cached_property def store(self): return self.object.store @cached_property def source_language(self): return self.project.source_language @cached_property def directory(self): return self.store.parent @lru_cache() def get_object(self): return super(PootleUnitJSON, self).get_object() class UnitTimelineJSON(PootleUnitJSON): model = Unit pk_url_kwarg = "uid" template_name = 'editor/units/xhr_timeline.html' @property def language(self): return self.object.store.translation_project.language @cached_property def permission_context(self): self.object = self.get_object() return self.project.directory @property def project(self): return self.object.store.translation_project.project @property def timeline(self): return Timeline(self.object) def get_context_data(self, *args, **kwargs): return dict( event_groups=self.timeline.grouped_events(), language=self.language) def get_queryset(self): return Unit.objects.get_translatable(self.request.user).select_related( "change", "store__translation_project__language", "store__translation_project__project__directory") def get_response_data(self, context): return { 'uid': self.object.id, 'event_groups': self.get_event_groups_data(context), 'timeline': self.render_timeline(context)} def render_timeline(self, context): return loader.get_template(self.template_name).render(context=context) def get_event_groups_data(self, context): result = [] for event_group in context['event_groups']: display_dt = event_group['datetime'] if display_dt is not None: display_dt = dateformat.format(display_dt) iso_dt = event_group['datetime'].isoformat() relative_time = timesince( calendar.timegm(event_group['datetime'].timetuple()), self.request_lang) else: iso_dt = None relative_time = None result.append({ "display_datetime": display_dt, "iso_datetime": iso_dt, "relative_time": relative_time, "via_upload": event_group.get('via_upload', False), }) return result CHARACTERS_NAMES = OrderedDict( ( # Code Display name (8204, 'ZWNJ'), (8205, 'ZWJ'), (8206, 'LRM'), (8207, 'RLM'), (8234, 'LRE'), (8235, 'RLE'), (8236, 'PDF'), (8237, 'LRO'), (8238, 'RLO'), ) ) CHARACTERS = u"".join([unichr(index) for index in CHARACTERS_NAMES.keys()]) class UnitEditJSON(PootleUnitJSON): @property def special_characters(self): if self.language.direction == "rtl": # Inject some extra special characters for RTL languages. language_specialchars = CHARACTERS # Do not repeat special chars. language_specialchars += u"".join( [c for c in self.language.specialchars if c not in CHARACTERS]) else: language_specialchars = self.language.specialchars special_chars = [] for specialchar in language_specialchars: code = ord(specialchar) special_chars.append({ 'display': CHARACTERS_NAMES.get(code, specialchar), 'code': code, 'hex_code': "U+" + hex(code)[2:].upper(), # Like U+200C 'name': unicodedata.name(specialchar, ''), }) return special_chars def get_edit_template(self): if self.project.is_terminology or self.store.has_terminology: return loader.get_template('editor/units/term_edit.html') return loader.get_template('editor/units/edit.html') def render_edit_template(self, context): return self.get_edit_template().render(context=context, request=self.request) def get_source_nplurals(self): if self.object.hasplural(): return len(self.object.source.strings) return None def get_target_nplurals(self): source_nplurals = self.get_source_nplurals() return self.language.nplurals if source_nplurals is not None else 1 def get_unit_values(self): target_nplurals = self.get_target_nplurals() unit_values = [value for value in self.object.target_f.strings] if len(unit_values) < target_nplurals: return unit_values + ((target_nplurals - len(unit_values)) * ['']) return unit_values def get_unit_edit_form(self): form_class = unit_form_factory(self.language, self.get_source_nplurals(), self.request) return form_class(instance=self.object, request=self.request) def get_unit_comment_form(self): comment_form_class = unit_comment_form_factory(self.language) return comment_form_class({}, instance=self.object, request=self.request) @lru_cache() def get_alt_srcs(self): if self.request.user.is_anonymous: return [] return find_altsrcs( self.object, get_alt_src_langs(self.request, self.request.user, self.tp), store=self.store, project=self.project) def get_queryset(self): return Unit.objects.get_translatable(self.request.user).select_related( "change", "change__submitted_by", "store", "store__filetype", "store__parent", "store__translation_project", "store__translation_project__project", "store__translation_project__project__directory", "store__translation_project__project__source_language", "store__translation_project__language") def get_sources(self): sources = { unit.language_code: unit.target.strings for unit in self.get_alt_srcs()} sources[self.source_language.code] = self.object.source_f.strings return sources def get_context_data(self, *args, **kwargs): priority = ( self.store.priority if 'virtualfolder' in settings.INSTALLED_APPS else None) suggestions = self.object.get_suggestions() latest_target_submission = self.object.get_latest_target_submission() accepted_suggestion = None if latest_target_submission is not None: accepted_suggestion = latest_target_submission.suggestion critical_checks = list(self.object.get_critical_qualitychecks()) failing_checks = any( not check.false_positive for check in critical_checks) return { 'unit': self.object, 'accepted_suggestion': accepted_suggestion, 'form': self.get_unit_edit_form(), 'comment_form': self.get_unit_comment_form(), 'priority': priority, 'store': self.store, 'directory': self.directory, 'user': self.request.user, 'project': self.project, 'language': self.language, 'special_characters': self.special_characters, 'source_language': self.source_language, 'cantranslate': check_user_permission(self.request.user, "translate", self.directory), 'cantranslatexlang': check_user_permission(self.request.user, "administrate", self.project.directory), 'cansuggest': check_user_permission(self.request.user, "suggest", self.directory), 'canreview': check_user_permission(self.request.user, "review", self.directory), 'has_admin_access': check_user_permission(self.request.user, 'administrate', self.directory), 'altsrcs': {x.id: x.data for x in self.get_alt_srcs()}, 'unit_values': self.get_unit_values(), 'target_nplurals': self.get_target_nplurals(), 'has_plurals': self.object.hasplural(), 'filetype': self.object.store.filetype.name, 'suggestions': suggestions, 'suggestions_dict': {x.id: dict(id=x.id, target=x.target.strings) for x in suggestions}, "failing_checks": failing_checks, "critical_checks": critical_checks, "warning_checks": list( self.object.get_warning_qualitychecks()), "terms": self.object.get_terminology()} def get_response_data(self, context): return { 'editor': self.render_edit_template(context), 'tm_suggestions': self.object.get_tm_suggestions(), 'is_obsolete': self.object.isobsolete(), 'sources': self.get_sources()} @get_unit_context('view') def permalink_redirect(request, unit): return redirect(request.build_absolute_uri(unit.get_translate_url())) class UnitSuggestionJSON(PootleJSONMixin, GatherContextMixin, FormView): action = "accept" form_class = SuggestionReviewForm http_method_names = ['post', 'delete'] @property def permission_context(self): return self.get_object().unit.store.parent @set_permissions @requires_permission("view") def dispatch(self, request, *args, **kwargs): # get funky with the request 8/ return super(UnitSuggestionJSON, self).dispatch(request, *args, **kwargs) @lru_cache() def get_object(self): return get_object_or_404( Suggestion.objects.select_related( "unit", "unit__store", "unit__store__parent", "unit__change", "state"), unit_id=self.request.resolver_match.kwargs["uid"], id=self.request.resolver_match.kwargs["sugg_id"]) def get_form_kwargs(self, **kwargs): comment = ( QueryDict(self.request.body).get("comment") if self.action == "reject" else self.request.POST.get("comment")) is_fuzzy = ( QueryDict(self.request.body).get("is_fuzzy") if self.action == "reject" else self.request.POST.get("is_fuzzy")) return dict( target_object=self.get_object(), request_user=self.request.user, data=dict( is_fuzzy=is_fuzzy, comment=comment, action=self.action)) def delete(self, request, *args, **kwargs): self.action = "reject" return self.post(request, *args, **kwargs) def get_context_data(self, *args, **kwargs): ctx = super(UnitSuggestionJSON, self).get_context_data(*args, **kwargs) form = ctx["form"] if form.is_valid(): result = dict( udbid=form.target_object.unit.id, sugid=form.target_object.id, user_score=self.request.user.public_score) if form.cleaned_data["action"] == "accept": result.update( dict( newtargets=[ target for target in form.target_object.unit.target.strings], checks=_get_critical_checks_snippet( self.request, form.target_object.unit))) return result def form_valid(self, form): form.save() return self.render_to_response( self.get_context_data(form=form)) def form_invalid(self, form): if form.non_field_errors(): raise Http404 raise Http400(form.errors) @ajax_required @get_unit_context('review') def toggle_qualitycheck(request, unit, check_id, **kwargs_): try: unit.toggle_qualitycheck(check_id, 'mute' in request.POST, request.user) except ObjectDoesNotExist: raise Http404 return JsonResponse({}) class UnitSubmitJSON(UnitSuggestionJSON): @set_permissions @requires_permission("translate") def dispatch(self, request, *args, **kwargs): # get funky with the request 8/ return super(UnitSuggestionJSON, self).dispatch(request, *args, **kwargs) @property def form_class(self): if self.get_suggestion(): return SuggestionSubmitForm return SubmitForm @property def permission_context(self): return self.get_object().store.parent @lru_cache() def get_object(self): return get_object_or_404( Unit.objects.select_related( "store", "change", "store__parent", "store__translation_project", "store__filetype", "store__translation_project__language", "store__translation_project__project", "store__data", "store__translation_project__data"), id=self.request.resolver_match.kwargs["uid"]) @lru_cache() def get_suggestion(self): if "suggestion" in self.request.POST: return get_object_or_404( Suggestion, unit_id=self.get_object().id, id=self.request.POST["suggestion"]) def get_form_kwargs(self, **kwargs): kwargs = dict( unit=self.get_object(), request_user=self.request.user, data=self.request.POST) if self.get_suggestion(): kwargs["target_object"] = self.get_suggestion() return kwargs def get_context_data(self, *args, **kwargs): ctx = super(UnitSuggestionJSON, self).get_context_data(*args, **kwargs) form = ctx["form"] if form.is_valid(): form.unit.refresh_from_db() result = dict( checks=_get_critical_checks_snippet(self.request, form.unit), user_score=self.request.user.public_score, newtargets=[target for target in form.unit.target.strings], critical_checks_active=( form.unit.get_active_critical_qualitychecks().exists())) return result class UnitAddSuggestionJSON(PootleJSONMixin, GatherContextMixin, FormView): form_class = AddSuggestionForm http_method_names = ['post'] @set_permissions @requires_permission("suggest") def dispatch(self, request, *args, **kwargs): # get funky with the request 8/ return super(UnitAddSuggestionJSON, self).dispatch(request, *args, **kwargs) @property def permission_context(self): return self.get_object().store.parent @lru_cache() def get_object(self): return get_object_or_404( Unit.objects.select_related( "store", "store__parent", "store__translation_project", "store__filetype", "store__translation_project__language", "store__translation_project__project", "store__data", "store__translation_project__data"), id=self.request.resolver_match.kwargs["uid"]) def get_form_kwargs(self, **kwargs): kwargs = dict( unit=self.get_object(), request_user=self.request.user, data=self.request.POST) return kwargs def get_context_data(self, *args, **kwargs): ctx = super(UnitAddSuggestionJSON, self).get_context_data(*args, **kwargs) form = ctx["form"] if form.is_valid(): data = dict() if not self.request.user.is_anonymous: data['user_score'] = self.request.user.public_score return data def form_valid(self, form): form.save() return self.render_to_response( self.get_context_data(form=form)) def form_invalid(self, form): if form.non_field_errors(): raise Http404 raise Http400(form.errors)
26,523
Python
.py
629
31.874404
84
0.610238
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,307
managers.py
translate_pootle/pootle/apps/pootle_store/managers.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.db import models from pootle.core.url_helpers import split_pootle_path from pootle_app.models import Directory from .constants import OBSOLETE class SuggestionManager(models.Manager): def pending(self): return self.get_queryset().filter(state__name="pending") class UnitManager(models.Manager): def live(self): """Filters non-obsolete units.""" return self.filter(state__gt=OBSOLETE, store__obsolete=False) def get_for_user(self, user): """Filters units for a specific user. - Admins always get all non-obsolete units - Regular users only get units from enabled projects accessible to them. :param user: The user for whom units need to be retrieved for. :return: A filtered queryset with `Unit`s for `user`. """ from pootle_project.models import Project if user.is_superuser: return self.live() user_projects = Project.accessible_by_user(user) filter_by = { "store__translation_project__project__disabled": False, "store__translation_project__project__code__in": user_projects } return self.live().filter(**filter_by) def get_translatable(self, user, project_code=None, language_code=None, dir_path=None, filename=None): """Returns translatable units for a `user`, optionally filtered by their location within Pootle. :param user: The user who is accessing the units. :param project_code: A string for matching the code of a Project. :param language_code: A string for matching the code of a Language. :param dir_path: A string for matching the dir_path and descendants from the TP. :param filename: A string for matching the filename of Stores. """ units_qs = self.get_for_user(user) if language_code: units_qs = units_qs.filter( store__translation_project__language__code=language_code) else: units_qs = units_qs.exclude(store__is_template=True) if project_code: units_qs = units_qs.filter( store__translation_project__project__code=project_code) if not (dir_path or filename): return units_qs tp_path = "/%s%s" % ( dir_path or "", filename or "") if filename: return units_qs.filter( store__tp_path=tp_path) else: return units_qs.filter( store__tp_path__startswith=tp_path) class StoreManager(models.Manager): def live(self): """Filters non-obsolete stores.""" return self.filter(obsolete=False) def create(self, *args, **kwargs): if "filetype" not in kwargs: filetypes = kwargs["translation_project"].project.filetype_tool kwargs['filetype'] = filetypes.choose_filetype(kwargs["name"]) if kwargs["translation_project"].is_template_project: kwargs["is_template"] = True kwargs["pootle_path"] = ( "%s%s" % (kwargs["parent"].pootle_path, kwargs["name"])) kwargs["tp_path"] = ( "%s%s" % (kwargs["parent"].tp_path, kwargs["name"])) return super(StoreManager, self).create(*args, **kwargs) def get_or_create(self, *args, **kwargs): store, created = super(StoreManager, self).get_or_create(*args, **kwargs) if not created: return store, created update = False if store.translation_project.is_template_project: store.is_template = True update = True if "filetype" not in kwargs: filetypes = store.translation_project.project.filetype_tool store.filetype = filetypes.choose_filetype(store.name) update = True if update: store.save() return store, created def create_by_path(self, pootle_path, project=None, create_tp=True, create_directory=True, **kwargs): from pootle_language.models import Language from pootle_project.models import Project (lang_code, proj_code, dir_path, filename) = split_pootle_path(pootle_path) ext = filename.split(".")[-1] if project is None: project = Project.objects.get(code=proj_code) elif project.code != proj_code: raise ValueError( "Project must match pootle_path when provided") if ext not in project.filetype_tool.valid_extensions: raise ValueError( "'%s' is not a valid extension for this Project" % ext) if create_tp: tp, created = ( project.translationproject_set.get_or_create( language=Language.objects.get(code=lang_code))) elif create_directory or not dir_path: tp = project.translationproject_set.get( language__code=lang_code) if dir_path: if not create_directory: parent = Directory.objects.get( pootle_path="/".join( ["", lang_code, proj_code, dir_path])) else: parent = tp.directory for child in dir_path.strip("/").split("/"): parent, created = Directory.objects.get_or_create( tp=tp, name=child, parent=parent) else: parent = tp.directory store, created = self.get_or_create( name=filename, parent=parent, translation_project=tp, **kwargs) return store
5,999
Python
.py
136
33.441176
81
0.604938
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,308
filters.py
translate_pootle/pootle/apps/pootle_store/unit/filters.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.db.models import Q from pootle_statistics.models import SubmissionTypes from pootle_store.constants import FUZZY, TRANSLATED, UNTRANSLATED class FilterNotFound(Exception): pass class BaseUnitFilter(object): def __init__(self, qs, *args_, **kwargs_): self.qs = qs def filter(self, unit_filter): try: return getattr( self, "filter_%s" % unit_filter.replace("-", "_"))() except AttributeError: raise FilterNotFound() class UnitChecksFilter(BaseUnitFilter): def __init__(self, qs, *args, **kwargs): self.qs = qs self.checks = kwargs.get("checks") self.category = kwargs.get("category") def filter_checks(self): if self.checks: return self.qs.filter( qualitycheck__false_positive=False, qualitycheck__name__in=self.checks).distinct() elif self.category: return self.qs.filter( qualitycheck__false_positive=False, qualitycheck__category=self.category).distinct() return self.qs.none() class UnitStateFilter(BaseUnitFilter): """Filter a Unit qs based on unit state""" def filter_all(self): return self.qs.all() def filter_translated(self): return self.qs.filter(state=TRANSLATED) def filter_untranslated(self): return self.qs.filter(state=UNTRANSLATED) def filter_fuzzy(self): return self.qs.filter(state=FUZZY) def filter_incomplete(self): return self.qs.filter( Q(state=UNTRANSLATED) | Q(state=FUZZY)) class UnitContributionFilter(BaseUnitFilter): """Filter a Unit qs based on user contributions""" def __init__(self, qs, *args, **kwargs): self.qs = qs self.user = kwargs.get("user") def filter_suggestions(self): return self.qs.filter( suggestion__state__name="pending").distinct() def filter_user_suggestions(self): if not self.user: return self.qs.none() return self.qs.filter( suggestion__user=self.user, suggestion__state__name="pending").distinct() def filter_my_suggestions(self): return self.filter_user_suggestions() def filter_user_suggestions_accepted(self): if not self.user: return self.qs.none() return self.qs.filter( suggestion__user=self.user, suggestion__state__name="accepted").distinct() def filter_user_suggestions_rejected(self): if not self.user: return self.qs.none() return self.qs.filter( suggestion__user=self.user, suggestion__state__name="rejected").distinct() def filter_user_submissions(self): if not self.user: return self.qs.none() return self.qs.filter(change__submitted_by=self.user) def filter_my_submissions(self): return self.filter_user_submissions() def filter_user_submissions_overwritten(self): if not self.user: return self.qs.none() qs = self.qs.exclude(change__submitted_by=self.user) return ( qs.filter( submission__submitter_id=self.user.id, submission__type__in=SubmissionTypes.EDIT_TYPES, submission__suggestion__isnull=True) | qs.filter( submission__suggestion__isnull=False, submission__suggestion__user_id=self.user.id, submission__suggestion__state__name="accepted")).distinct() def filter_my_submissions_overwritten(self): return self.filter_user_submissions_overwritten() class UnitSearchFilter(object): filters = ( UnitChecksFilter, UnitStateFilter, UnitContributionFilter) def filter(self, qs, unit_filter, *args, **kwargs): for search_filter in self.filters: # try each of the filter classes to find one with a method to handle # `unit_filter` try: return search_filter(qs, *args, **kwargs).filter(unit_filter) except FilterNotFound: pass # if none match then return the empty qs return qs.none() class UnitTextSearch(object): """Search Unit's fields for text strings """ search_fields = ( "source_f", "target_f", "locations", "translator_comment", "developer_comment") search_mappings = { "notes": ["translator_comment", "developer_comment"], "source": ["source_f"], "target": ["target_f"]} def __init__(self, qs): self.qs = qs def get_search_fields(self, sfields): search_fields = set() for field in sfields: if field in self.search_mappings: search_fields.update(self.search_mappings[field]) elif field in self.search_fields: search_fields.add(field) return search_fields def get_words(self, text, exact): if exact: return [text] return [t.strip() for t in text.split(" ") if t.strip()] def search(self, text, sfields, exact=False, case=False): result = self.qs.none() words = self.get_words(text, exact) for k in self.get_search_fields(sfields): result |= self.search_field(k, words, exact=exact, case=case) return result def search_field(self, k, words, exact=False, case=False): subresult = self.qs contains = ( "contains" if case else "icontains") for word in words: subresult = subresult.filter( **{("%s__%s" % (k, contains)): word}) return subresult
6,035
Python
.py
151
30.781457
80
0.619178
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,309
proxy.py
translate_pootle/pootle/apps/pootle_store/unit/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 pootle_store.fields import to_python as multistring_to_python class UnitProxy(object): """Wraps a values Unit dictionary""" @property def source(self): return multistring_to_python(self.unit["source_f"]) @property def target(self): return multistring_to_python(self.unit["target_f"]) def __init__(self, unit): self.unit = unit def __getattr__(self, k): try: return self.__dict__["unit"][k] or "" except KeyError: return self.__getattribute__(k) def getlocations(self): if self.locations is None: return [] return filter(None, self.locations.split('\n')) def hasplural(self): return ( self.source is not None and (len(self.source.strings) > 1 or getattr(self.source, "plural", None)))
1,150
Python
.py
32
29.125
77
0.634806
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,310
altsrc.py
translate_pootle/pootle/apps/pootle_store/unit/altsrc.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 language_dir from pootle_store.templatetags.store_tags import pluralize_target from .proxy import UnitProxy class AltSrcUnitProxy(UnitProxy): @property def language_code(self): return self.unit["store__translation_project__language__code"] @property def language_direction(self): return language_dir(self.language_code) @property def language_name(self): return self.unit["store__translation_project__language__fullname"] @property def nplurals(self): return self.unit["store__translation_project__language__nplurals"] or 0 @property def data(self): return dict( id=self.id, language_code=self.language_code, language_name=self.language_name, language_direction=self.language_direction, nplurals=self.nplurals, has_plurals=self.hasplural(), target=[target[1] for target in pluralize_target(self, self.nplurals)], ) class AltSrcUnits(object): fields = { "id", "source_f", "target_f", "store__translation_project__language__code", "store__translation_project__language__fullname", "store__translation_project__language__nplurals", } def __init__(self, qs): self.qs = qs @property def units(self): return [AltSrcUnitProxy(x) for x in self.qs.values(*self.fields)]
1,776
Python
.py
50
28.36
79
0.657526
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,311
search.py
translate_pootle/pootle/apps/pootle_store/unit/search.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.db.models import Max from django.utils.functional import cached_property from pootle_store.constants import SIMPLY_SORTED from pootle_store.models import Unit from pootle_store.unit.filters import UnitSearchFilter, UnitTextSearch class DBSearchBackend(object): default_chunk_size = None default_order = "store__pootle_path", "index" select_related = ( 'store__translation_project__project', 'store__translation_project__language') def __init__(self, request_user, **kwargs): self.kwargs = kwargs self.request_user = request_user @property def chunk_size(self): return self.kwargs.get( 'count', self.default_chunk_size) @property def project_code(self): return self.kwargs.get("project_code") @property def language_code(self): return self.kwargs.get("language_code") @property def dir_path(self): return self.kwargs.get("dir_path") @property def filename(self): return self.kwargs.get("filename") @property def unit_filter(self): return self.kwargs.get("filter") @property def offset(self): return self.kwargs.get("offset", None) @property def previous_uids(self): return self.kwargs.get("previous_uids", []) or [] @property def sort_by(self): return self.kwargs.get("sort_by") @property def sort_on(self): return self.kwargs.get("sort_on") @property def qs_kwargs(self): kwargs = { k: getattr(self, k) for k in [ "project_code", "language_code", "dir_path", "filename"]} kwargs["user"] = self.request_user return kwargs @property def uids(self): return self.kwargs.get("uids", []) @property def units_qs(self): return ( Unit.objects.get_translatable(**self.qs_kwargs) .order_by(*self.default_order) .select_related(*self.select_related)) def sort_qs(self, qs): if self.unit_filter and self.sort_by is not None: sort_by = self.sort_by if self.sort_on not in SIMPLY_SORTED: # Omit leading `-` sign if self.sort_by[0] == '-': max_field = self.sort_by[1:] sort_by = '-sort_by_field' else: max_field = self.sort_by sort_by = 'sort_by_field' # It's necessary to use `Max()` here because we can't # use `distinct()` and `order_by()` at the same time qs = qs.annotate(sort_by_field=Max(max_field)) return qs.order_by( sort_by, "store__pootle_path", "index") return qs def filter_qs(self, qs): kwargs = self.kwargs category = kwargs['category'] checks = kwargs['checks'] exact = 'exact' in kwargs['soptions'] case = 'case' in kwargs['soptions'] modified_since = kwargs['modified-since'] month = kwargs['month'] search = kwargs['search'] sfields = kwargs['sfields'] user = kwargs['user'] if self.unit_filter: qs = UnitSearchFilter().filter( qs, self.unit_filter, user=user, checks=checks, category=category) if modified_since is not None: qs = qs.filter( change__submitted_on__gt=modified_since).distinct() if month is not None: qs = qs.filter( change__submitted_on__gte=month[0], change__submitted_on__lte=month[1]).distinct() if sfields and search: qs = UnitTextSearch(qs).search( search, sfields, exact=exact, case=case) return qs @cached_property def results(self): return self.sort_qs(self.filter_qs(self.units_qs)) def search(self): total = self.results.count() start = self.offset if start > (total + len(self.previous_uids)): return total, total, total, self.results.none() find_unit = ( self.language_code and self.project_code and self.filename and self.uids) find_next_slice = ( self.previous_uids and self.offset) if not find_unit and find_next_slice: # if both previous_uids and offset are set then try to ensure # that the results we are returning start from the end of previous # result set _start = start = max(self.offset - len(self.previous_uids), 0) end = min(self.offset + (2 * self.chunk_size), total) uid_list = self.results[start:end].values_list("pk", flat=True) offset = 0 for i, uid in enumerate(uid_list): if uid in self.previous_uids: start = _start + i + 1 offset = i + 1 start = start or 0 end = min(start + (2 * self.chunk_size), total) return ( total, start, end, uid_list[offset:offset + (2 * self.chunk_size)]) if find_unit: # find the uid in the Store uid_list = list(self.results.values_list("pk", flat=True)) if self.chunk_size and self.uids[0] in uid_list: unit_index = uid_list.index(self.uids[0]) start = ( int(unit_index / (2 * self.chunk_size)) * (2 * self.chunk_size)) if self.chunk_size is None: return total, 0, total, self.results start = start or 0 end = min(start + (2 * self.chunk_size), total) return ( total, start, end, list(self.results[start:end].values_list("pk", flat=True)))
6,340
Python
.py
168
27.035714
78
0.556985
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,312
results.py
translate_pootle/pootle/apps/pootle_store/unit/results.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 itertools import groupby from django.urls import reverse from pootle.core.url_helpers import split_pootle_path from pootle.i18n.gettext import language_dir from pootle_store.constants import FUZZY from pootle_store.models import Unit from pootle_store.templatetags.store_tags import ( pluralize_source, pluralize_target) from pootle_store.unit.proxy import UnitProxy class UnitResult(UnitProxy): @property def filetype(self): return self.unit["store__filetype__name"] @property def nplurals(self): return self.unit[ "store__translation_project__language__nplurals"] or 0 @property def pootle_path(self): return self.unit["store__pootle_path"] @property def project_code(self): return self.unit["store__translation_project__project__code"] @property def project_style(self): return self.unit[ "store__translation_project__project__checkstyle"] @property def source_dir(self): return language_dir(self.source_lang) @property def source_lang(self): return self.unit[ "store__translation_project__project__source_language__code"] @property def target_dir(self): return language_dir(self.target_lang) @property def target_lang(self): return self.unit[ "store__translation_project__language__code"] @property def translate_url(self): return ( u'%s%s' % (reverse("pootle-tp-store-translate", args=split_pootle_path(self.pootle_path)), '#unit=%s' % unicode(self.id))) class StoreResults(object): def __init__(self, units): self.units = units @property def data(self): meta = None units_list = [] for unit in iter(self.units): unit = UnitResult(unit) if meta is None: meta = { 'filetype': unit.filetype, 'source_lang': unit.source_lang, 'source_dir': unit.source_dir, 'target_lang': unit.target_lang, 'target_dir': unit.target_dir, 'project_code': unit.project_code, 'project_style': unit.project_style} units_list.append( {'id': unit.id, 'url': unit.translate_url, 'isfuzzy': unit.state == FUZZY, 'source': [source[1] for source in pluralize_source(unit)], 'target': [target[1] for target in pluralize_target(unit, unit.nplurals)]}) return { 'meta': meta, 'units': units_list} class GroupedResults(object): select_fields = [ "id", "source_f", "target_f", "state", "store__filetype__name", "store__pootle_path", "store__translation_project__project__code", "store__translation_project__project__source_language__code", "store__translation_project__project__checkstyle", "store__translation_project__language__code", "store__translation_project__language__nplurals"] def __init__(self, units): self.units = units @property def data(self): unit_groups = [] units = { unit["id"]: unit for unit in Unit.objects.filter( pk__in=self.units).values(*self.select_fields)} units = [units[pk] for pk in self.units] units_by_path = groupby( units, lambda x: x["store__pootle_path"]) for pootle_path, units in units_by_path: unit_groups.append({pootle_path: StoreResults(units).data}) return unit_groups
4,173
Python
.py
116
26.258621
77
0.584573
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,313
__init__.py
translate_pootle/pootle/apps/pootle_store/unit/__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 .proxy import UnitProxy __all__ = ("UnitProxy", )
333
Python
.py
9
35.666667
77
0.741433
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,314
timeline.py
translate_pootle/pootle/apps/pootle_store/unit/timeline.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 itertools import groupby from django.urls import reverse from django.utils.functional import cached_property from django.utils.html import format_html from accounts.proxy import DisplayUser from pootle.core.delegate import event_formatters, grouped_events from pootle.core.proxy import BaseProxy from pootle.i18n.gettext import ugettext_lazy as _ from pootle_checks.constants import CHECK_NAMES from pootle_comment import get_model as get_comment_model from pootle_log.utils import GroupedEvents, UnitLog from pootle_statistics.models import ( Submission, SubmissionFields, SubmissionTypes) from pootle_store.constants import STATES_MAP from pootle_store.fields import to_python from pootle_store.models import Suggestion ACTION_ORDER = { 'unit_created': 0, 'suggestion_created': 5, 'suggestion_rejected': 5, 'source_updated': 10, 'state_changed': 10, 'target_updated': 20, 'suggestion_accepted': 25, 'comment_updated': 30, 'check_muted': 40, 'check_unmuted': 40, } class UnitTimelineLog(UnitLog): @property def suggestion_qs(self): return Suggestion.objects class SuggestionEvent(object): def __init__(self, suggestion, **kwargs): self.suggestion = suggestion @property def comment(self): comments = get_comment_model().objects.for_model(Suggestion) comments = comments.filter( object_pk=self.suggestion.id).values_list("comment", flat=True) if comments: return comments[0] @cached_property def user(self): return DisplayUser(self.suggestion.user.username, self.suggestion.user.full_name) class SuggestionAddedEvent(SuggestionEvent): @property def context(self): return dict( value=self.suggestion.target, description=_(u"Added suggestion")) class SuggestionAcceptedEvent(SuggestionEvent): def __init__(self, suggestion, **kwargs): super(SuggestionAcceptedEvent, self).__init__(suggestion) @property def context(self): params = { 'author': self.user.author_link} sugg_accepted_desc = _(u'Accepted suggestion from %(author)s', params) if self.comment: params.update({ 'comment': format_html(u'<span class="comment">{}</span>', self.comment), }) sugg_accepted_desc = _( u'Accepted suggestion from %(author)s ' u'with comment: %(comment)s', params) target = self.suggestion.target submission = self.suggestion.submission_set.filter( field=SubmissionFields.TARGET).first() if submission: target = submission.new_value return dict( value=target, translation=True, description=format_html(sugg_accepted_desc)) class SuggestionRejectedEvent(SuggestionEvent): @property def context(self): params = { 'author': self.user.author_link} sugg_rejected_desc = _(u'Rejected suggestion from %(author)s', params) if self.comment: params.update({ 'comment': format_html(u'<span class="comment">{}</span>', self.comment), }) sugg_rejected_desc = _( u'Rejected suggestion from %(author)s ' u'with comment: %(comment)s', params) return dict( value=self.suggestion.target, description=format_html(sugg_rejected_desc)) class SubmissionEvent(object): def __init__(self, submission, **kwargs): self.submission = submission class TargetUpdatedEvent(SubmissionEvent): @property def context(self): suggestion_accepted = (self.submission.suggestion_id and self.submission.suggestion.is_accepted) if suggestion_accepted: return None return dict( value=self.submission.new_value, translation=True) class UnitCreatedEvent(object): def __init__(self, unit_source, **kwargs): self.unit_source = unit_source self.target_event = kwargs.get("target_event") @property def context(self): ctx = dict(description=_(u"Unit created")) if self.target_event is not None: if self.target_event.value.old_value != '': ctx['value'] = self.target_event.value.old_value ctx['translation'] = True else: if self.unit_source.unit.istranslated(): ctx['value'] = self.unit_source.unit.target ctx['translation'] = True return ctx class UnitStateChangedEvent(SubmissionEvent): @property def context(self): return dict( value=format_html( u"{} <span class='timeline-arrow'></span> {}", STATES_MAP[int(to_python(self.submission.old_value))], STATES_MAP[int(to_python(self.submission.new_value))]), state=True) class CommentUpdatedEvent(SubmissionEvent): @property def context(self): if self.submission.new_value: return dict( value=self.submission.new_value, sidetitle=_(u"Comment:"), comment=True) return dict(description=_(u"Removed comment")) class CheckEvent(SubmissionEvent): @cached_property def check_name(self): return self.submission.quality_check.name @cached_property def check_url(self): return u''.join( [reverse('pootle-checks-descriptions'), '#', self.check_name]) @property def check_link(self): return format_html(u"<a href='{}'>{}</a>", self.check_url, CHECK_NAMES[self.check_name]) class CheckMutedEvent(CheckEvent): @property def context(self): return dict( description=format_html(_( u"Muted %(check_name)s check", {'check_name': self.check_link}))) class CheckUnmutedEvent(CheckEvent): @property def context(self): return dict( description=format_html(_( u"Unmuted %(check_name)s check", {'check_name': self.check_link}))) class Timeline(object): def __init__(self, obj): self.object = obj self.log = UnitTimelineLog(self.object) self.events_adapter = grouped_events.get(self.log.__class__)(self.log) def grouped_events(self, **kwargs): groups = [] target_event = None for __, group in self.events_adapter.grouped_events(**kwargs): event_group = EventGroup(group, target_event) if event_group.target_event: target_event = event_group.target_event if event_group.events: groups.append(event_group.context) return groups class ComparableUnitTimelineLogEvent(BaseProxy): _special_names = (x for x in BaseProxy._special_names if x not in ["__lt__", "__gt__"]) def __cmp__(self, other): # valuable revisions are authoritative if self.revision is not None and other.revision is not None: if self.revision > other.revision: return 1 elif self.revision < other.revision: return -1 # timestamps have the next priority if self.timestamp and other.timestamp: if self.timestamp > other.timestamp: return 1 elif self.timestamp < other.timestamp: return -1 elif self.timestamp: return 1 elif other.timestamp: return -1 # conditions below are applied for events with equal timestamps # or without any action_order = ACTION_ORDER[self.action] - ACTION_ORDER[other.action] if action_order > 0: return 1 elif action_order < 0: return -1 if self.action == other.action: if self.value.pk > other.value.pk: return 1 elif self.value.pk < other.value.pk: return -1 return 0 class UnitTimelineGroupedEvents(GroupedEvents): def grouped_events(self, start=None, end=None, users=None): def _group_id(event): user_id = event.user.id if event.action == 'suggestion_accepted': user_id = event.value.user_id return '%s\001%s' % (event.timestamp, user_id) return groupby( self.sorted_events( start=start, end=end, users=users, reverse=True), key=_group_id) class EventGroup(object): def __init__(self, log_events, related_target_event=None): self.log_events = OrderedDict() self.related_target_event = related_target_event self.log_event_class = None for event in log_events: if self.log_event_class is None: self.log_event_class = event.__class__ self.log_events[event.action] = event @cached_property def event_formatters(self): return event_formatters.gather(self.log_event_class) @property def target_event(self): return self.log_events.get('target_updated') @property def context_event(self): event = self.log_events.get('suggestion_accepted') if event is not None: return event event = self.log_events.get('target_updated') if event is not None: return event if len(self.log_events) > 0: return self.log_events.values()[0] return None @property def events(self): events = [] for event_action in self.log_events: event_formatter_class = self.event_formatters.get(event_action) if event_formatter_class is not None: ctx = event_formatter_class( self.log_events[event_action].value, target_event=self.related_target_event).context if ctx is not None: events.append(ctx) return events @property def user(self): if 'suggestion_accepted' in self.log_events: return self.log_events['suggestion_accepted'].user return self.context_event.user @property def context(self): return { 'events': self.events, 'via_upload': self.via_upload, 'datetime': self.context_event.timestamp, 'user': DisplayUser( self.user.username, self.user.full_name, self.user.email), } @property def via_upload(self): if isinstance(self.context_event.value, Submission): return self.context_event.value == SubmissionTypes.UPLOAD return False
11,377
Python
.py
299
28.294314
78
0.609486
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,315
store_tags.py
translate_pootle/pootle/apps/pootle_store/templatetags/store_tags.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 re from django import template from django.core.exceptions import ObjectDoesNotExist from pootle.core.utils.templates import get_template_source from pootle.i18n.gettext import ugettext as _ register = template.Library() IMAGE_URL_RE = re.compile("(https?://[^\s]+\.(png|jpe?g|gif))", re.IGNORECASE) @register.filter def image_urls(text): """Return a list of image URLs extracted from `text`.""" return map(lambda x: x[0], IMAGE_URL_RE.findall(text)) @register.filter('pluralize_source') def pluralize_source(unit): if not unit.hasplural(): return [(0, unit.source, None)] count = len(unit.source.strings) if count == 1: return [(0, unit.source.strings[0], "%s+%s" % (_('Singular'), _('Plural')))] if count == 2: return [(0, unit.source.strings[0], _('Singular')), (1, unit.source.strings[1], _('Plural'))] forms = [] for i, source in enumerate(unit.source.strings): forms.append((i, source, _('Plural Form %d', i))) return forms @register.filter('pluralize_target') def pluralize_target(unit, nplurals=None): if not unit.hasplural(): return [(0, unit.target, None)] if nplurals is None: try: nplurals = unit.store.translation_project.language.nplurals except ObjectDoesNotExist: pass forms = [] if nplurals is None: for i, target in enumerate(unit.target.strings): forms.append((i, target, _('Plural Form %d', i))) else: for i in range(nplurals): try: target = unit.target.strings[i] except IndexError: target = '' forms.append((i, target, _('Plural Form %d', i))) return forms @register.tag(name="include_raw") def do_include_raw(parser, token): """ Performs a template include without parsing the context, just dumps the template in. Source: http://djangosnippets.org/snippets/1684/ """ bits = token.split_contents() if len(bits) != 2: raise template.TemplateSyntaxError( "%r tag takes one argument: the name of the template " "to be included" % bits[0] ) template_name = bits[1] if (template_name[0] in ('"', "'") and template_name[-1] == template_name[0]): template_name = template_name[1:-1] source, __ = get_template_source(template_name) return template.base.TextNode(source)
2,800
Python
.py
73
31.410959
78
0.629068
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,316
0038_suggestion_tmp_state.py
translate_pootle/pootle/apps/pootle_store/migrations/0038_suggestion_tmp_state.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-28 05:28 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0037_unitsource_fields'), ] operations = [ migrations.AddField( model_name='suggestion', name='tmp_state', field=models.CharField(choices=[('pending', 'Pending'), ('accepted', 'Accepted'), ('rejected', 'Rejected')], db_index=True, default='pending', max_length=16), ), ]
580
Python
.py
15
32.266667
170
0.632143
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,317
0004_index_store_index_together.py
translate_pootle/pootle/apps/pootle_store/migrations/0004_index_store_index_together.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0003_remove_unit_ordering'), ] operations = [ migrations.AlterIndexTogether( name='unit', index_together=set([('store', 'index')]), ), ]
385
Python
.py
13
23.307692
54
0.613079
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,318
0020_store_tp_path.py
translate_pootle/pootle/apps/pootle_store/migrations/0020_store_tp_path.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.11 on 2016-11-04 12:32 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0019_remove_unit_priority'), ] operations = [ migrations.AddField( model_name='store', name='tp_path', field=models.CharField(blank=True, db_index=True, max_length=255, null=True, verbose_name='Path'), ), ]
516
Python
.py
15
28
110
0.635081
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,319
0024_set_store_base_manager_name.py
translate_pootle/pootle/apps/pootle_store/migrations/0024_set_store_base_manager_name.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-01-20 07:49 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0023_add_unit_store_idxs'), ] operations = [ migrations.AlterModelOptions( name='store', options={'base_manager_name': 'objects', 'ordering': ['pootle_path']}, ), ]
454
Python
.py
14
26.5
82
0.627586
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,320
0048_set_change_commented.py
translate_pootle/pootle/apps/pootle_store/migrations/0048_set_change_commented.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-21 11:33 from __future__ import unicode_literals from django.contrib.auth import get_user_model from django.db import migrations from django.db.models import Value from pootle_statistics.models import SubmissionTypes def _add_comment_attrib(values, unit_changes, units_with_change, no_user=False): system_user = get_user_model().objects.get_system_user() existing_change = values.filter(id__in=units_with_change) no_existing_change = values.exclude(id__in=units_with_change) updated = 0 for res in existing_change.iterator(): if no_user: unit, timestamp = res user = system_user.id else: unit, timestamp, user = res updated = unit_changes.filter(unit_id=unit).update( commented_by_id=user, commented_on=timestamp) if no_user: return ( updated, len(unit_changes.bulk_create( [unit_changes.model( unit_id=unit, changed_with=SubmissionTypes.SYSTEM, commented_by_id=system_user.id, commented_on=timestamp) for unit, timestamp in no_existing_change.iterator()]))) else: return ( updated, len(unit_changes.bulk_create( [unit_changes.model( unit_id=unit, changed_with=( SubmissionTypes.SYSTEM if user == system_user else SubmissionTypes.WEB), commented_by_id=user, commented_on=timestamp) for unit, timestamp, user in no_existing_change.iterator()]))) def set_change_commented(apps, schema_editor): system_user = get_user_model().objects.get_system_user() units = apps.get_model("pootle_store.Unit").objects.all() unit_changes = apps.get_model("pootle_store.UnitChange").objects.all() units_with_comments = units.filter(translator_comment__gt="") # units with an existing change obj - not so many at this stage units_with_change = dict(units.filter(change__isnull=False).values_list("id", "change")) # units that have commented_by and commented_on commented = units_with_comments.filter( commented_on__isnull=False).filter(commented_by__isnull=False) _add_comment_attrib( commented.values_list("id", "commented_on", "commented_by"), unit_changes, units_with_change) # units that have comments and no attribution at all - use system/mtime no_attrib = units_with_comments.filter( commented_on__isnull=True).filter(commented_by__isnull=True) _add_comment_attrib( no_attrib.values_list("id", "mtime"), unit_changes, units_with_change, no_user=True) # units that have commented_by but no comment time - use commenter/mtime no_commented_on = units_with_comments.filter( commented_on__isnull=True).filter(commented_by__isnull=False) _add_comment_attrib( no_commented_on.values_list("id", "mtime", "commented_by"), unit_changes, units_with_change) # units that have commented_on but no commenter - use system/comment_time no_commented_by = units_with_comments.filter( commented_on__isnull=False).filter(commented_by__isnull=True) _add_comment_attrib( no_commented_by.values_list("id", "commented_on"), unit_changes, units_with_change, no_user=True) class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0047_remove_old_unit_fields'), ] operations = [ migrations.RunPython(set_change_commented), ]
3,825
Python
.py
89
33.449438
92
0.628594
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,321
0055_fill_unit_source_data.py
translate_pootle/pootle/apps/pootle_store/migrations/0055_fill_unit_source_data.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-04-28 11:31 from __future__ import unicode_literals import functools import logging from hashlib import md5 from django.conf import settings from django.db import migrations from django.utils.encoding import force_bytes from pootle.core.batch import Batch from pootle.core.delegate import wordcount from pootle_misc.util import import_func from pootle_store.fields import to_python from pootle_store.utils import UnitWordcount BATCH_SIZE = 500 logger = logging.getLogger(__name__) def unit_source_update(counter, unit_source): unit_source.source_hash = md5( force_bytes(unit_source.unit.source_f)).hexdigest() unit_source.source_length = len(unit_source.unit.source_f) unit_source.source_wordcount = max( 1, (counter.count_words(to_python(unit_source.unit.source_f)) or 0)) return unit_source def set_unit_source_data(apps, schema_editor): from pootle_store.models import Unit UnitSource = apps.get_model( "pootle_store.UnitSource") counter = wordcount.get(Unit) unit_sources = ( UnitSource.objects.select_related('unit') .filter(source_wordcount=0) .only("unit__source_f", "id") .order_by("id")) Batch(unit_sources, batch_size=BATCH_SIZE).update( unit_sources, update_method=functools.partial(unit_source_update, counter), update_fields=[ 'source_hash', 'source_length', 'source_wordcount']) class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0054_clean_abs_file_paths'), ] operations = [ migrations.RunPython(set_unit_source_data), ]
1,772
Python
.py
47
31.340426
76
0.684395
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,322
0030_store_tablename.py
translate_pootle/pootle/apps/pootle_store/migrations/0030_store_tablename.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-11 09:38 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0029_unit_tablename'), ] operations = [ migrations.AlterModelTable( name='store', table='pootle_store_store', ), ]
404
Python
.py
14
22.928571
48
0.628571
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,323
0034_limit_text_fields.py
translate_pootle/pootle/apps/pootle_store/migrations/0034_limit_text_fields.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-09-10 18:01 from __future__ import unicode_literals import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0033_remove_store_file'), ] operations = [ migrations.AlterField( model_name='qualitycheck', name='message', field=models.TextField(validators=[django.core.validators.MaxLengthValidator(4096)]), ), migrations.AlterField( model_name='unit', name='context', field=models.TextField(editable=False, null=True, validators=[django.core.validators.MaxLengthValidator(4096)]), ), migrations.AlterField( model_name='unit', name='developer_comment', field=models.TextField(blank=True, null=True, validators=[django.core.validators.MaxLengthValidator(4096)]), ), migrations.AlterField( model_name='unit', name='locations', field=models.TextField(editable=False, null=True, validators=[django.core.validators.MaxLengthValidator(4096)]), ), migrations.AlterField( model_name='unit', name='translator_comment', field=models.TextField(blank=True, null=True, validators=[django.core.validators.MaxLengthValidator(4096)]), ), ]
1,458
Python
.py
36
31.472222
124
0.639379
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,324
0040_remove_suggestion_state.py
translate_pootle/pootle/apps/pootle_store/migrations/0040_remove_suggestion_state.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-28 05:34 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0039_set_suggestion_tmp_state'), ] operations = [ migrations.RemoveField( model_name='suggestion', name='state', ), ]
407
Python
.py
14
23.142857
58
0.628866
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,325
0047_remove_old_unit_fields.py
translate_pootle/pootle/apps/pootle_store/migrations/0047_remove_old_unit_fields.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-21 00:20 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0046_unit_source_one_to_one'), ] operations = [ migrations.RemoveField( model_name='unit', name='source_hash', ), migrations.RemoveField( model_name='unit', name='source_length', ), migrations.RemoveField( model_name='unit', name='source_wordcount', ), ]
624
Python
.py
22
20.590909
56
0.574539
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,326
0028_set_created_by.py
translate_pootle/pootle/apps/pootle_store/migrations/0028_set_created_by.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-02 21:46 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0027_unit_created_by'), ] operations = [ ]
292
Python
.py
10
25.3
49
0.67509
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,327
0035_set_created_by_again.py
translate_pootle/pootle/apps/pootle_store/migrations/0035_set_created_by_again.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-02 21:46 from __future__ import unicode_literals import logging import time from django.db import migrations from pootle.core.user import get_system_user_id logger = logging.getLogger(__name__) def set_unit_created_by(apps, schema_editor): subs = apps.get_model("pootle_statistics.Submission").objects.all() UnitSource = apps.get_model("pootle_store.UnitSource") sources = UnitSource.objects.all() units = apps.get_model("pootle_store.Unit").objects.all() total = units.count() offset = 0 step = 10000 start = time.time() # type 10 is the now deleted UNIT_CREATE creators = dict( subs.filter(type=10) .exclude(submitter__username="system") .values_list("unit_id", "submitter")) sysuser = get_system_user_id() while True: UnitSource.objects.bulk_create( [UnitSource( unit_id=pk, created_by_id=creators.get(pk, sysuser)) for pk in units[offset: offset + step].values_list("id", flat=True)]) logger.debug( "added %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', '0034_unitsource'), ] operations = [ migrations.RunPython(set_unit_created_by), ]
1,505
Python
.py
43
28
75
0.626897
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,328
0006_remove_auto_now_add.py
translate_pootle/pootle/apps/pootle_store/migrations/0006_remove_auto_now_add.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0005_unit_priority'), ] operations = [ migrations.AlterField( model_name='unit', name='mtime', field=models.DateTimeField(auto_now=True, db_index=True), preserve_default=True, ), ]
453
Python
.py
15
23
69
0.6097
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,329
0018_move_priority_to_store.py
translate_pootle/pootle/apps/pootle_store/migrations/0018_move_priority_to_store.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models def move_priority_from_unit_to_store(apps, schema_editor): Unit = apps.get_model("pootle_store.Unit") Store = apps.get_model("pootle_store.Store") priorities = dict( Unit.objects.exclude(priority=1.0).values_list("store_id", "priority")) _prios = {} for store_id, priority in priorities.items(): _prios[priority] = _prios.get(priority, []) _prios[priority].append(store_id) Store.objects.all().update(priority=1.0) for prio, stores in _prios.items(): Store.objects.filter(id__in=stores).update(priority=prio) class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0017_store_priority'), ] operations = [ migrations.RunPython(move_priority_from_unit_to_store), ]
885
Python
.py
22
34.727273
79
0.675234
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,330
0039_set_suggestion_tmp_state.py
translate_pootle/pootle/apps/pootle_store/migrations/0039_set_suggestion_tmp_state.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-28 05:28 from __future__ import unicode_literals from django.db import migrations from django.db.models import F def set_suggestion_tmp(apps, schema_editor): suggestions = apps.get_model("pootle_store.Suggestion").objects.all() suggestions.update(tmp_state=F("state")) class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0038_suggestion_tmp_state'), ] operations = [ migrations.RunPython(set_suggestion_tmp), ]
544
Python
.py
15
32.133333
73
0.712644
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,331
0019_remove_unit_priority.py
translate_pootle/pootle/apps/pootle_store/migrations/0019_remove_unit_priority.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0018_move_priority_to_store'), ] operations = [ migrations.RemoveField( model_name='unit', name='priority', ), ]
361
Python
.py
13
21.461538
56
0.612245
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,332
0017_store_priority.py
translate_pootle/pootle/apps/pootle_store/migrations/0017_store_priority.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.core.validators class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0016_blank_last_sync_revision'), ('virtualfolder', '0003_case_sensitive_schema'), ] operations = [ migrations.AddField( model_name='store', name='priority', field=models.FloatField(default=1, db_index=True, validators=[django.core.validators.MinValueValidator(0)]), ), ]
569
Python
.py
16
29
120
0.656934
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,333
0033_conditionally_remove_unit_created_by.py
translate_pootle/pootle/apps/pootle_store/migrations/0033_conditionally_remove_unit_created_by.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-15 14:42 from __future__ import unicode_literals from django.db import migrations def conditionally_remove_unit_created_by(apps, schema_editor): Unit = apps.get_model("pootle_store.Unit") connection = schema_editor.connection cursor = connection.cursor() fields = connection.introspection.get_table_description(cursor, Unit._meta.db_table) # Since we have no real way of controlling if when this is run the field # actually exists, we need to test the field exists. if 'created_by_id' in [field.name for field in fields]: schema_editor.remove_field(Unit, Unit._meta.get_field('created_by')) class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0032_qc_tablename'), ] operations = [ migrations.RunPython(conditionally_remove_unit_created_by), ]
965
Python
.py
21
38.47619
80
0.672009
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,334
0046_unit_source_one_to_one.py
translate_pootle/pootle/apps/pootle_store/migrations/0046_unit_source_one_to_one.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-20 22:45 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0045_remove_suggestion_tmp_state'), ] operations = [ migrations.AlterField( model_name='unitsource', name='unit', field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='unit_source', to='pootle_store.Unit'), ), ]
586
Python
.py
16
30.5625
136
0.669027
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,335
0053_remove_unit_submitted.py
translate_pootle/pootle/apps/pootle_store/migrations/0053_remove_unit_submitted.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-23 09:21 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_store', '0052_set_change_submitted'), ] operations = [ migrations.RemoveField( model_name='unit', name='submitted_by', ), migrations.RemoveField( model_name='unit', name='submitted_on', ), migrations.AlterField( model_name='unitchange', name='submitted_by', field=models.ForeignKey(null=True, on_delete=models.SET(pootle.core.user.get_system_user), related_name='submitted', to=settings.AUTH_USER_MODEL), ), ]
847
Python
.py
25
26.44
158
0.629131
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,336
0044_set_new_suggestion_states.py
translate_pootle/pootle/apps/pootle_store/migrations/0044_set_new_suggestion_states.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-28 05:48 from __future__ import unicode_literals from django.db import migrations class OLDSuggestionStates(object): PENDING = 'pending' ACCEPTED = 'accepted' REJECTED = 'rejected' def set_suggestion_states(apps, schema_editor): suggestions = apps.get_model("pootle_store.Suggestion").objects.all() states = apps.get_model("pootle_store.SuggestionState").objects.all() pending = states.get(name="pending") accepted = states.get(name="accepted") rejected = states.get(name="rejected") suggestions.filter(tmp_state=OLDSuggestionStates.PENDING).update(state_id=pending.id) suggestions.filter(tmp_state=OLDSuggestionStates.ACCEPTED).update(state_id=accepted.id) suggestions.filter(tmp_state=OLDSuggestionStates.REJECTED).update(state_id=rejected.id) class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0043_suggestion_state'), ] operations = [ migrations.RunPython(set_suggestion_states), ]
1,058
Python
.py
24
39.541667
91
0.738537
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,337
0031_remove_suggestion_translator_comment_f.py
translate_pootle/pootle/apps/pootle_store/migrations/0031_remove_suggestion_translator_comment_f.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-07-04 07:42 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0030_remove_extra_indeces'), ] operations = [ migrations.RemoveField( model_name='suggestion', name='translator_comment_f', ), ]
418
Python
.py
14
23.928571
54
0.636591
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,338
0011_store_is_template.py
translate_pootle/pootle/apps/pootle_store/migrations/0011_store_is_template.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0010_set_store_filetypes'), ] operations = [ migrations.AddField( model_name='store', name='is_template', field=models.BooleanField(default=False), ), ]
413
Python
.py
14
22.714286
53
0.616751
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,339
0022_add_unique_tp_path_idx.py
translate_pootle/pootle/apps/pootle_store/migrations/0022_add_unique_tp_path_idx.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.10 on 2016-11-04 13:58 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0021_set_tp_path'), ] operations = [ migrations.AlterUniqueTogether( name='store', unique_together=set([('obsolete', 'translation_project', 'tp_path'), ('parent', 'name')]), ), ]
468
Python
.py
14
27.5
102
0.623608
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,340
0032_fix_empty_wordcounts.py
translate_pootle/pootle/apps/pootle_store/migrations/0032_fix_empty_wordcounts.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-07-04 14:04 from __future__ import unicode_literals import logging from django.db import migrations from pootle_data.store_data import StoreDataTool from pootle_data.tp_data import TPDataTool logger = logging.getLogger(__name__) def fix_empty_wordcounts(apps, schema_editor): unit_sources = apps.get_model("pootle_store.UnitSource").objects Store = apps.get_model("pootle_store.Store") TranslationProject = apps.get_model("pootle_translationproject.TranslationProject") unit_sources = unit_sources.filter(source_wordcount=1).filter(unit__source_f__regex="^$") stores = set(unit_sources.values_list("unit__store", flat=True).distinct()) tps = set(unit_sources.values_list("unit__store__translation_project", flat=True).distinct()) unit_sources.update(source_wordcount=0) for store in Store.objects.filter(id__in=stores).iterator(): logger.debug("Updating stats for Store: %s" % store.pootle_path) StoreDataTool(store).update() for tp in TranslationProject.objects.filter(id__in=tps).iterator(): logger.debug("Set stats for TP: %s" % tp.pootle_path) TPDataTool(tp).update() class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0031_remove_suggestion_translator_comment_f'), ('pootle_data', '0007_add_store_and_tp_data_again'), ] operations = [ migrations.RunPython(fix_empty_wordcounts), ]
1,489
Python
.py
30
44.666667
97
0.718923
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,341
0033_remove_store_file.py
translate_pootle/pootle/apps/pootle_store/migrations/0033_remove_store_file.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-08-26 14:01 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pootle_fs', '0002_convert_localfs'), ('pootle_store', '0032_fix_empty_wordcounts'), ] operations = [ migrations.RemoveField( model_name='store', name='file', ), ]
444
Python
.py
15
23.466667
54
0.615566
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,342
0049_remove_unit_commented.py
translate_pootle/pootle/apps/pootle_store/migrations/0049_remove_unit_commented.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-21 14:54 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_store', '0048_set_change_commented'), ] operations = [ migrations.RemoveField( model_name='unit', name='commented_by', ), migrations.RemoveField( model_name='unit', name='commented_on', ), migrations.AlterField( model_name='unitchange', name='commented_by', field=models.ForeignKey(null=True, on_delete=models.SET(pootle.core.user.get_system_user), related_name='commented', to=settings.AUTH_USER_MODEL), ), ]
847
Python
.py
25
26.44
158
0.629131
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,343
0012_set_is_template.py
translate_pootle/pootle/apps/pootle_store/migrations/0012_set_is_template.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import logging from django.db import migrations, models logger = logging.getLogger(__name__) def migrate_store_is_template(apps, schema_editor): tps = apps.get_model("pootle_translationproject.TranslationProject").objects.all() for tp in tps: try: __ = tp.project except apps.get_model("pootle_project.Project").DoesNotExist: logger.warn("TP with missing project '%s', not updating", tp.pootle_path) continue if tp.language == tp.project.source_language or tp.language.code == "templates": tp.stores.update(is_template=True) else: tp.stores.update(is_template=False) class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0011_store_is_template'), ] operations = [ migrations.RunPython(migrate_store_is_template), ]
942
Python
.py
24
32.291667
88
0.664829
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,344
0031_suggestion_tablename.py
translate_pootle/pootle/apps/pootle_store/migrations/0031_suggestion_tablename.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-11 10:23 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0030_store_tablename'), ] operations = [ migrations.AlterModelTable( name='suggestion', table='pootle_store_suggestion', ), ]
415
Python
.py
14
23.714286
49
0.638889
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,345
0003_remove_unit_ordering.py
translate_pootle/pootle/apps/pootle_store/migrations/0003_remove_unit_ordering.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0002_make_suggestion_user_not_null'), ] operations = [ migrations.AlterModelOptions( name='unit', options={'get_latest_by': 'mtime'}, ), ]
387
Python
.py
13
23.461538
63
0.617886
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,346
0030_remove_extra_indeces.py
translate_pootle/pootle/apps/pootle_store/migrations/0030_remove_extra_indeces.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-06-02 15:14 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0029_set_unit_creation_revision'), ] operations = [ migrations.AlterField( model_name='store', name='parent', field=models.ForeignKey(db_index=False, editable=False, on_delete=django.db.models.deletion.CASCADE, related_name='child_stores', to='pootle_app.Directory'), ), migrations.AlterField( model_name='store', name='translation_project', field=models.ForeignKey(db_index=False, editable=False, on_delete=django.db.models.deletion.CASCADE, related_name='stores', to='pootle_translationproject.TranslationProject'), ), migrations.AlterField( model_name='unit', name='store', field=models.ForeignKey(db_index=False, on_delete=django.db.models.deletion.CASCADE, to='pootle_store.Store'), ), migrations.AlterIndexTogether( name='unit', index_together=set([('store', 'revision'), ('store', 'index'), ('store', 'mtime')]), ), ]
1,311
Python
.py
30
35.2
187
0.638715
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,347
0023_add_unit_store_idxs.py
translate_pootle/pootle/apps/pootle_store/migrations/0023_add_unit_store_idxs.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.11 on 2016-11-05 18:12 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0022_add_unique_tp_path_idx'), ] operations = [ migrations.AlterUniqueTogether( name='unit', unique_together=set([('store', 'state', 'index', 'unitid_hash'), ('store', 'unitid_hash')]), ), migrations.AlterIndexTogether( name='store', index_together=set([('translation_project', 'pootle_path', 'is_template', 'filetype'), ('translation_project', 'is_template')]), ), migrations.AlterIndexTogether( name='unit', index_together=set([('store', 'revision'), ('store', 'index'), ('store', 'state'), ('store', 'mtime')]), ), ]
889
Python
.py
22
32.636364
140
0.589327
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,348
0027_unit_created_by_squashed_0055_fill_unit_source_data.py
translate_pootle/pootle/apps/pootle_store/migrations/0027_unit_created_by_squashed_0055_fill_unit_source_data.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-05-09 15:35 from __future__ import unicode_literals import logging import os import django.db.models.deletion from django.conf import settings from django.db import migrations, models import pootle.core.user from pootle.core.batch import Batch from pootle.core.url_helpers import split_pootle_path from pootle.core.user import get_system_user_id from pootle_statistics.models import SubmissionTypes logger = logging.getLogger(__name__) UNIT_CREATE_TYPE = 10 UNIT_SOURCE_SQL = ( "INSERT INTO `pootle_store_unit_source` " " (`unit_id`, `created_with`, `created_by_id`, `source_hash`, `source_length`, `source_wordcount`) " "(SELECT `id` as `unit_id`, " " %s as `created_with`, " " %s as `created_by_id`, " " `source_hash` as `source_hash`," " `source_length` as `source_length`," " `source_wordcount` as `source_wordcount`" " from `pootle_store_unit`)") UNIT_CHANGE_SQL = ( "INSERT INTO `pootle_store_unit_change` " " (`unit_id`, `changed_with`, `commented_on`, `commented_by_id`, `reviewed_on`, `reviewed_by_id`, `submitted_on`, `submitted_by_id`) " " (SELECT `id` as `unit_id`, " " %s as `changed_with`, " " `commented_on` as `commented_on`," " `commented_by_id` as `commented_by_id`," " `reviewed_on` as `reviewed_on`," " `reviewed_by_id` as `reviewed_by_id`," " `submitted_on` as `submitted_on`," " `submitted_by_id` as `submitted_by_id`" " from `pootle_store_unit` " " WHERE " " ((`pootle_store_unit`.`translator_comment` is not NULL " " AND (`commented_on` is not NULL " " OR `commented_by_id` is not NULL)) " " OR (`reviewed_on` is not NULL " " OR `reviewed_by_id` is not NULL) " " OR (`submitted_on` is not NULL " " OR `submitted_by_id` is not NULL)))") UNIT_DELETE_COLS_SQL = ( "ALTER TABLE `pootle_store_unit` %s") REMOVED_UNIT_COLS = [ "source_hash", "source_length", "source_wordcount", "commented_on", "commented_by_id", "reviewed_by_id", "reviewed_on", "submitted_by_id", "submitted_on"] class OLDSuggestionStates(object): PENDING = 'pending' ACCEPTED = 'accepted' REJECTED = 'rejected' def _missing_changes(apps): units = apps.get_model("pootle_store.Unit").objects.all() changeless = units.filter(change__isnull=True) missing_comments = changeless.filter(translator_comment__gt="") missing_comments = ( missing_comments.filter(commented_by_id__isnull=False) | missing_comments.filter(commented_on__isnull=False)) missing_reviews = ( changeless.filter(reviewed_by_id__isnull=False) | changeless.filter(reviewed_on__isnull=False)) missing_submits = ( changeless.filter(submitted_by_id__isnull=False) | changeless.filter(submitted_on__isnull=False)) return (missing_comments | missing_reviews | missing_submits) def create_sources_with_orm(apps, creators): sysuser = get_system_user_id() UnitSource = apps.get_model("pootle_store.UnitSource") units = apps.get_model("pootle_store.Unit").objects.all() _units = list( units.values_list( "id", "source_hash", "source_length", "source_wordcount").iterator()) def _unit_source_create(pk, source_hash, source_length, source_wordcount): return dict( unit_id=pk, source_hash=source_hash, source_wordcount=source_wordcount, source_length=source_length, created_with=SubmissionTypes.WEB, created_by_id=creators.get(pk, sysuser)) Batch(UnitSource.objects, batch_size=500).create( _units, _unit_source_create, reduces=False) def update_sources_with_orm(apps, creators): UnitSource = apps.get_model("pootle_store.UnitSource") def _set_created_by(unit_source): unit_source.created_by_id = creators.get(unit_source.unit_id) return unit_source Batch(UnitSource.objects, batch_size=500).update( list(UnitSource.objects.filter(unit_id__in=creators.keys())), update_method=_set_created_by, update_fields=["created_by"], reduces=False) def create_changes_with_orm(apps): UnitChange = apps.get_model("pootle_store.UnitChange") missing = list( _missing_changes(apps).iterator()) def _unit_change_create(unit): return dict( unit_id=unit.pk, changed_with=SubmissionTypes.WEB, commented_by_id=unit.commented_by_id, commented_on=unit.commented_on, reviewed_by_id=unit.reviewed_by_id, reviewed_on=unit.reviewed_on, submitted_by_id=unit.submitted_by_id, submitted_on=unit.submitted_on) Batch(UnitChange.objects, batch_size=500).create( missing, _unit_change_create, reduces=False) def create_sources_with_sql(schema_editor): sysuser = get_system_user_id() cursor = schema_editor.connection.cursor() cursor.execute(UNIT_SOURCE_SQL % (SubmissionTypes.SYSTEM, sysuser)) def create_changes_with_sql(schema_editor): cursor = schema_editor.connection.cursor() cursor.execute(UNIT_CHANGE_SQL % SubmissionTypes.WEB) def add_unit_sources(apps, schema_editor): subs = apps.get_model("pootle_statistics.Submission").objects.all() sysuser = get_system_user_id() creators = dict( subs.filter(type=UNIT_CREATE_TYPE) .exclude(submitter_id=sysuser) .values_list("unit_id", "submitter")) if schema_editor.connection.vendor == "mysql" and settings.POOTLE_SQL_MIGRATIONS: create_sources_with_sql(schema_editor) update_sources_with_orm(apps, creators) else: create_sources_with_orm(apps, creators) def add_unit_changes(apps, schema_editor): if schema_editor.connection.vendor == "mysql" and settings.POOTLE_SQL_MIGRATIONS: create_changes_with_sql(schema_editor) else: create_changes_with_orm(apps) def convert_unit_source_change(apps, schema_editor): add_unit_sources(apps, schema_editor) add_unit_changes(apps, schema_editor) def add_default_suggestion_states(apps, schema_editor): states = apps.get_model("pootle_store.SuggestionState").objects for state in ["pending", "accepted", "rejected"]: states.create(name=state) def set_suggestion_states(apps, schema_editor): # TODO: add sql path for this update suggestions = apps.get_model("pootle_store.Suggestion").objects.all() states = apps.get_model("pootle_store.SuggestionState").objects.all() pending = states.get(name="pending") accepted = states.get(name="accepted") rejected = states.get(name="rejected") suggestions.filter(tmp_state=OLDSuggestionStates.PENDING).update(state_id=pending.id) suggestions.filter(tmp_state=OLDSuggestionStates.ACCEPTED).update(state_id=accepted.id) suggestions.filter(tmp_state=OLDSuggestionStates.REJECTED).update(state_id=rejected.id) def clean_abs_file_paths(apps, schema_editor): """Replace wrong absolute store file paths by proper relative paths built based on store.pootle_path values. """ store_model = apps.get_model("pootle_store.Store") stores = store_model.objects.filter( translation_project__project__treestyle="nongnu") stores = stores.filter(file__startswith="/").only("file", "pootle_path") to_update = [] for store in stores.iterator(): lang, prj, d, fn = split_pootle_path(store.pootle_path) store.file = os.path.join(prj, lang, d, fn) to_update.append(store) if to_update: result = Batch(store_model, batch_size=500).update( to_update, update_fields=["file"], reduces=False) logger.debug("Cleaned %s store paths" % result) def remove_fields_with_sql(apps, schema_editor): Unit = apps.get_model("pootle_store.Unit") cursor = schema_editor.connection.cursor() for col in REMOVED_UNIT_COLS: field = Unit._meta.get_field(col) if field.remote_field: fk_names = schema_editor._constraint_names( Unit, [field.column], foreign_key=True) for fk_name in fk_names: cursor.execute( schema_editor._delete_constraint_sql( schema_editor.sql_delete_fk, Unit, fk_name)) cursor.execute( UNIT_DELETE_COLS_SQL % (", ".join( [("DROP COLUMN `%s`" % col) for col in REMOVED_UNIT_COLS]))) def remove_fields(apps, schema_editor): if schema_editor.connection.vendor == "mysql" and settings.POOTLE_SQL_MIGRATIONS: remove_fields_with_sql(apps, schema_editor) class RemoveFieldIfExists(migrations.RemoveField): def database_forwards(self, app_label, schema_editor, from_state, to_state): if schema_editor.connection.vendor == "mysql" and settings.POOTLE_SQL_MIGRATIONS: return super(RemoveFieldIfExists, self).database_forwards( app_label, schema_editor, from_state, to_state) class Migration(migrations.Migration): replaces = [ (b'pootle_store', '0027_unit_created_by'), (b'pootle_store', '0028_set_created_by'), (b'pootle_store', '0029_unit_tablename'), (b'pootle_store', '0030_store_tablename'), (b'pootle_store', '0031_suggestion_tablename'), (b'pootle_store', '0032_qc_tablename'), (b'pootle_store', '0033_conditionally_remove_unit_created_by'), (b'pootle_store', '0034_unitsource'), (b'pootle_store', '0035_set_created_by_again'), (b'pootle_store', '0036_unitchange'), (b'pootle_store', '0037_unitsource_fields'), (b'pootle_store', '0038_suggestion_tmp_state'), (b'pootle_store', '0039_set_suggestion_tmp_state'), (b'pootle_store', '0040_remove_suggestion_state'), (b'pootle_store', '0041_suggestionstate'), (b'pootle_store', '0042_add_default_suggestion_states'), (b'pootle_store', '0043_suggestion_state'), (b'pootle_store', '0044_set_new_suggestion_states'), (b'pootle_store', '0045_remove_suggestion_tmp_state'), (b'pootle_store', '0046_unit_source_one_to_one'), (b'pootle_store', '0047_remove_old_unit_fields'), (b'pootle_store', '0048_set_change_commented'), (b'pootle_store', '0049_remove_unit_commented'), (b'pootle_store', '0050_set_change_reviewed'), (b'pootle_store', '0051_remove_unit_reviewed'), (b'pootle_store', '0052_set_change_submitted'), (b'pootle_store', '0053_remove_unit_submitted'), (b'pootle_store', '0054_clean_abs_file_paths'), (b'pootle_store', '0055_fill_unit_source_data')] dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('pootle_store', '0026_suggestion_on_delete_user'), ('pootle_statistics', '0001_initial'), ] operations = [ migrations.AlterModelTable( name='unit', table='pootle_store_unit', ), migrations.AlterModelTable( name='store', table='pootle_store_store', ), migrations.AlterModelTable( name='suggestion', table='pootle_store_suggestion', ), migrations.AlterModelTable( name='qualitycheck', table='pootle_store_qualitycheck', ), migrations.CreateModel( name='UnitSource', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_with', models.IntegerField(db_index=True, default=5)), ('created_by', models.ForeignKey(default=pootle.core.user.get_system_user_id, on_delete=models.SET(pootle.core.user.get_system_user), related_name='created_units', to=settings.AUTH_USER_MODEL)), ('unit', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='unit_source', to='pootle_store.Unit')), ('source_hash', models.CharField(editable=False, max_length=32, null=True)), ('source_length', models.SmallIntegerField(default=0, editable=False)), ('source_wordcount', models.SmallIntegerField(default=0, editable=False)), ], options={ 'abstract': False, 'db_table': 'pootle_store_unit_source', }, ), migrations.CreateModel( name='UnitChange', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('changed_with', models.IntegerField(db_index=True)), ('submitted_on', models.DateTimeField(db_index=True, null=True)), ('commented_on', models.DateTimeField(db_index=True, null=True)), ('reviewed_on', models.DateTimeField(db_index=True, null=True)), ('commented_by', models.ForeignKey(null=True, on_delete=models.SET(pootle.core.user.get_system_user), related_name='units_commented', to=settings.AUTH_USER_MODEL)), ('reviewed_by', models.ForeignKey(null=True, on_delete=models.SET(pootle.core.user.get_system_user), related_name='units_reviewed', to=settings.AUTH_USER_MODEL)), ('submitted_by', models.ForeignKey(null=True, on_delete=models.SET(pootle.core.user.get_system_user), related_name='units_submitted', to=settings.AUTH_USER_MODEL)), ('unit', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='change', to='pootle_store.Unit')), ], options={ 'abstract': False, 'db_table': 'pootle_store_unit_change', }, ), migrations.RunPython(convert_unit_source_change), migrations.RunPython( remove_fields, ), RemoveFieldIfExists( model_name='unit', name='source_hash', ), RemoveFieldIfExists( model_name='unit', name='source_length', ), RemoveFieldIfExists( model_name='unit', name='source_wordcount', ), RemoveFieldIfExists( model_name='unit', name='commented_by', ), RemoveFieldIfExists( model_name='unit', name='commented_on', ), RemoveFieldIfExists( model_name='unit', name='reviewed_by', ), RemoveFieldIfExists( model_name='unit', name='reviewed_on', ), RemoveFieldIfExists( model_name='unit', name='submitted_by', ), RemoveFieldIfExists( model_name='unit', name='submitted_on', ), migrations.AlterField( model_name='unitchange', name='commented_by', field=models.ForeignKey(null=True, on_delete=models.SET(pootle.core.user.get_system_user), related_name='commented', to=settings.AUTH_USER_MODEL), ), migrations.AlterField( model_name='unitchange', name='reviewed_by', field=models.ForeignKey(null=True, on_delete=models.SET(pootle.core.user.get_system_user), related_name='reviewed', to=settings.AUTH_USER_MODEL), ), migrations.AlterField( model_name='unitchange', name='submitted_by', field=models.ForeignKey(null=True, on_delete=models.SET(pootle.core.user.get_system_user), related_name='submitted', to=settings.AUTH_USER_MODEL), ), migrations.CreateModel( name='SuggestionState', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(db_index=True, max_length=16)), ], options={ 'abstract': False, 'db_table': 'pootle_store_suggestion_state', }, ), migrations.RunPython(add_default_suggestion_states), migrations.RenameField( model_name='suggestion', old_name="state", new_name="tmp_state"), migrations.AddField( model_name='suggestion', name='state', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='suggestions', to='pootle_store.SuggestionState'), ), migrations.RunPython(set_suggestion_states), migrations.RemoveField( model_name='suggestion', name='tmp_state', ), migrations.RunPython(clean_abs_file_paths)]
16,954
Python
.py
380
35.792105
210
0.629948
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,349
0001_initial.py
translate_pootle/pootle/apps/pootle_store/migrations/0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import datetime from django.utils.timezone import utc import translate.storage.base import pootle_store.fields import pootle.core.mixins.treeitem from django.conf import settings import django.db.models.fields.files class Migration(migrations.Migration): dependencies = [ ('pootle_translationproject', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('pootle_app', '0001_initial'), ] operations = [ migrations.CreateModel( name='Store', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('file', django.db.models.fields.files.FileField(upload_to='', max_length=255, editable=False, db_index=True)), ('pootle_path', models.CharField(unique=True, max_length=255, verbose_name='Path', db_index=True)), ('name', models.CharField(max_length=128, editable=False)), ('file_mtime', models.DateTimeField(default=datetime.datetime(1, 1, 1, 0, 0, tzinfo=utc))), ('state', models.IntegerField(default=0, editable=False, db_index=True)), ('creation_time', models.DateTimeField(db_index=True, auto_now_add=True, null=True)), ('last_sync_revision', models.IntegerField(null=True, db_index=True)), ('obsolete', models.BooleanField(default=False)), ('parent', models.ForeignKey(related_name='child_stores', editable=False, to='pootle_app.Directory', on_delete=models.CASCADE)), ('translation_project', models.ForeignKey(related_name='stores', editable=False, to='pootle_translationproject.TranslationProject', on_delete=models.CASCADE)), ], options={ 'ordering': ['pootle_path'], }, bases=(models.Model, pootle.core.mixins.treeitem.CachedTreeItem, translate.storage.base.TranslationStore), ), migrations.CreateModel( name='Unit', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('index', models.IntegerField(db_index=True)), ('unitid', models.TextField(editable=False)), ('unitid_hash', models.CharField(max_length=32, editable=False, db_index=True)), ('source_f', pootle_store.fields.MultiStringField(null=True)), ('source_hash', models.CharField(max_length=32, editable=False, db_index=True)), ('source_wordcount', models.SmallIntegerField(default=0, editable=False)), ('source_length', models.SmallIntegerField(default=0, editable=False, db_index=True)), ('target_f', pootle_store.fields.MultiStringField(null=True, blank=True)), ('target_wordcount', models.SmallIntegerField(default=0, editable=False)), ('target_length', models.SmallIntegerField(default=0, editable=False, db_index=True)), ('developer_comment', models.TextField(null=True, blank=True)), ('translator_comment', models.TextField(null=True, blank=True)), ('locations', models.TextField(null=True, editable=False)), ('context', models.TextField(null=True, editable=False)), ('state', models.IntegerField(default=0, db_index=True)), ('revision', models.IntegerField(default=0, db_index=True, blank=True)), ('creation_time', models.DateTimeField(db_index=True, auto_now_add=True, null=True)), ('mtime', models.DateTimeField(auto_now=True, auto_now_add=True, db_index=True)), ('submitted_on', models.DateTimeField(null=True, db_index=True)), ('commented_on', models.DateTimeField(null=True, db_index=True)), ('reviewed_on', models.DateTimeField(null=True, db_index=True)), ('commented_by', models.ForeignKey(related_name='commented', to=settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)), ('reviewed_by', models.ForeignKey(related_name='reviewed', to=settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)), ('store', models.ForeignKey(to='pootle_store.Store', on_delete=models.CASCADE)), ('submitted_by', models.ForeignKey(related_name='submitted', to=settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)), ], options={ 'ordering': ['store', 'index'], 'get_latest_by': 'mtime', }, bases=(models.Model, translate.storage.base.TranslationUnit), ), migrations.CreateModel( name='Suggestion', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('target_f', pootle_store.fields.MultiStringField()), ('target_hash', models.CharField(max_length=32, db_index=True)), ('translator_comment_f', models.TextField(null=True, blank=True)), ('state', models.CharField(default='pending', max_length=16, db_index=True, choices=[('pending', 'Pending'), ('accepted', 'Accepted'), ('rejected', 'Rejected')])), ('creation_time', models.DateTimeField(null=True, db_index=True)), ('review_time', models.DateTimeField(null=True, db_index=True)), ('unit', models.ForeignKey(to='pootle_store.Unit', on_delete=models.CASCADE)), ('reviewer', models.ForeignKey(related_name='reviews', to=settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)), ('user', models.ForeignKey(related_name='suggestions', to=settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)), ], options={ }, bases=(models.Model, translate.storage.base.TranslationUnit), ), migrations.CreateModel( name='QualityCheck', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=64, db_index=True)), ('category', models.IntegerField(default=0)), ('message', models.TextField()), ('false_positive', models.BooleanField(default=False, db_index=True)), ('unit', models.ForeignKey(to='pootle_store.Unit', on_delete=models.CASCADE)), ], options={ }, bases=(models.Model,), ), migrations.AlterUniqueTogether( name='unit', unique_together=set([('store', 'unitid_hash')]), ), migrations.AlterUniqueTogether( name='store', unique_together=set([('parent', 'name')]), ), ]
7,063
Python
.py
114
48.903509
179
0.610543
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,350
0029_set_unit_creation_revision.py
translate_pootle/pootle/apps/pootle_store/migrations/0029_set_unit_creation_revision.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-05-23 10:20 from __future__ import unicode_literals import logging from django.conf import settings from django.db import migrations from pootle.core.batch import Batch from pootle_store.constants import OBSOLETE logger = logging.getLogger(__name__) SET_CREATION_REVISION_SQL = ( "UPDATE `pootle_store_unit_source` " " JOIN `pootle_store_unit` " " ON `pootle_store_unit`.`id` = `pootle_store_unit_source`.`unit_id` " " LEFT JOIN `pootle_store_unit_change` " " ON `pootle_store_unit`.`id` = `pootle_store_unit_change`.`unit_id` " " LEFT JOIN `pootle_app_submission` " " ON `pootle_store_unit`.`id` = `pootle_app_submission`.`unit_id` " " SET `pootle_store_unit_source`.`creation_revision` = `pootle_store_unit`.`revision` " " WHERE `pootle_app_submission`.`id` IS NULL " " AND `pootle_store_unit_change`.id IS NULL " " AND `pootle_store_unit`.`state` >= 0 " " AND `pootle_store_unit`.`revision` > 0") def set_creation_revisions_with_sql(apps, schema_editor): cursor = schema_editor.connection.cursor() result = cursor.execute(SET_CREATION_REVISION_SQL) logger.debug("Updated %s for unit_source.creation_revision" % result) def set_creation_revisions_with_orm(apps, schema_editor): UnitSource = apps.get_model("pootle_store.UnitSource") no_change = UnitSource.objects.filter(unit__submission__isnull=True).filter(unit__change__isnull=True) no_change = no_change.exclude(unit__state=OBSOLETE).filter(unit__revision__gt=0) no_change = list(no_change.select_related("unit").only("unit__revision")) def _set_creation_revision(unit_source): unit_source.creation_revision = unit_source.unit.revision return unit_source Batch(UnitSource.objects, batch_size=1000).update( no_change, update_method=_set_creation_revision, update_fields=["creation_revision"], reduces=False) def set_creation_revisions(apps, schema_editor): if schema_editor.connection.vendor == "mysql" and settings.POOTLE_SQL_MIGRATIONS: set_creation_revisions_with_sql(apps, schema_editor) else: set_creation_revisions_with_orm(apps, schema_editor) class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0028_unitsource_creation_revision'), ] operations = [ migrations.RunPython(set_creation_revisions), ]
2,476
Python
.py
51
43.509804
106
0.69838
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,351
0008_flush_django_cache.py
translate_pootle/pootle/apps/pootle_store/migrations/0008_flush_django_cache.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.core.management import call_command from django.db import migrations def flush_django_cache(apps, schema_editor): call_command('flush_cache', '--django-cache') class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0007_case_sensitive_schema'), ] operations = [ migrations.RunPython(flush_django_cache), ]
444
Python
.py
13
29.846154
55
0.709906
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,352
0045_remove_suggestion_tmp_state.py
translate_pootle/pootle/apps/pootle_store/migrations/0045_remove_suggestion_tmp_state.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-28 05:54 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0044_set_new_suggestion_states'), ] operations = [ migrations.RemoveField( model_name='suggestion', name='tmp_state', ), ]
412
Python
.py
14
23.5
59
0.631043
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,353
0028_unitsource_creation_revision.py
translate_pootle/pootle/apps/pootle_store/migrations/0028_unitsource_creation_revision.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-05-23 09:15 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0027_unit_created_by_squashed_0055_fill_unit_source_data'), ] operations = [ migrations.AddField( model_name='unitsource', name='creation_revision', field=models.IntegerField(blank=True, db_index=True, default=0), ), ]
528
Python
.py
15
28.8
85
0.651575
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,354
0034_unitsource.py
translate_pootle/pootle/apps/pootle_store/migrations/0034_unitsource.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-17 14:22 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import pootle.core.user class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('pootle_store', '0033_conditionally_remove_unit_created_by'), ] operations = [ migrations.CreateModel( name='UnitSource', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_with', models.IntegerField(db_index=True, default=5)), ('created_by', models.ForeignKey(default=pootle.core.user.get_system_user_id, on_delete=models.SET(pootle.core.user.get_system_user), related_name='created_units', to=settings.AUTH_USER_MODEL)), ('unit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='unit_source', to='pootle_store.Unit', unique=True)), ], options={ 'abstract': False, 'db_table': 'pootle_store_unit_source', }, ), ]
1,278
Python
.py
27
38.592593
210
0.645265
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,355
0052_set_change_submitted.py
translate_pootle/pootle/apps/pootle_store/migrations/0052_set_change_submitted.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-22 13:43 from __future__ import unicode_literals import logging import time from django.db import migrations from pootle.core.batch import Batch from pootle.core.user import get_system_user_id from pootle_statistics.models import SubmissionTypes logger = logging.getLogger(__name__) def _update_submitted(qs, unit_changes): values = qs.values_list("change", "submitted_on", "submitted_by") for change, submitted_on, submitted_by in values.iterator(): unit_changes.filter(pk=change).update( submitted_on=submitted_on, submitted_by=submitted_by) def _add_submitted(qs, unit_changes): values = qs.values_list("id", "submitted_on", "submitted_by") def _create_method(unit, timestamp, user): return dict( unit_id=unit, changed_with=( SubmissionTypes.SYSTEM if user == get_system_user_id() else SubmissionTypes.WEB), submitted_by_id=user, submitted_on=timestamp) Batch(unit_changes).create(values, _create_method) def set_change_submitted(apps, schema_editor): units = apps.get_model("pootle_store.Unit").objects.all() unit_changes = apps.get_model("pootle_store.UnitChange").objects.all() units_with_submitter = units.filter( submitted_by__isnull=False).filter(submitted_on__isnull=False) _update_submitted( units_with_submitter.filter(change__isnull=False), unit_changes) _add_submitted( units_with_submitter.filter(change__isnull=True), unit_changes) class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0051_remove_unit_reviewed'), ] operations = [ migrations.RunPython(set_change_submitted), ]
1,841
Python
.py
46
33.304348
74
0.679213
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,356
0029_unit_tablename.py
translate_pootle/pootle/apps/pootle_store/migrations/0029_unit_tablename.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-10 17:42 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0028_set_created_by'), ] operations = [ migrations.AlterModelTable( name='unit', table='pootle_store_unit', ), ]
402
Python
.py
14
22.785714
48
0.624021
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,357
0041_suggestionstate.py
translate_pootle/pootle/apps/pootle_store/migrations/0041_suggestionstate.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-28 05:39 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0040_remove_suggestion_state'), ] operations = [ migrations.CreateModel( name='SuggestionState', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(db_index=True, max_length=16)), ], options={ 'abstract': False, 'db_table': 'pootle_store_suggestion_state', }, ), ]
745
Python
.py
21
26.428571
114
0.5758
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,358
0021_set_tp_path.py
translate_pootle/pootle/apps/pootle_store/migrations/0021_set_tp_path.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.10 on 2016-11-02 19:42 from __future__ import unicode_literals from django.db import migrations def set_store_tp_path(apps, schema_editor): stores = apps.get_model("pootle_store.Store").objects.all() for store in stores: parts = store.pootle_path.lstrip("/").split("/") store.tp_path = '/'.join([""] + parts[2:]) store.save() class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0020_store_tp_path'), ] operations = [ migrations.RunPython(set_store_tp_path), ]
603
Python
.py
17
30.294118
63
0.642487
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,359
0005_unit_priority.py
translate_pootle/pootle/apps/pootle_store/migrations/0005_unit_priority.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.core.validators class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0004_index_store_index_together'), ] operations = [ migrations.AddField( model_name='unit', name='priority', field=models.FloatField(default=1, db_index=True, validators=[django.core.validators.MinValueValidator(0)]), preserve_default=True, ), ]
548
Python
.py
16
27.4375
120
0.652751
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,360
0016_blank_last_sync_revision.py
translate_pootle/pootle/apps/pootle_store/migrations/0016_blank_last_sync_revision.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0015_add_slashes_validator_for_name'), ] operations = [ migrations.AlterField( model_name='store', name='last_sync_revision', field=models.IntegerField(db_index=True, null=True, blank=True), ), ]
456
Python
.py
14
25.785714
76
0.631579
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,361
0010_set_store_filetypes.py
translate_pootle/pootle/apps/pootle_store/migrations/0010_set_store_filetypes.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import logging from django.db import migrations, models from pootle.core.delegate import formats logger = logging.getLogger(__name__) def migrate_store_filetypes(apps, schema_editor): format_registry = formats.get() projects = apps.get_model("pootle_project.Project").objects.all() stores = apps.get_model("pootle_store.Store").objects.all() filetypes = apps.get_model("pootle_format.Format").objects.all() for project in projects: for filetype in project.filetypes.all(): stores = ( stores.filter(translation_project__project=project) .filter(filetype__isnull=True) .filter(name__endswith=".%s" % filetype.extension)) stores.update(filetype=filetype) class Migration(migrations.Migration): dependencies = [ ('pootle_translationproject', '0003_realpath_can_be_none'), ('pootle_project', '0007_migrate_localfiletype'), ('pootle_store', '0009_store_filetype'), ] operations = [ migrations.RunPython(migrate_store_filetypes), ]
1,162
Python
.py
27
35.62963
73
0.66934
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,362
0015_add_slashes_validator_for_name.py
translate_pootle/pootle/apps/pootle_store/migrations/0015_add_slashes_validator_for_name.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import pootle_store.validators class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0014_add_unit_index_togethers'), ] operations = [ migrations.AlterField( model_name='store', name='name', field=models.CharField(max_length=128, editable=False, validators=[pootle_store.validators.validate_no_slashes]), ), ]
516
Python
.py
15
28
125
0.66129
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,363
0002_make_suggestion_user_not_null.py
translate_pootle/pootle/apps/pootle_store/migrations/0002_make_suggestion_user_not_null.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_store', '0001_initial'), ] operations = [ migrations.AlterField( model_name='suggestion', name='user', field=models.ForeignKey(related_name='suggestions', to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE), preserve_default=True, ), ]
535
Python
.py
16
26.625
119
0.64786
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,364
0050_set_change_reviewed.py
translate_pootle/pootle/apps/pootle_store/migrations/0050_set_change_reviewed.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-21 19:06 from __future__ import unicode_literals from django.db import migrations from pootle.core.batch import Batch from pootle.core.user import get_system_user_id from pootle_statistics.models import SubmissionTypes def _update_reviewed(qs, unit_changes): values = qs.values_list("change", "reviewed_on", "reviewed_by") for change, reviewed_on, reviewed_by in values.iterator(): unit_changes.filter(pk=change).update( reviewed_on=reviewed_on, reviewed_by=reviewed_by) def _add_reviewed(qs, unit_changes): values = qs.values_list("id", "reviewed_on", "reviewed_by") def _create_method(unit, timestamp, user): return dict( unit_id=unit, changed_with=( SubmissionTypes.SYSTEM if user == get_system_user_id() else SubmissionTypes.WEB), reviewed_by_id=user, reviewed_on=timestamp) Batch(unit_changes).create(values, _create_method) def set_change_reviewed(apps, schema_editor): units = apps.get_model("pootle_store.Unit").objects.all() unit_changes = apps.get_model("pootle_store.UnitChange").objects.all() _update_reviewed( units.filter( change__isnull=False).filter(reviewed_by__isnull=False), unit_changes) _add_reviewed( units.filter( change__isnull=True).filter(reviewed_by__isnull=False), unit_changes) class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0049_remove_unit_commented'), ] operations = [ migrations.RunPython(set_change_reviewed), ]
1,710
Python
.py
43
32.418605
74
0.660218
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,365
0032_qc_tablename.py
translate_pootle/pootle/apps/pootle_store/migrations/0032_qc_tablename.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-11 10:51 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0031_suggestion_tablename'), ] operations = [ migrations.AlterModelTable( name='qualitycheck', table='pootle_store_qualitycheck', ), ]
424
Python
.py
14
24.357143
54
0.646914
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,366
0051_remove_unit_reviewed.py
translate_pootle/pootle/apps/pootle_store/migrations/0051_remove_unit_reviewed.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-21 19:58 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_store', '0050_set_change_reviewed'), ] operations = [ migrations.RemoveField( model_name='unit', name='reviewed_by', ), migrations.RemoveField( model_name='unit', name='reviewed_on', ), migrations.AlterField( model_name='unitchange', name='reviewed_by', field=models.ForeignKey(null=True, on_delete=models.SET(pootle.core.user.get_system_user), related_name='reviewed', to=settings.AUTH_USER_MODEL), ), ]
842
Python
.py
25
26.24
157
0.626847
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,367
0054_clean_abs_file_paths.py
translate_pootle/pootle/apps/pootle_store/migrations/0054_clean_abs_file_paths.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-04-25 12:59 from __future__ import unicode_literals import os from django.db import migrations from bulk_update.helper import bulk_update from pootle.core.url_helpers import split_pootle_path def clean_abs_file_paths(apps, schema_editor): """Replace wrong absolute store file paths by proper relative paths built based on store.pootle_path values. """ store_model = apps.get_model("pootle_store.Store") store_qs = store_model.objects.select_related("filetype") for project in apps.get_model("pootle_project.Project").objects.all(): if not project.treestyle == 'nongnu': continue stores = list(store_qs.filter( translation_project__project_id=project.id, file__startswith="/")) for store in stores: lang, prj, d, fn = split_pootle_path(store.pootle_path) store.file = os.path.join(prj, lang, d, fn) bulk_update(stores, update_fields=["file"]) class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0053_remove_unit_submitted'), ] operations = [ migrations.RunPython(clean_abs_file_paths), ]
1,227
Python
.py
30
34.666667
74
0.677338
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,368
0026_suggestion_on_delete_user.py
translate_pootle/pootle/apps/pootle_store/migrations/0026_suggestion_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_store', '0025_unit_on_delete_user'), ] operations = [ migrations.AlterField( model_name='suggestion', name='reviewer', field=models.ForeignKey(null=True, on_delete=models.SET(pootle.core.user.get_system_user), related_name='reviews', to=settings.AUTH_USER_MODEL), ), migrations.AlterField( model_name='suggestion', name='user', field=models.ForeignKey(on_delete=models.SET(pootle.core.user.get_system_user), related_name='suggestions', to=settings.AUTH_USER_MODEL), ), ]
880
Python
.py
22
32.954545
156
0.66354
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,369
0036_unitchange.py
translate_pootle/pootle/apps/pootle_store/migrations/0036_unitchange.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-19 13:38 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import pootle.core.user class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('pootle_store', '0035_set_created_by_again'), ] operations = [ migrations.CreateModel( name='UnitChange', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('changed_with', models.IntegerField(db_index=True)), ('submitted_on', models.DateTimeField(db_index=True, null=True)), ('commented_on', models.DateTimeField(db_index=True, null=True)), ('reviewed_on', models.DateTimeField(db_index=True, null=True)), ('commented_by', models.ForeignKey(null=True, on_delete=models.SET(pootle.core.user.get_system_user), related_name='units_commented', to=settings.AUTH_USER_MODEL)), ('reviewed_by', models.ForeignKey(null=True, on_delete=models.SET(pootle.core.user.get_system_user), related_name='units_reviewed', to=settings.AUTH_USER_MODEL)), ('submitted_by', models.ForeignKey(null=True, on_delete=models.SET(pootle.core.user.get_system_user), related_name='units_submitted', to=settings.AUTH_USER_MODEL)), ], options={ 'abstract': False, 'db_table': 'pootle_store_unit_change', }, ), migrations.AddField( model_name='unitchange', name='unit', field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='change', to='pootle_store.Unit'), ), ]
1,905
Python
.py
36
42.888889
180
0.638412
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,370
0043_suggestion_state.py
translate_pootle/pootle/apps/pootle_store/migrations/0043_suggestion_state.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-28 05:45 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0042_add_default_suggestion_states'), ] operations = [ migrations.AddField( model_name='suggestion', name='state', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='suggestions', to='pootle_store.SuggestionState'), ), ]
607
Python
.py
16
31.875
156
0.675768
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,371
0042_add_default_suggestion_states.py
translate_pootle/pootle/apps/pootle_store/migrations/0042_add_default_suggestion_states.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-28 05:40 from __future__ import unicode_literals from django.db import migrations def add_default_suggestion_states(apps, schema_editor): states = apps.get_model("pootle_store.SuggestionState").objects for state in ["pending", "accepted", "rejected"]: states.create(name=state) class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0041_suggestionstate'), ] operations = [ migrations.RunPython(add_default_suggestion_states), ]
567
Python
.py
15
33.133333
67
0.704587
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,372
0014_add_unit_index_togethers.py
translate_pootle/pootle/apps/pootle_store/migrations/0014_add_unit_index_togethers.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0013_set_store_filetype_again'), ] operations = [ migrations.AlterIndexTogether( name='unit', index_together=set([('store', 'revision'), ('store', 'index'), ('store', 'mtime')]), ), ]
432
Python
.py
13
26.923077
96
0.60628
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,373
0013_set_store_filetype_again.py
translate_pootle/pootle/apps/pootle_store/migrations/0013_set_store_filetype_again.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import logging from django.db import migrations, models logger = logging.getLogger(__name__) def migrate_store_filetypes(apps, schema_editor): projects = apps.get_model("pootle_project.Project").objects.all() for project in projects: for filetype in project.filetypes.all(): (apps.get_model("pootle_store.Store").objects.all() .filter(translation_project__project=project) .filter(name__endswith=".%s" % filetype.extension.name) .update(filetype=filetype)) if filetype.extension != filetype.template_extension: (apps.get_model("pootle_store.Store").objects.all() .filter(translation_project__project=project) .filter(name__endswith=".%s" % filetype.template_extension.name) .update(filetype=filetype)) class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0012_set_is_template'), ] operations = [ migrations.RunPython(migrate_store_filetypes), ]
1,143
Python
.py
25
36.2
85
0.638663
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,374
0007_case_sensitive_schema.py
translate_pootle/pootle/apps/pootle_store/migrations/0007_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_store_paths_cs(apps, schema_editor): cursor = schema_editor.connection.cursor() set_mysql_collation_for_column( apps, cursor, "pootle_store.Store", "pootle_path", "utf8_bin", "varchar(255)") set_mysql_collation_for_column( apps, cursor, "pootle_store.Store", "name", "utf8_bin", "varchar(255)") class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0006_remove_auto_now_add'), ] operations = [ migrations.RunPython(make_store_paths_cs), ]
785
Python
.py
27
22.592593
63
0.626667
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,375
0037_unitsource_fields.py
translate_pootle/pootle/apps/pootle_store/migrations/0037_unitsource_fields.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-19 22:51 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0036_unitchange'), ] operations = [ migrations.AddField( model_name='unitsource', name='source_hash', field=models.CharField(editable=False, max_length=32, null=True), ), migrations.AddField( model_name='unitsource', name='source_length', field=models.SmallIntegerField(default=0, editable=False), ), migrations.AddField( model_name='unitsource', name='source_wordcount', field=models.SmallIntegerField(default=0, editable=False), ), ]
849
Python
.py
25
25.56
77
0.610501
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,376
0027_unit_created_by.py
translate_pootle/pootle/apps/pootle_store/migrations/0027_unit_created_by.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-02 21:45 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_store', '0026_suggestion_on_delete_user'), ] operations = [ ]
434
Python
.py
13
29.538462
66
0.721154
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,377
0009_store_filetype.py
translate_pootle/pootle/apps/pootle_store/migrations/0009_store_filetype.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pootle_format', '0002_default_formats'), ('pootle_store', '0008_flush_django_cache'), ] operations = [ migrations.AddField( model_name='store', name='filetype', field=models.ForeignKey(related_name='stores', blank=True, to='pootle_format.Format', null=True, on_delete=models.CASCADE), ), ]
542
Python
.py
15
29.2
135
0.6341
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,378
0025_unit_on_delete_user.py
translate_pootle/pootle/apps/pootle_store/migrations/0025_unit_on_delete_user.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-02 14:03 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_store', '0024_set_store_base_manager_name'), ] operations = [ migrations.AlterField( model_name='unit', name='commented_by', field=models.ForeignKey(null=True, on_delete=models.SET(pootle.core.user.get_system_user), related_name='commented', to=settings.AUTH_USER_MODEL), ), migrations.AlterField( model_name='unit', name='reviewed_by', field=models.ForeignKey(null=True, on_delete=models.SET(pootle.core.user.get_system_user), related_name='reviewed', to=settings.AUTH_USER_MODEL), ), migrations.AlterField( model_name='unit', name='submitted_by', field=models.ForeignKey(null=True, on_delete=models.SET(pootle.core.user.get_system_user), related_name='submitted', to=settings.AUTH_USER_MODEL), ), ]
1,163
Python
.py
27
35.185185
158
0.655752
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,379
deserialize.py
translate_pootle/pootle/apps/pootle_store/store/deserialize.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 io from translate.storage.factory import getclass from django.utils.functional import cached_property from pootle.core.delegate import config, deserializers class StoreDeserialization(object): """Calls configured deserializers for Store""" def __init__(self, store): self.store = store @property def project_deserializers(self): project = self.store.translation_project.project return ( config.get( project.__class__, instance=project, key="pootle.core.deserializers") or []) @cached_property def deserializers(self): available_deserializers = deserializers.gather( self.store.translation_project.project.__class__) found_deserializers = [] for deserializer in self.project_deserializers: found_deserializers.append(available_deserializers[deserializer]) return found_deserializers def pipeline(self, data): if not self.deserializers: return data for deserializer in self.deserializers: data = deserializer(self.store, data).output return data def dataio(self, data): data = io.BytesIO(data) data.name = self.store.name return data def fromstring(self, data): data = self.dataio(data) return getclass(data)(data) def deserialize(self, data): return self.fromstring(self.pipeline(data))
1,769
Python
.py
47
30.234043
77
0.675834
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,380
serialize.py
translate_pootle/pootle/apps/pootle_store/store/serialize.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.utils.functional import cached_property from pootle.core.delegate import config, serializers class StoreSerialization(object): """Calls configured deserializers for Store""" def __init__(self, store): self.store = store @cached_property def project_serializers(self): project = self.store.translation_project.project return ( config.get( project.__class__, instance=project, key="pootle.core.serializers") or []) @property def pootle_path(self): return self.store.pootle_path @cached_property def max_unit_revision(self): return self.store.data.max_unit_revision @cached_property def serializers(self): available_serializers = serializers.gather( self.store.translation_project.project.__class__) if not available_serializers.keys(): return [] found_serializers = [] for serializer in self.project_serializers: found_serializers.append(available_serializers[serializer]) return found_serializers def tostring(self, include_obsolete=False, raw=False): store = self.store.syncer.convert( include_obsolete=include_obsolete, raw=raw) if hasattr(store, "updateheader"): # FIXME We need those headers on import # However some formats just don't support setting metadata max_unit_revision = self.max_unit_revision or 0 store.updateheader(add=True, X_Pootle_Path=self.pootle_path) store.updateheader(add=True, X_Pootle_Revision=max_unit_revision) return str(store) def pipeline(self, data): if not self.serializers: return data for serializer in self.serializers: data = serializer(self.store, data).output return data def serialize(self, include_obsolete=False, raw=False): return self.pipeline( self.tostring(include_obsolete=include_obsolete, raw=raw))
2,351
Python
.py
57
32.947368
77
0.666959
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,381
util.py
translate_pootle/pootle/apps/pootle_misc/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 datetime import datetime, timedelta from functools import wraps from importlib import import_module from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.http import HttpResponseBadRequest from django.utils import timezone def import_func(path): i = path.rfind('.') module, attr = path[:i], path[i+1:] try: mod = import_module(module) except ImportError as e: raise ImproperlyConfigured('Error importing module %s: "%s"' % (module, e)) try: func = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured( 'Module "%s" does not define a "%s" callable function' % (module, attr)) return func def ajax_required(f): """Check that the request is an AJAX request. Use it in your views: @ajax_required def my_view(request): .... Taken from: http://djangosnippets.org/snippets/771/ """ @wraps(f) def wrapper(request, *args, **kwargs): if not settings.DEBUG and not request.is_ajax(): return HttpResponseBadRequest("This must be an AJAX request.") return f(request, *args, **kwargs) return wrapper def get_max_month_datetime(dt): next_month = dt.replace(day=1) + timedelta(days=31) if settings.USE_TZ: tz = timezone.get_default_timezone() next_month = timezone.localtime(next_month, tz) return next_month.replace(day=1, hour=0, minute=0, second=0) - \ timedelta(microseconds=1) def get_date_interval(month): from pootle.core.utils.timezone import make_aware now = start = end = timezone.now() default_month = start.strftime('%Y-%m') if month is None: month = default_month try: month_datetime = datetime.strptime(month, '%Y-%m') except ValueError: month_datetime = datetime.strptime(default_month, '%Y-%m') start = make_aware(month_datetime) if start < now: if start.month != now.month or start.year != now.year: end = get_max_month_datetime(start) else: end = start start = start.replace(hour=0, minute=0, second=0) end = end.replace(hour=23, minute=59, second=59, microsecond=999999) return [start, end] def cmp_by_last_activity(x, y): val_x = 0 val_y = 0 if 'stats' in x and 'last_submission' in x['stats']: val_x = x['stats']['last_submission']['mtime'] if 'stats' in y and 'last_submission' in y['stats']: val_y = y['stats']['last_submission']['mtime'] return cmp(val_y, val_x)
2,906
Python
.py
78
31.230769
77
0.658937
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,382
context_processors.py
translate_pootle/pootle/apps/pootle_misc/context_processors.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 pootle.core.markup import get_markup_filter_name from pootle_project.models import Project from staticpages.models import LegalPage def _agreement_context(request): """Returns whether the agreement box should be displayed or not.""" request_path = request.META['PATH_INFO'] nocheck = filter(lambda x: request_path.startswith(x), settings.POOTLE_LEGALPAGE_NOCHECK_PREFIXES) if (request.user.is_authenticated and not nocheck and LegalPage.objects.has_pending_agreement(request.user)): return True return False def _get_social_auth_providers(request): if 'allauth.socialaccount' not in settings.INSTALLED_APPS: return [] from allauth.socialaccount import providers return [{'name': provider.name, 'url': provider.get_login_url(request)} for provider in providers.registry.get_list()] def pootle_context(request): """Exposes settings to templates.""" # FIXME: maybe we should expose relevant settings only? return { 'settings': { 'POOTLE_CUSTOM_LOGO': getattr(settings, "POOTLE_CUSTOM_LOGO", ""), 'POOTLE_TITLE': settings.POOTLE_TITLE, 'POOTLE_FAVICONS_PATH': settings.POOTLE_FAVICONS_PATH, 'POOTLE_INSTANCE_ID': settings.POOTLE_INSTANCE_ID, 'POOTLE_CONTACT_ENABLED': (settings.POOTLE_CONTACT_ENABLED and settings.POOTLE_CONTACT_EMAIL), 'POOTLE_MARKUP_FILTER': get_markup_filter_name(), 'POOTLE_SIGNUP_ENABLED': settings.POOTLE_SIGNUP_ENABLED, 'SCRIPT_NAME': settings.SCRIPT_NAME, 'POOTLE_CACHE_TIMEOUT': settings.POOTLE_CACHE_TIMEOUT, 'DEBUG': settings.DEBUG, }, 'custom': settings.POOTLE_CUSTOM_TEMPLATE_CONTEXT, 'ALL_PROJECTS': Project.objects.cached_dict(request.user), 'SOCIAL_AUTH_PROVIDERS': _get_social_auth_providers(request), 'display_agreement': _agreement_context(request), }
2,321
Python
.py
48
40.604167
78
0.685537
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,383
baseurl.py
translate_pootle/pootle/apps/pootle_misc/baseurl.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. """Utility functions to help deploy Pootle under different url prefixes.""" from django.conf import settings def link(path): """Filter URLs adding base_path prefix if required.""" if path and path.startswith('/'): base_url = getattr(settings, "SCRIPT_NAME", "") return base_url + path return path
604
Python
.py
15
37.133333
77
0.721368
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,384
forms.py
translate_pootle/pootle/apps/pootle_misc/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. from django import forms from django.core.validators import EMPTY_VALUES from django.forms.models import ModelChoiceIterator from pootle.i18n.gettext import ugettext_lazy as _ class GroupedModelChoiceIterator(ModelChoiceIterator): def __init__(self, field): self.field = field self.choice_groups = field.choice_groups def __iter__(self): if self.field.empty_label is not None: yield (u'', self.field.empty_label) for title, queryset in self.choice_groups: if title is not None: yield (title, [self.choice(choice) for choice in queryset]) else: for choice in queryset: yield self.choice(choice) class GroupedModelChoiceField(forms.ModelChoiceField): """A `ModelChoiceField` with grouping capabilities. :param choice_groups: List of tuples including the `title` and `queryset` of each individual choice group. """ def __init__(self, choice_groups, *args, **kwargs): self.choice_groups = choice_groups super(GroupedModelChoiceField, self).__init__(*args, **kwargs) def _get_choices(self): if hasattr(self, '_choices'): return self._choices return GroupedModelChoiceIterator(self) choices = property(_get_choices, forms.ModelChoiceField._set_choices) class LiberalModelChoiceField(forms.ModelChoiceField): """ModelChoiceField that doesn't complain about choices not present in the queryset. This is essentially a hack for admin pages. to be able to exclude currently used choices from dropdowns without failing validation. """ def clean(self, value): if value in EMPTY_VALUES: return None try: key = self.to_field_name or 'pk' value = self.queryset.model.objects.get(**{key: value}) except self.queryset.model.DoesNotExist: raise forms.ValidationError(self.error_messages['invalid_choice']) return value def make_search_form(*args, **kwargs): """Factory that instantiates one of the search forms below.""" request = kwargs.pop('request', None) if request is not None: sparams_cookie = request.COOKIES.get('pootle-search') if sparams_cookie: import json import urllib try: initial_sparams = json.loads(urllib.unquote(sparams_cookie)) except ValueError: pass else: if (isinstance(initial_sparams, dict) and 'sfields' in initial_sparams): kwargs.update({ 'initial': initial_sparams, }) return SearchForm(*args, **kwargs) class SearchForm(forms.Form): """Normal search form for translation projects.""" search = forms.CharField( widget=forms.TextInput(attrs={ 'autocomplete': 'off', 'size': '15', 'placeholder': _('Search'), 'title': _("Search (Ctrl+Shift+S)<br/>Type and press Enter to " "search"), }), ) soptions = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=( ('exact', _('Phrase match')), ('case', _('Case-sensitive match')))) sfields = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=( ('source', _('Source Text')), ('target', _('Target Text')), ('notes', _('Comments')), ('locations', _('Locations')) ), initial=['source', 'target'], )
3,996
Python
.py
99
31.252525
80
0.621482
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,385
render_pager.py
translate_pootle/pootle/apps/pootle_misc/templatetags/render_pager.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 template from django.utils.safestring import mark_safe from pootle.i18n.gettext import ugettext as _ register = template.Library() @register.filter def render_pager(pager): """Render a pager block with next and previous links""" if not pager.has_other_pages(): return "" result = '<ul class="pager">' if pager.has_previous(): result += '<li><a href="?page=1" class="nth-link">%s</a></li>' % \ _('First') result += ('<li><a href="?page=%d" class="prevnext-link">%s</a>' '</li>' % (pager.previous_page_number(), _('Previous'))) start = max(1, pager.number - 4) end = min(pager.paginator.num_pages, pager.number + 4) if start > 1: result += '<li>...</li>' for i in range(start, end+1): if i == pager.number: result += '<li><span class="current-link">%s</span></li>' % i else: result += ('<li><a href="?page=%d" class="number-link">%d</a>' '</li>' % (i, i)) if end < pager.paginator.num_pages: result += '<li>...</li>' if pager.has_next(): result += ('<li><a href="?page=%d" class="prevnext-link">%s</a>' '</li>' % (pager.next_page_number(), _('Next'))) result += '<li><a href="?page=%d" class="nth-link">%s</a></li>' % \ (pager.paginator.num_pages, _('Last (%d)', pager.paginator.num_pages)) result += '</ul>' return mark_safe(result)
1,825
Python
.py
42
35.333333
77
0.557812
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,386
search.py
translate_pootle/pootle/apps/pootle_misc/templatetags/search.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 template from pootle.i18n.gettext import ugettext as _ from pootle_misc.forms import make_search_form register = template.Library() @register.inclusion_tag('core/search.html', takes_context=True) def render_search(context): search_form = make_search_form(request=context['request']) is_disabled = (context["page"] != "translate" and not context["can_translate_stats"]) if is_disabled: search_form.fields["search"].widget.attrs.update({ 'readonly': 'readonly', 'disabled': True, 'title': '', 'placeholder': _("Search unavailable"), }) return { 'search_form': search_form, 'search_action': context["object"].get_translate_url(), 'is_disabled': is_disabled, }
1,085
Python
.py
28
32.964286
77
0.666667
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,387
common_tags.py
translate_pootle/pootle/apps/pootle_misc/templatetags/common_tags.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 from django import template from django.utils.translation import get_language from pootle.i18n import formatter from pootle.i18n.dates import timesince from pootle.i18n.gettext import ugettext_lazy as _ register = template.Library() @register.filter def time_since(timestamp): return ( timesince( timestamp, locale=get_language()) if timestamp else "") @register.inclusion_tag('includes/avatar.html') def avatar(username, email_hash, size): # TODO: return sprite if its a system user if username == "system": return dict(icon="icon-pootle") return dict( avatar_url=( 'https://secure.gravatar.com/avatar/%s?s=%d&d=mm' % (email_hash, size))) @register.inclusion_tag('browser/_progressbar.html') def progress_bar(total, fuzzy, translated): if not total: fuzzy_frac = translated_frac = untranslated_frac = 0 cldrformat = "0%" else: untranslated = total - translated - fuzzy untranslated_frac = float(untranslated)/total fuzzy_frac = float(fuzzy)/total translated_frac = float(translated)/total cldrformat = "#,##0.0%" untranslated_display = (_("{percentage} untranslated")).format( percentage=formatter.percent(untranslated_frac, cldrformat)) fuzzy_display = (_("{percentage} needs work")).format( percentage=formatter.percent(fuzzy_frac, cldrformat)) translated_display = (_("{percentage} translated")).format( percentage=formatter.percent(translated_frac, cldrformat)) return dict( untranslated_percent_display=untranslated_display, fuzzy_percent_display=fuzzy_display, translated_percent_display=translated_display, untranslated_bar=round(untranslated_frac * 100, 1), fuzzy_bar=round(fuzzy_frac * 100, 1), translated_bar=round(translated_frac * 100, 1)) @register.inclusion_tag('browser/_table.html') def display_table(table, can_translate): return { 'can_translate': can_translate, 'table': table, } @register.filter @template.defaultfilters.stringfilter def cssid(value): """Replaces all '.', '+', ' ' and '@' with '-'. Used to create valid CSS identifiers from tree item codes. """ return value.replace(u'.', u'-').replace(u'@', u'-') \ .replace(u'+', u'-').replace(u' ', u'-') @register.filter def endswith(value, arg): return value.endswith(arg) @register.filter def count(value, arg): return value.count(arg) @register.filter def label_tag(field, suffix=None): """Returns the `label_tag` for a field. Optionally allows overriding the default `label_suffix` for the form this field belongs to. """ if not hasattr(field, 'label_tag'): return '' return field.label_tag(label_suffix=suffix) @register.inclusion_tag('core/_top_scorers.html') def top_scorers(user, top_scorers): return dict(user=user, top_scorers=top_scorers) @register.simple_tag def format_date_range(date_from, date_to, separator=" - ", format_str="{dt:%B} {dt.day}, {dt:%Y}", year_f=", {dt:%Y}", month_f="{dt:%B}"): """Takes a start date, end date, separator and formatting strings and returns a pretty date range string """ if (isinstance(date_to, datetime.datetime) and isinstance(date_from, datetime.datetime)): date_to = date_to.date() date_from = date_from.date() if date_to and date_to != date_from: from_format = to_format = format_str if date_from.year == date_to.year: from_format = from_format.replace(year_f, '') if date_from.month == date_to.month: to_format = to_format.replace(month_f, '') return separator.join((from_format.format(dt=date_from), to_format.format(dt=date_to))) return format_str.format(dt=date_from)
4,253
Python
.py
106
33.830189
77
0.664319
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,388
select2l10n.py
translate_pootle/pootle/apps/pootle_misc/templatetags/select2l10n.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 django import template from django.conf import settings from django.template.defaultfilters import stringfilter register = template.Library() select2_langs = [] @register.filter @stringfilter def is_select2_lang(language_code): """Return the script tag snippet if the language has l10n for Select2.""" if not language_code: return '' global select2_langs if not select2_langs: select2_l10n_dir = os.path.join( settings.WORKING_DIR, 'static', 'js', 'select2_l10n') select2_langs = [f.split(".")[0] for f in os.listdir(select2_l10n_dir) if (os.path.isfile(os.path.join(select2_l10n_dir, f)) and f.endswith('.js'))] return language_code if language_code in select2_langs else ''
1,107
Python
.py
28
33.5
78
0.676608
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,389
locale.py
translate_pootle/pootle/apps/pootle_misc/templatetags/locale.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 calendar from django import template from django.utils.formats import get_format from django.utils.translation import get_language, trans_real from pootle.core.utils import dateformat from pootle.i18n.dates import timesince register = template.Library() @register.simple_tag def locale_dir(): """Returns current locale's direction.""" return trans_real.get_language_bidi() and "rtl" or "ltr" @register.filter(name='dateformat') def do_dateformat(value, use_format='c'): """Formats a `value` date using `format`. :param value: a datetime object. :param use_format: a format string accepted by :func:`django.utils.formats.get_format` or :func:`django.utils.dateformat.format`. If none is set, the current locale's default format will be used. """ try: use_format = get_format(use_format) except AttributeError: pass return dateformat.format(value, use_format) @register.filter(name='relative_datetime_format') def do_relative_datetime_format(value): return timesince( calendar.timegm(value.timetuple()), locale=get_language()) @register.simple_tag def locale_align(): """Returns current locale's default alignment.""" return trans_real.get_language_bidi() and "right" or "left"
1,577
Python
.py
41
34.560976
77
0.735043
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,390
cleanhtml.py
translate_pootle/pootle/apps/pootle_misc/templatetags/cleanhtml.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 re from lxml.html import fromstring, tostring from django import template from django.template.defaultfilters import stringfilter from django.utils.safestring import mark_safe from pootle.core.utils.html import rewrite_links register = template.Library() @register.filter @stringfilter def url_target_blank(text): """Sets the target="_blank" for hyperlinks.""" return mark_safe(text.replace('<a ', '<a target="_blank" ')) TRIM_URL_LENGTH = 70 def trim_url(link): """Trims `link` if it's longer than `TRIM_URL_LENGTH` chars. Trimming is done by always keeping the scheme part, and replacing everything up to the last path part with three dots. Example:: https://www.evernote.com/shard/s12/sh/f6f3eb18-c11c/iPhone5_AppStore_01_Overview.png?resizeSmall&width=832 becomes https://.../iPhone5_AppStore_01_Overview.png?resizeSmall&width=832 """ link_text = link if len(link_text) > TRIM_URL_LENGTH: scheme_index = link.rfind('://') + 3 last_slash_index = link.rfind('/') text_to_replace = link[scheme_index:last_slash_index] link_text = link_text.replace(text_to_replace, '...') return link_text @register.filter @stringfilter def url_trim(html): """Trims anchor texts that are longer than 70 chars.""" fragment = fromstring(html) for el, attrib_, link_, pos_ in fragment.iterlinks(): new_link_text = trim_url(el.text_content()) el.text = new_link_text return mark_safe(tostring(fragment, encoding=unicode)) LANGUAGE_LINK_RE = re.compile(ur'/xx/', re.IGNORECASE) @register.filter @stringfilter def rewrite_language_links(html, language_code): if language_code: html = rewrite_links( html, lambda lnk: LANGUAGE_LINK_RE.sub(u'/' + language_code + u'/', lnk) ) return mark_safe(html)
2,141
Python
.py
54
35.240741
110
0.710131
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,391
models.py
translate_pootle/pootle/apps/accounts/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 re from hashlib import md5 from django.conf import settings from django.contrib.auth.base_user import AbstractBaseUser from django.core.exceptions import ValidationError from django.core.mail import send_mail from django.core.validators import RegexValidator from django.db import models from django.db.models import ProtectedError, Q from django.forms.models import model_to_dict from django.urls import reverse from django.utils import timezone from django.utils.encoding import force_bytes from django.utils.functional import cached_property from allauth.account.models import EmailAddress from allauth.account.utils import sync_user_email_addresses from pootle.core.views.display import ActionDisplay from pootle.i18n import formatter from pootle.i18n.gettext import ugettext_lazy as _ from pootle_statistics.models import Submission from pootle_store.models import Unit from .managers import UserManager from .utils import UserMerger, UserPurger __all__ = ('User', ) CURRENCIES = (('USD', 'USD'), ('EUR', 'EUR'), ('CNY', 'CNY'), ('JPY', 'JPY')) class User(AbstractBaseUser): """The Pootle User. ``username``, ``password`` and ``email`` are required. Other fields are optional. Note that the ``password`` and ``last_login`` fields are inherited from ``AbstractBaseUser``. """ username = models.CharField( _('Username'), max_length=30, unique=True, help_text=_('Required. 30 characters or fewer. Letters, numbers and ' '@/./+/-/_ characters'), validators=[ RegexValidator(re.compile('^[\w.@+-]+$', re.UNICODE), _('Enter a valid username.'), 'invalid') ], error_messages={ 'unique': _('A user with that username already exists.'), }, ) email = models.EmailField(_('Email Address'), max_length=255) full_name = models.CharField(_('Full Name'), max_length=255, blank=True) is_active = models.BooleanField( _('Active'), default=True, db_index=True, help_text=_('Designates whether this user should be treated as ' 'active. Unselect this instead of deleting accounts.')) is_superuser = models.BooleanField( _('Superuser Status'), default=False, db_index=True, help_text=_('Designates that this user has all permissions without ' 'explicitly assigning them.')) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) # Translation setting fields unit_rows = models.SmallIntegerField(default=9, verbose_name=_("Number of Rows")) alt_src_langs = models.ManyToManyField( 'pootle_language.Language', blank=True, db_index=True, limit_choices_to=~Q(code='templates'), verbose_name=_("Alternative Source Languages")) # Score-related fields score = models.FloatField(_('Score'), null=False, default=0) is_employee = models.BooleanField(_('Is employee?'), default=False) twitter = models.CharField(_('Twitter'), max_length=15, null=True, blank=True) website = models.URLField(_('Website'), null=True, blank=True) linkedin = models.URLField(_('LinkedIn'), null=True, blank=True) bio = models.TextField(_('Short Bio'), null=True, blank=True) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] objects = UserManager() @property def display_name(self): """Human-readable display name.""" return (self.get_full_name() if self.get_full_name() else self.get_short_name()) @property def public_score(self): return formatter.number(round(self.score)) @property def has_contact_details(self): """Returns ``True`` if any contact details have been set.""" return bool(self.website or self.twitter or self.linkedin) @property def twitter_url(self): return 'https://twitter.com/{0}'.format(self.twitter) @cached_property def is_meta(self): """Returns `True` if this is a special fake user.""" return self.username in \ UserManager.META_USERS + settings.POOTLE_META_USERS @cached_property def email_hash(self): try: return md5(force_bytes(self.email)).hexdigest() except UnicodeEncodeError: return None def __unicode__(self): return self.username def save(self, *args, **kwargs): old_email = (None if self.pk is None else User.objects.get(pk=self.pk).email) super(User, self).save(*args, **kwargs) self.sync_email(old_email) def delete(self, *args, **kwargs): """Deletes a user instance. Trying to delete a meta user raises the `ProtectedError` exception. """ if self.is_meta: raise ProtectedError('Cannot remove meta user instances', None) purge = kwargs.pop("purge", False) if purge: UserPurger(self).purge() else: UserMerger(self, User.objects.get_nobody_user()).merge() super(User, self).delete(*args, **kwargs) def get_absolute_url(self): return reverse('pootle-user-profile', args=[self.username]) def field_values(self): """Returns the user's field-values (can be encoded as e.g. JSON).""" values = model_to_dict(self, exclude=['password']) values["alt_src_langs"] = list( values["alt_src_langs"].values_list("pk", flat=True)) return values @property def is_anonymous(self): """Returns `True` if this is an anonymous user.""" return self.username == 'nobody' @property def is_authenticated(self): """Returns `True` if this is an authenticated user.""" return self.username != 'nobody' def is_system(self): """Returns `True` if this is the special `system` user.""" return self.username == 'system' def has_manager_permissions(self): """Tells if the user is a manager for any language, project or TP.""" if self.is_anonymous: return False if self.is_superuser: return True criteria = { 'positive_permissions__codename': 'administrate', 'directory__pootle_path__regex': r'^/[^/]*/([^/]*/)?$', } return self.permissionset_set.filter(**criteria).exists() def get_full_name(self): """Returns the user's full name.""" return self.full_name.strip() def get_short_name(self): """Returns the short name for the user.""" return self.username def email_user(self, subject, message, from_email=None): """Sends an email to this user.""" send_mail(subject, message, from_email, [self.email]) def clean_fields(self, exclude=None): super(User, self).clean_fields(exclude=exclude) self.validate_email() def validate_email(self): """Ensure emails are unique across the models tracking emails. Since it's essential to keep email addresses unique to support our workflows, a `ValidationError` will be raised if the email trying to be saved is already assigned to some other user. """ lookup = Q(email__iexact=self.email) if self.pk is not None: # When there's an update, ensure no one else has this address lookup &= ~Q(user=self) try: EmailAddress.objects.get(lookup) except EmailAddress.DoesNotExist: pass else: raise ValidationError({ 'email': [_('This email address already exists.')] }) def sync_email(self, old_email): """Syncs up `self.email` with allauth's own `EmailAddress` model. :param old_email: Address this user previously had """ if old_email != self.email: # Update EmailAddress.objects.filter( user=self, email__iexact=old_email, ).update(email=self.email) else: sync_user_email_addresses(self) def gravatar_url(self, size=80): if not self.email_hash: return '' return 'https://secure.gravatar.com/avatar/%s?s=%d&d=mm' % \ (self.email_hash, size) def get_suggestion_reviews(self): return self.submission_set.get_unit_suggestion_reviews() def get_unit_rows(self): return min(max(self.unit_rows, 5), 49) def get_unit_states_changed(self): return self.submission_set.get_unit_state_changes() def get_units_created(self): """Units that were created by this user. :return: Queryset of `Unit`s that were created by this user. """ return Unit.objects.filter(unit_source__created_by=self) def last_event(self, locale=None): """Returns the latest submission linked with this user. If there's no activity, `None` is returned instead. """ last_event = Submission.objects.select_related( "unit", "unit__store", "unit__store__parent").filter(submitter=self).last() if last_event: return ActionDisplay( last_event.get_submission_info(), locale=locale)
9,746
Python
.py
231
33.731602
78
0.631239
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,392
getters.py
translate_pootle/pootle/apps/accounts/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.contrib.auth import get_user_model from pootle.core.delegate import crud from pootle.core.plugin import getter from .updater import UserCRUD User = get_user_model() CRUD = { User: UserCRUD()} @getter(crud, sender=User) def accounts_crud_getter(**kwargs): return CRUD[kwargs["sender"]]
588
Python
.py
17
32.647059
77
0.765542
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,393
proxy.py
translate_pootle/pootle/apps/accounts/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 hashlib import md5 from django.urls import reverse from django.utils.encoding import force_bytes from django.utils.html import format_html class DisplayUser(object): def __init__(self, username, full_name, email=None): self.username = username self.full_name = full_name self.email = email @property def author_link(self): return format_html( u'<a href="{}">{}</a>', self.get_absolute_url(), self.display_name) @property def display_name(self): return ( self.full_name.strip() if self.full_name.strip() else self.username) @property def email_hash(self): return md5(force_bytes(self.email)).hexdigest() def get_absolute_url(self): return reverse( 'pootle-user-profile', args=[self.username]) def gravatar_url(self, size=80): return ( 'https://secure.gravatar.com/avatar/%s?s=%d&d=mm' % (self.email_hash, size)) def to_dict(self): userdict = {} props = [ "username", "author_link", "display_name", "email_hash"] methods = [ "get_absolute_url", "gravatar_url"] for prop in props: userdict[prop] = getattr(self, prop) for method in methods: userdict[method] = getattr(self, method)() return userdict
1,720
Python
.py
51
26
77
0.608565
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,394
urls.py
translate_pootle/pootle/apps/accounts/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 .views import SocialVerificationView urlpatterns = [ url(r'^social/verify/$', SocialVerificationView.as_view(), name='pootle-social-verify'), ]
481
Python
.py
14
31.642857
77
0.740821
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,395
apps.py
translate_pootle/pootle/apps/accounts/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 AccountsConfig(AppConfig): name = "accounts" verbose_name = "Accounts" version = "0.1.1" def ready(self): importlib.import_module("accounts.getters") importlib.import_module("accounts.receivers")
566
Python
.py
16
32
77
0.737132
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,396
receivers.py
translate_pootle/pootle/apps/accounts/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 django.contrib.auth import get_user_model from django.dispatch import receiver from pootle.core.delegate import crud from pootle.core.signals import update User = get_user_model() @receiver(update, sender=User) def handle_account_user_update(**kwargs): crud.get(User).update(**kwargs)
575
Python
.py
15
36.666667
77
0.781588
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,397
utils.py
translate_pootle/pootle/apps/accounts/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. import functools import logging import sys from django.contrib.auth import get_user_model from django.core.validators import ValidationError, validate_email from django.db.models import Count from allauth.account.models import EmailAddress from allauth.account.utils import sync_user_email_addresses from pootle.core.contextmanagers import keep_data from pootle.core.delegate import score_updater from pootle.core.models import Revision from pootle.core.signals import update_data, update_revisions from pootle_app.models import Directory from pootle_statistics.models import SubmissionFields from pootle_store.constants import FUZZY, UNTRANSLATED from pootle_store.models import SuggestionState logger = logging.getLogger(__name__) def get_user_by_email(email): """Retrieves auser by its email address. First it looks up the `EmailAddress` entries, and as a safety measure falls back to looking up the `User` entries (these addresses are sync'ed in theory). :param email: address of the user to look up. :return: `User` instance belonging to `email`, `None` otherwise. """ try: return EmailAddress.objects.get(email__iexact=email).user except EmailAddress.DoesNotExist: try: User = get_user_model() return User.objects.get(email__iexact=email) except User.DoesNotExist: return None def write_stdout(start_msg, end_msg="DONE\n", fail_msg="FAILED\n"): def class_wrapper(f): @functools.wraps(f) def method_wrapper(self, *args, **kwargs): sys.stdout.write(start_msg % self.__dict__) try: result = f(self, *args, **kwargs) except Exception as e: sys.stdout.write(fail_msg % self.__dict__) logger.exception(e) raise e sys.stdout.write(end_msg % self.__dict__) return result return method_wrapper return class_wrapper class UserMerger(object): def __init__(self, src_user, target_user): """Purges src_user from site reverting any changes that they have made. :param src_user: `User` instance to merge from. :param target_user: `User` instance to merge to. """ self.src_user = src_user self.target_user = target_user @write_stdout("Merging user: " "%(src_user)s --> %(target_user)s...\n", "User merged: %(src_user)s --> %(target_user)s \n") def merge(self): """Merges one user to another. The following are fields are updated (model: fields): - units: submitted_by, commented_by, reviewed_by - submissions: submitter - suggestions: user, reviewer """ self.merge_submitted() self.merge_commented() self.merge_reviewed() self.merge_submissions() self.merge_suggestions() self.merge_reviews() @write_stdout(" * Merging units comments: " "%(src_user)s --> %(target_user)s... ") def merge_commented(self): """Merge commented_by attribute on units """ # TODO: this need to update unitchange not unit self.src_user.commented.update(commented_by=self.target_user) @write_stdout(" * Merging units reviewed: " "%(src_user)s --> %(target_user)s... ") def merge_reviewed(self): """Merge reviewed_by attribute on units """ self.src_user.reviewed.update(reviewed_by=self.target_user) @write_stdout(" * Merging suggestion reviews: " "%(src_user)s --> %(target_user)s... ") def merge_reviews(self): """Merge reviewer attribute on suggestions """ self.src_user.reviews.update(reviewer=self.target_user) @write_stdout(" * Merging remaining submissions: " "%(src_user)s --> %(target_user)s... ") def merge_submissions(self): """Merge submitter attribute on submissions """ # Delete orphaned submissions. self.src_user.submission_set.filter(unit__isnull=True).delete() score_updater.get( self.src_user.__class__)(users=[self.src_user.id]).clear() # Update submitter on submissions self.src_user.submission_set.update(submitter=self.target_user) @write_stdout(" * Merging units submitted_by: " "%(src_user)s --> %(target_user)s... ") def merge_submitted(self): """Merge submitted_by attribute on units """ self.src_user.submitted.update(submitted_by=self.target_user) @write_stdout(" * Merging suggestions: " "%(src_user)s --> %(target_user)s... ") def merge_suggestions(self): """Merge user attribute on suggestions """ # Update user and reviewer on suggestions self.src_user.suggestions.update(user=self.target_user) class UserPurger(object): def __init__(self, user): """Purges user from site reverting any changes that they have made. :param user: `User` to purge. """ self.user = user @write_stdout("Purging user: %(user)s... \n", "User purged: %(user)s \n") def purge(self): """Purges user from site reverting any changes that they have made. The following steps are taken: - Delete units created by user and without other submissions. - Revert units edited by user. - Revert reviews made by user. - Revert unit comments by user. - Revert unit state changes by user. - Delete any remaining submissions and suggestions. - Expire caches for relevant directories """ stores = set() with keep_data(): stores |= self.remove_units_created() stores |= self.revert_units_edited() stores |= self.revert_units_reviewed() stores |= self.revert_units_commented() stores |= self.revert_units_state_changed() # Delete remaining submissions. logger.debug("Deleting remaining submissions for: %s", self.user) self.user.submission_set.all().delete() # Delete remaining suggestions. logger.debug("Deleting remaining suggestions for: %s", self.user) self.user.suggestions.all().delete() for store in stores: update_data.send(store.__class__, instance=store) update_revisions.send( Directory, object_list=Directory.objects.filter( id__in=set(store.parent.id for store in stores))) @write_stdout(" * Removing units created by: %(user)s... ") def remove_units_created(self): """Remove units created by user that have not had further activity. """ stores = set() # Delete units created by user without submissions by others. for unit in self.user.get_units_created().iterator(): stores.add(unit.store) # Find submissions by other users on this unit. other_subs = unit.submission_set.exclude(submitter=self.user) if not other_subs.exists(): unit.delete() logger.debug("Unit deleted: %s", repr(unit)) return stores @write_stdout(" * Reverting unit comments by: %(user)s... ") def revert_units_commented(self): """Revert comments made by user on units to previous comment or else just remove the comment. """ stores = set() # Revert unit comments where self.user is latest commenter. for unit_change in self.user.commented.select_related("unit").iterator(): unit = unit_change.unit stores.add(unit.store) # Find comments by other self.users comments = unit.get_comments().exclude(submitter=self.user) change = {} if comments.exists(): # If there are previous comments by others update the # translator_comment, commented_by, and commented_on last_comment = comments.latest('pk') translator_comment = last_comment.new_value change["commented_by_id"] = last_comment.submitter_id change["commented_on"] = last_comment.creation_time logger.debug("Unit comment reverted: %s", repr(unit)) else: translator_comment = "" change["commented_by"] = None change["commented_on"] = None logger.debug("Unit comment removed: %s", repr(unit)) unit_change.__class__.objects.filter(id=unit_change.id).update( **change) unit.__class__.objects.filter(id=unit.id).update( translator_comment=translator_comment, revision=Revision.incr()) return stores @write_stdout(" * Reverting units edited by: %(user)s... ") def revert_units_edited(self): """Revert unit edits made by a user to previous edit. """ stores = set() # Revert unit target where user is the last submitter. for unit_change in self.user.submitted.select_related("unit").iterator(): unit = unit_change.unit stores.add(unit.store) # Find the last submission by different user that updated the # unit.target. edits = unit.get_edits().exclude(submitter=self.user) updates = {} unit_updates = {} if edits.exists(): last_edit = edits.latest("pk") unit_updates["target_f"] = last_edit.new_value updates["submitted_by_id"] = last_edit.submitter_id updates["submitted_on"] = last_edit.creation_time logger.debug("Unit edit reverted: %s", repr(unit)) else: # if there is no previous submissions set the target to "" and # set the unit.change.submitted_by to None unit_updates["target_f"] = "" updates["submitted_by"] = None updates["submitted_on"] = unit.creation_time logger.debug("Unit edit removed: %s", repr(unit)) # Increment revision unit_change.__class__.objects.filter(id=unit_change.id).update( **updates) unit.__class__.objects.filter(id=unit.id).update( revision=Revision.incr(), **unit_updates) return stores @write_stdout(" * Reverting units reviewed by: %(user)s... ") def revert_units_reviewed(self): """Revert reviews made by user on suggestions to previous state. """ stores = set() pending = SuggestionState.objects.get(name="pending") # Revert reviews by this user. for review in self.user.get_suggestion_reviews().iterator(): suggestion = review.suggestion stores.add(suggestion.unit.store) if suggestion.user_id == self.user.id: # If the suggestion was also created by this user then remove # both review and suggestion. suggestion.delete() logger.debug("Suggestion removed: %s", (suggestion)) elif suggestion.reviewer_id == self.user.id: # If the suggestion is showing as reviewed by the user, then # set the suggestion back to pending and update # reviewer/review_time. suggestion.state = pending suggestion.reviewer = None suggestion.review_time = None suggestion.save() logger.debug("Suggestion reverted: %s", (suggestion)) # Remove the review. review.delete() for unit_change in self.user.reviewed.select_related("unit").iterator(): unit = unit_change.unit stores.add(unit.store) unit.suggestion_set.filter(reviewer=self.user).update( state=SuggestionState.objects.get(name="pending"), reviewer=None) unit_updates = {} updates = {} if not unit.target: unit_updates["state"] = UNTRANSLATED updates["reviewed_by"] = None updates["reviewed_on"] = None else: old_state_sub = unit.submission_set.exclude( submitter=self.user).filter( field=SubmissionFields.STATE).order_by( "-creation_time", "-pk").first() if old_state_sub: unit_updates["state"] = old_state_sub.new_value updates["reviewed_by"] = old_state_sub.submitter updates["reviewed_on"] = old_state_sub.creation_time logger.debug("Unit reviewed_by removed: %s", repr(unit)) unit_change.__class__.objects.filter(id=unit_change.id).update( **updates) # Increment revision unit.__class__.objects.filter(id=unit.id).update( revision=Revision.incr(), **unit_updates) return stores @write_stdout(" * Reverting unit state changes by: %(user)s... ") def revert_units_state_changed(self): """Revert unit edits made by a user to previous edit. """ stores = set() # Delete orphaned submissions. self.user.submission_set.filter(unit__isnull=True).delete() for submission in self.user.get_unit_states_changed().iterator(): unit = submission.unit stores.add(unit.store) # We have to get latest by pk as on mysql precision is not to # microseconds - so creation_time can be ambiguous if submission != unit.get_state_changes().latest('pk'): # If the unit has been changed more recently we don't need to # revert the unit state. submission.delete() return submission.delete() other_submissions = (unit.get_state_changes() .exclude(submitter=self.user)) if other_submissions.exists(): new_state = other_submissions.latest('pk').new_value else: new_state = UNTRANSLATED if new_state != unit.state: if unit.state == FUZZY: unit.markfuzzy(False) elif new_state == FUZZY: unit.markfuzzy(True) unit.state = new_state # Increment revision unit.__class__.objects.filter(id=unit.id).update( revision=Revision.incr()) logger.debug("Unit state reverted: %s", repr(unit)) return stores def verify_user(user): """Verify a user account without email confirmation If the user has an existing primary allauth.EmailAddress set then this is verified. Otherwise, an allauth.EmailAddress is created using email set for User.email. If the user is already verified raises a ValueError :param user: `User` to verify """ if not user.email: raise ValidationError("You cannot verify an account with no email " "set. You can set this user's email with " "'pootle update_user_email %s EMAIL'" % user.username) # Ensure this user's email address is unique try: validate_email_unique(user.email, user) except ValidationError: raise ValidationError("This user's email is not unique. You can find " "duplicate emails with 'pootle " "find_duplicate_emails'") # already has primary? existing_primary = EmailAddress.objects.filter(user=user, primary=True) if existing_primary.exists(): existing_primary = existing_primary.first() if not existing_primary.verified: existing_primary.verified = True existing_primary.save() return else: # already verified raise ValueError("User '%s' is already verified" % user.username) sync_user_email_addresses(user) email_address = (EmailAddress.objects .filter(user=user, email__iexact=user.email) .order_by("primary")).first() email_address.verified = True email_address.primary = True email_address.save() def get_duplicate_emails(): """Get a list of emails that occur more than once in user accounts. """ return (get_user_model().objects.hide_meta() .values('email') .annotate(Count('email')) .filter(email__count__gt=1) .values_list("email", flat=True)) def validate_email_unique(email, for_user=None): """Validates an email to ensure it does not already exist in the system. :param email: Email address to validate for uniqueness. :param for_user: Optionally check an email address is unique to this user """ existing_accounts = get_user_model().objects.filter(email=email) existing_email = EmailAddress.objects.filter(email=email) if for_user is not None: existing_accounts = existing_accounts.exclude(pk=for_user.pk) existing_email = existing_email.exclude(user=for_user) if existing_accounts.exists() or existing_email.exists(): raise ValidationError("A user with that email address already exists") def update_user_email(user, new_email): """Updates a user's email with new_email. :param user: `User` to update email for. :param new_email: Email address to update with. """ validate_email_unique(new_email) validate_email(new_email) user.email = new_email user.save()
18,334
Python
.py
398
34.922111
81
0.601209
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,398
__init__.py
translate_pootle/pootle/apps/accounts/__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 = 'accounts.apps.AccountsConfig'
328
Python
.py
8
39.875
77
0.76489
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,399
updater.py
translate_pootle/pootle/apps/accounts/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. from django.contrib.auth import get_user_model from pootle.core.bulk import BulkCRUD class UserCRUD(BulkCRUD): model = get_user_model()
419
Python
.py
11
36.363636
77
0.769802
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)