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,100
__init__.py
translate_pootle/pootle/__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 pootle.core.utils.version import get_version from pootle.constants import VERSION __version__ = get_version(VERSION)
400
Python
.py
10
38.7
77
0.775194
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,101
phaselist2vfolder.py
translate_pootle/pootle/tools/phaselist2vfolder.py
#!/usr/bin/env python # -*- 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 json # Config # Goals file to convert to JSON phaselistfile = 'firefox.phaselist' # Name of the project on Pootle project = "firefox" # Mapping of goals and priorities, default will be 1.0 priorities = { 'tbshared': 1.0, 'androidshared': 1.0, 'user1': 5.0, 'lang': 0.9, 'user2': 4.0, 'user3': 3.0, 'config1': 3.0, 'user4': 2.0, 'config2': 2.0, 'configx': 1.0, 'install': 1.0, 'platform': 1.0, 'other': 0.9, '1': 0.9, 'developers': 0.5, 'security1': 0.4, 'notnb': 0.3, 'never': 0.1, 'langpack': 6.0, } # If a goal should be marked as not public not_public = [ 'notnb', 'never', ] vfolders = [] with open(phaselistfile) as phaselist: for line in phaselist: goal, pofile = line.split("\t") goal = goal.strip() pofile = pofile.rstrip('\n').strip('.').lstrip('/') for vfolder in vfolders: if vfolder['name'] == goal: vfolder['filters']['files'].append(pofile) break else: vfolders.append({ 'name': goal, 'location': '/{LANG}/%s/' % project, 'priority': priorities.get(goal, 1.0), 'is_public': goal not in not_public, 'filters': { 'files': [ pofile, ] } }) print(json.dumps(vfolders, sort_keys=True, indent=4))
1,775
Python
.py
64
21.015625
77
0.553204
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,102
auth.py
translate_pootle/pootle/middleware/auth.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. """ Custom Pootle authentication middleware that takes care of returning Pootle's special `nobody` user instead of Django's own `AnonymousUser`. The code has been slightly adapted from django.contrib.auth.middleware. Note this customization would probably be unnecessary if there was a fix for https://code.djangoproject.com/ticket/20313 """ from django.contrib import auth from django.utils.deprecation import MiddlewareMixin from django.utils.functional import SimpleLazyObject def get_user(request): if not hasattr(request, '_cached_user'): user = auth.get_user(request) request._cached_user = (user if user.is_authenticated else auth.get_user_model().objects.get_nobody_user()) return request._cached_user class AuthenticationMiddleware(MiddlewareMixin): def process_request(self, request): assert hasattr(request, 'session'), ( "The Django authentication middleware requires session middleware " "to be installed. Edit your MIDDLEWARE setting to insert " "'django.contrib.sessions.middleware.SessionMiddleware' before " "'django.contrib.auth.middleware.AuthenticationMiddleware'." ) request.user = SimpleLazyObject(lambda: get_user(request))
1,562
Python
.py
32
43.4375
80
0.740473
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,103
captcha.py
translate_pootle/pootle/middleware/captcha.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.conf import settings from django.http import Http404 from django.shortcuts import render from django.urls import resolve from django.utils.deprecation import MiddlewareMixin from pootle.core.forms import MathCaptchaForm URL_RE = re.compile("https?://", re.I) CAPTCHA_EXEMPT_URLPATTERNS = ( 'account_login', 'account_signup', 'account_reset_password', 'account_reset_password_from_key', 'pootle-social-verify', 'pootle-contact', 'pootle-tp-paths', 'pootle-project-paths') class CaptchaMiddleware(MiddlewareMixin): """Middleware to display a captcha question to verify POST submissions are made by humans. """ def process_request(self, request): if (not settings.POOTLE_CAPTCHA_ENABLED or not request.POST or request.session.get('ishuman', False)): return try: # No captcha for exempted pages resolver_match = resolve(request.path_info) if resolver_match.url_name in CAPTCHA_EXEMPT_URLPATTERNS: return except Http404: pass if request.user.is_authenticated: if ('target_f_0' not in request.POST or 'translator_comment' not in request.POST): return # We are in translate page. Users introducing new URLs in the # target or comment field are suspect even if authenticated try: target_urls = len(URL_RE.findall(request.POST['target_f_0'])) except KeyError: target_urls = 0 try: comment_urls = len(URL_RE.findall( request.POST['translator_comment'])) except KeyError: comment_urls = 0 try: source_urls = len(URL_RE.findall(request.POST['source_f_0'])) except KeyError: source_urls = 0 if (comment_urls == 0 and (target_urls == 0 or target_urls == source_urls)): return if 'captcha_answer' in request.POST: form = MathCaptchaForm(request.POST) if form.is_valid(): request.session['ishuman'] = True return else: # new question form.reset_captcha() else: form = MathCaptchaForm() template_name = 'core/captcha.html' ctx = { 'form': form, 'url': request.path, 'post_data': request.POST, } if (request.is_ajax() and ('sfn' in request.POST and 'efn' in request.POST)): template_name = 'core/xhr_captcha.html' response = render(request, template_name, ctx) response.status_code = 402 # (Ab)using 402 for captcha purposes. return response
3,177
Python
.py
83
28.180723
77
0.595966
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,104
cache.py
translate_pootle/pootle/middleware/cache.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django.utils.cache import add_never_cache_headers from django.utils.deprecation import MiddlewareMixin class CacheAnonymousOnly(MiddlewareMixin): """Imitate the deprecated `CACHE_MIDDLEWARE_ANONYMOUS_ONLY` behavior.""" def process_response(self, request, response): if hasattr(request, 'user') and request.user.is_authenticated: add_never_cache_headers(response) return response
700
Python
.py
15
42.933333
77
0.760294
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,105
baseurl.py
translate_pootle/pootle/middleware/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. from django.conf import settings from django.utils.deprecation import MiddlewareMixin class BaseUrlMiddleware(MiddlewareMixin): def process_request(self, request): """calculate settings.BASEURL based on HTTP headers""" domain = None if 'HTTP_HOST' in request.META: domain = request.get_host() if 'SCRIPT_NAME' in request.META: settings.SCRIPT_NAME = request.META['SCRIPT_NAME'] if domain is not None: domain += request.META['SCRIPT_NAME'] if domain is not None: if request.is_secure(): settings.BASE_URL = 'https://' + domain else: settings.BASE_URL = 'http://' + domain # FIXME: DIRTY HACK ALERT if this works then something is wrong # with the universe poison sites cache using detected domain from django.contrib.sites import models as sites_models new_site = sites_models.Site(settings.SITE_ID, request.get_host(), settings.POOTLE_TITLE) sites_models.SITE_CACHE[settings.SITE_ID] = new_site
1,431
Python
.py
30
38
78
0.639627
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,106
errorpages.py
translate_pootle/pootle/middleware/errorpages.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 __future__ import print_function import sys import traceback from django.conf import settings from django.core.exceptions import PermissionDenied from django.core.mail import mail_admins from django.http import Http404, HttpResponseForbidden, HttpResponseServerError from django.template.loader import render_to_string from django.urls import reverse from django.utils.deprecation import MiddlewareMixin from django.utils.encoding import force_text try: from raven.contrib.django.models import sentry_exception_handler except ImportError: sentry_exception_handler = None from pootle.core.exceptions import Http400 from pootle.core.http import (JsonResponseBadRequest, JsonResponseForbidden, JsonResponseNotFound, JsonResponseServerError) from pootle.i18n.gettext import ugettext as _ def log_exception(request, exception, tb): if sentry_exception_handler is None: # Send email to admins with details about exception ip_type = (request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS and 'internal' or 'EXTERNAL') msg_args = { 'ip_type': ip_type, 'path': request.path, } subject = 'Error (%(ip_type)s IP): %(path)s' % msg_args try: request_repr = repr(request) except Exception: request_repr = "Request repr() unavailable" msg_args = (unicode(exception.args[0]), tb, request_repr) message = "%s\n\n%s\n\n%s" % msg_args mail_admins(subject, message, fail_silently=True) else: sentry_exception_handler(request=request) def handle_exception(request, exception, template_name): # XXX: remove this? exceptions are already displayed in debug mode tb = traceback.format_exc() print(tb, file=sys.stderr) if settings.DEBUG: return None log_exception(request, exception, tb) msg = force_text(exception) if request.is_ajax(): return JsonResponseServerError({'msg': msg}) ctx = { 'exception': msg, } if hasattr(exception, 'filename'): msg_args = { 'filename': exception.filename, 'errormsg': exception.strerror, } msg = _('Error accessing %(filename)s, Filesystem ' 'sent error: %(errormsg)s', msg_args) ctx['fserror'] = msg return HttpResponseServerError( render_to_string(template_name, context=ctx, request=request) ) class ErrorPagesMiddleware(MiddlewareMixin): """Friendlier error pages.""" def process_exception(self, request, exception): msg = force_text(exception) if isinstance(exception, Http404): if request.is_ajax(): return JsonResponseNotFound({'msg': msg}) elif isinstance(exception, Http400): if request.is_ajax(): return JsonResponseBadRequest({'msg': msg}) elif isinstance(exception, PermissionDenied): if request.is_ajax(): return JsonResponseForbidden({'msg': msg}) ctx = { 'permission_error': msg, } if not request.user.is_authenticated: msg_args = { 'login_link': reverse('account_login'), } login_msg = _( 'You need to <a class="js-login" ' 'href="%(login_link)s">login</a> to access this page.', msg_args ) ctx["login_message"] = login_msg return HttpResponseForbidden( render_to_string('errors/403.html', context=ctx, request=request)) elif (exception.__class__.__name__ in ('OperationalError', 'ProgrammingError', 'DatabaseError')): # HACKISH: Since exceptions thrown by different databases do not # share the same class heirarchy (DBAPI2 sucks) we have to check # the class name instead. Since python uses duck typing I will call # this poking-the-duck-until-it-quacks-like-a-duck-test return handle_exception(request, exception, 'errors/db.html') else: return handle_exception(request, exception, 'errors/500.html')
4,628
Python
.py
109
33.055046
79
0.632562
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,107
urls.py
translate_pootle/pootle/apps/import_export/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 TPOfflineTMView, export urlpatterns = [ url(r"^export/$", export, name="pootle-export"), url(r'^\+\+offline_tm/(?P<language_code>[^/]*)/(?P<project_code>[^/]*)/$', TPOfflineTMView.as_view(), name='pootle-offline-tm-tp'), ]
594
Python
.py
17
31.352941
78
0.677138
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,108
apps.py
translate_pootle/pootle/apps/import_export/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 PootleImportExportConfig(AppConfig): name = "import_export" verbose_name = "Pootle Import Export" def ready(self): importlib.import_module("import_export.providers")
524
Python
.py
14
34.571429
77
0.759921
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,109
utils.py
translate_pootle/pootle/apps/import_export/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 logging import os from io import BytesIO from zipfile import ZipFile from translate.storage import tmx from translate.storage.factory import getclass from django.conf import settings from django.utils.functional import cached_property from pootle.core.delegate import revision from pootle.core.url_helpers import urljoin from pootle.i18n.gettext import ugettext_lazy as _ from pootle_app.models.permissions import check_user_permission from pootle_statistics.models import SubmissionTypes from pootle_store.constants import TRANSLATED from pootle_store.models import Store from .exceptions import (FileImportError, MissingPootlePathError, MissingPootleRevError, UnsupportedFiletypeError) logger = logging.getLogger(__name__) def import_file(f, user=None): ttk = getclass(f)(f.read()) if not hasattr(ttk, "parseheader"): raise UnsupportedFiletypeError(_("Unsupported filetype '%s', only PO " "files are supported at this time\n", f.name)) header = ttk.parseheader() pootle_path = header.get("X-Pootle-Path") if not pootle_path: raise MissingPootlePathError(_("File '%s' missing X-Pootle-Path " "header\n", f.name)) rev = header.get("X-Pootle-Revision") if not rev or not rev.isdigit(): raise MissingPootleRevError(_("File '%s' missing or invalid " "X-Pootle-Revision header\n", f.name)) rev = int(rev) try: store = Store.objects.get(pootle_path=pootle_path) except Store.DoesNotExist as e: raise FileImportError( _("Could not create '%(filename)s'. Missing " "Project/Language? (%(error)s)", dict(filename=f.name, error=e))) tp = store.translation_project allow_add_and_obsolete = ((tp.project.checkstyle == 'terminology' or tp.is_template_project) and check_user_permission(user, 'administrate', tp.directory)) try: store.update(store=ttk, user=user, submission_type=SubmissionTypes.UPLOAD, store_revision=rev, allow_add_and_obsolete=allow_add_and_obsolete) except Exception as e: # This should not happen! logger.error("Error importing file: %s", str(e)) raise FileImportError(_("There was an error uploading your file")) class TPTMXExporter(object): def __init__(self, context): self.context = context @cached_property def exported_revision(self): return revision.get(self.context.__class__)( self.context).get(key="pootle.offline.tm") @cached_property def revision(self): return revision.get(self.context.__class__)( self.context.directory).get(key="stats")[:10] or "0" def get_url(self): if self.exported_revision: relative_path = "offline_tm/%s/%s" % ( self.context.language.code, self.get_filename(self.exported_revision) ) return urljoin(settings.MEDIA_URL, relative_path) return None def update_exported_revision(self): if self.has_changes(): revision.get(self.context.__class__)( self.context).set(keys=["pootle.offline.tm"], value=self.revision) if "exported_revision" in self.__dict__: del self.__dict__["exported_revision"] def has_changes(self): return self.revision != self.exported_revision def file_exists(self): return os.path.exists(self.abs_filepath) @property def last_exported_file_path(self): if not self.exported_revision: return None exported_filename = self.get_filename(self.exported_revision) return os.path.join(self.directory, exported_filename) def exported_file_exists(self): if self.last_exported_file_path is None: return False return os.path.exists(self.last_exported_file_path) @property def directory(self): return os.path.join(settings.MEDIA_ROOT, 'offline_tm', self.context.language.code) def get_filename(self, revision): return ".".join([self.context.project.code, self.context.language.code, revision, 'tmx', 'zip']) def check_tp(self, filename): """Check if filename relates to the context TP.""" return filename.startswith(".".join([ self.context.project.code, self.context.language.code])) @property def filename(self): return self.get_filename(self.revision) @property def abs_filepath(self): return os.path.join(self.directory, self.filename) def export(self, rotate=False): source_language = self.context.project.source_language.code target_language = self.context.language.code if not os.path.exists(self.directory): os.makedirs(self.directory) tmxfile = tmx.tmxfile() for store in self.context.stores.live().iterator(): for unit in store.units.filter(state=TRANSLATED): tmxfile.addtranslation(unit.source, source_language, unit.target, target_language, unit.developer_comment) bs = BytesIO() tmxfile.serialize(bs) with open(self.abs_filepath, "wb") as f: with ZipFile(f, "w") as zf: zf.writestr(self.filename.rstrip('.zip'), bs.getvalue()) last_exported_filepath = self.last_exported_file_path self.update_exported_revision() removed = [] if rotate: for fn in os.listdir(self.directory): # Skip files from other projects. if not self.check_tp(fn): continue filepath = os.path.join(self.directory, fn) if filepath not in [self.abs_filepath, last_exported_filepath]: removed.append(filepath) os.remove(filepath) return self.abs_filepath, removed
6,795
Python
.py
153
32.823529
79
0.603391
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,110
__init__.py
translate_pootle/pootle/apps/import_export/__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 = 'import_export.apps.PootleImportExportConfig'
343
Python
.py
8
41.75
77
0.772455
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,111
providers.py
translate_pootle/pootle/apps/import_export/providers.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from pootle.core.delegate import context_data from pootle.core.plugin import provider from pootle_translationproject.views import TPBrowseView from .utils import TPTMXExporter @provider(context_data, sender=TPBrowseView) def register_context_data(**kwargs): tp = kwargs['view'].tp return dict(has_offline_tm=TPTMXExporter(tp).exported_file_exists())
637
Python
.py
15
40.666667
77
0.789644
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,112
exceptions.py
translate_pootle/pootle/apps/import_export/exceptions.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. class UnsupportedFiletypeError(ValueError): pass class MissingPootlePathError(ValueError): pass class MissingPootleRevError(ValueError): pass class FileImportError(ValueError): pass
481
Python
.py
15
29.466667
77
0.786026
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,113
forms.py
translate_pootle/pootle/apps/import_export/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 class UploadForm(forms.Form): file = forms.FileField(required=True) user_id = forms.ChoiceField( required=False, widget=forms.Select( attrs={'class': 'js-select2'})) def __init__(self, *args, **kwargs): self.uploader_list = kwargs.pop("uploader_list", []) super(UploadForm, self).__init__(*args, **kwargs) self.fields["file"].widget.attrs["id"] = "js-file-upload-input" self.fields["user_id"].choices = self.uploader_list self.fields["user_id"].widget.attrs["id"] = "js-user-upload-input"
873
Python
.py
20
38.45
77
0.669022
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,114
views.py
translate_pootle/pootle/apps/import_export/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 logging import os from io import BytesIO from zipfile import ZipFile, is_zipfile from django.contrib.auth import get_user_model from django.http import Http404, HttpResponse from django.shortcuts import redirect from pootle.core.delegate import language_team from pootle.core.views.base import PootleDetailView from pootle_app.models.permissions import check_permission from pootle_store.models import Store from pootle_translationproject.views import TPDirectoryMixin from .forms import UploadForm from .utils import TPTMXExporter, import_file def download(contents, name, content_type): response = HttpResponse(contents, content_type=content_type) response["Content-Disposition"] = "attachment; filename=%s" % (name) return response def export(request): path = request.GET.get("path") if not path: raise Http404 stores = Store.objects.live().select_related( "data", "filetype__extension", "translation_project", "translation_project__project", "translation_project__language").filter(pootle_path__startswith=path) num_items = stores.count() if not num_items: raise Http404 if num_items == 1: store = stores.get() contents = BytesIO(store.serialize()) name = os.path.basename(store.pootle_path) contents.seek(0) return download(contents.read(), name, "application/octet-stream") # zip all the stores together f = BytesIO() prefix = path.strip("/").replace("/", "-") if not prefix: prefix = "export" with BytesIO() as f: with ZipFile(f, "w") as zf: for store in stores: try: data = store.serialize() except Exception as e: logging.error("Could not serialize %r: %s", store.pootle_path, e) continue zf.writestr(prefix + store.pootle_path, data) return download(f.getvalue(), "%s.zip" % (prefix), "application/zip") def handle_upload_form(request, tp): """Process the upload form.""" valid_extensions = tp.project.filetype_tool.valid_extensions if "po" not in valid_extensions: return {} language = tp.language team = language_team.get(tp.language.__class__)(language) uploader_list = [(request.user.id, request.user.display_name), ] if check_permission('administrate', request): User = get_user_model() uploader_list = [ (user.id, user.display_name) for user in (team.submitters | team.reviewers | team.admins | team.superusers)] if request.method == "POST" and "file" in request.FILES: upload_form = UploadForm( request.POST, request.FILES, uploader_list=uploader_list ) if upload_form.is_valid(): uploader_id = upload_form.cleaned_data["user_id"] django_file = request.FILES["file"] uploader = request.user if uploader_id and uploader_id != uploader.id: User = get_user_model() uploader = User.objects.get( id=upload_form.cleaned_data["user_id"] ) try: if is_zipfile(django_file): with ZipFile(django_file, "r") as zf: for path in zf.namelist(): if path.endswith("/"): # is a directory continue ext = os.path.splitext(path)[1].strip(".") if ext not in valid_extensions: continue with zf.open(path, "r") as f: import_file(f, user=uploader) else: # is_zipfile consumes the file buffer django_file.seek(0) import_file(django_file, user=uploader) except Exception as e: upload_form.add_error("file", e) return { "upload_form": upload_form, } else: return { "upload_form": upload_form, } # Always return a blank upload form unless the upload form is not valid. return { "upload_form": UploadForm( uploader_list=uploader_list, initial=dict(user_id=request.user.id) ), } class TPOfflineTMView(TPDirectoryMixin, PootleDetailView): @property def path(self): return "/%s/%s/" % (self.kwargs['language_code'], self.kwargs['project_code']) def get(self, request, *args, **kwargs): self.object = self.get_object() exporter = TPTMXExporter(self.tp) url = exporter.get_url() if url is not None: return redirect(url) raise Http404
5,287
Python
.py
133
29.06015
82
0.583902
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,115
export.py
translate_pootle/pootle/apps/import_export/management/commands/export.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import os os.environ["DJANGO_SETTINGS_MODULE"] = "pootle.settings" from zipfile import ZipFile from django.core.management.base import CommandError from pootle_app.management.commands import PootleCommand from pootle_language.models import Language from pootle_project.models import Project from pootle_store.models import Store from ...utils import TPTMXExporter class Command(PootleCommand): help = "Export a Project, Translation Project, or path. " \ "Multiple files will be zipped." def add_arguments(self, parser): super(Command, self).add_arguments(parser) group_path_or_tmx = parser.add_mutually_exclusive_group() group_path_or_tmx.add_argument( "--path", action="store", dest="pootle_path", help="Export a single file", ) group_path_or_tmx.add_argument( "--tmx", action="store_true", dest="export_tmx", default=False, help="Export each translation project into a single TMX file", ) parser.add_argument( "--overwrite", action="store_true", default=False, help="Overwrite already exported TMX files", ) parser.add_argument( "--rotate", action="store_true", dest="rotate", default=False, help="Remove old exported TMX files", ) def _create_zip(self, stores, prefix): with open("%s.zip" % (prefix), "wb") as f: with ZipFile(f, "w") as zf: for store in stores: zf.writestr(prefix + store.pootle_path, store.serialize()) self.stdout.write("Created %s\n" % (f.name)) def handle_all(self, **options): if options['pootle_path'] is not None: return self.handle_path(options['pootle_path']) # support exporting an entire project if self.projects and not self.languages and not options['export_tmx']: for project in Project.objects.filter(code__in=self.projects): self.handle_project(project) return # Support exporting an entire language if self.languages and not self.projects and not options['export_tmx']: for language in Language.objects.filter(code__in=self.languages): self.handle_language(language) return return super(Command, self).handle_all(**options) def handle_translation_project(self, translation_project, **options): if options['export_tmx']: exporter = TPTMXExporter(translation_project) if not options['overwrite'] and exporter.file_exists(): self.stdout.write( 'Translation project (%s) has not been changed.' % translation_project) return False filename, removed = exporter.export(rotate=options['rotate']) self.stdout.write('File "%s" has been saved.' % filename) for filename in removed: self.stdout.write('File "%s" has been removed.' % filename) else: stores = translation_project.stores.live() prefix = "%s-%s" % (translation_project.project.code, translation_project.language.code) self._create_zip(stores, prefix) def handle_project(self, project): stores = Store.objects.live().filter( translation_project__project=project) if not stores: raise CommandError("No matches for project '%s'" % (project)) self._create_zip(stores, prefix=project.code) def handle_language(self, language): stores = Store.objects.live().filter( translation_project__language=language) self._create_zip(stores, prefix=language.code) def handle_path(self, path): stores = Store.objects.live().filter(pootle_path__startswith=path) if not stores: raise CommandError("Could not find store matching '%s'" % (path)) if stores.count() == 1: store = stores.get() with open(os.path.basename(store.pootle_path), "wb") as f: f.write(store.serialize()) self.stdout.write("Created '%s'" % (f.name)) return prefix = path.strip("/").replace("/", "-") if not prefix: prefix = "export" self._create_zip(stores, prefix)
4,788
Python
.py
109
33.669725
78
0.610264
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,116
import.py
translate_pootle/pootle/apps/import_export/management/commands/import.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import datetime import os os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings' from zipfile import ZipFile, is_zipfile from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand, CommandError from import_export.utils import import_file class Command(BaseCommand): help = "Import a translation file or a zip of translation files. " \ "X-Pootle-Path header must be present." def add_arguments(self, parser): parser.add_argument( "file", nargs="+", help="file to import" ) parser.add_argument( "--user", action="store", dest="user", help="Import translations as USER", ) def handle(self, **options): user = None if options["user"] is not None: User = get_user_model() try: user = User.objects.get(username=options["user"]) self.stdout.write( 'User %s will be set as author of the import.' % user.username) except User.DoesNotExist: raise CommandError("Unrecognised user: %s" % options["user"]) start = datetime.datetime.now() for filename in options['file']: self.stdout.write('Importing %s...' % filename) if not os.path.isfile(filename): raise CommandError("No such file '%s'" % filename) if is_zipfile(filename): with ZipFile(filename, "r") as zf: for path in zf.namelist(): with zf.open(path, "r") as f: if path.endswith("/"): # is a directory continue try: import_file(f, user=user) except Exception as e: self.stderr.write("Warning: %s" % (e)) else: with open(filename, "r") as f: try: import_file(f, user=user) except Exception as e: raise CommandError(e) end = datetime.datetime.now() self.stdout.write('All done in %s.' % (end - start))
2,624
Python
.py
64
28.09375
77
0.533935
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,117
getters.py
translate_pootle/pootle/apps/pootle_log/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 comparable_event, grouped_events, log from pootle.core.plugin import getter from pootle_store.models import Store, Unit from .utils import ( ComparableLogEvent, GroupedEvents, Log, StoreLog, UnitLog, UserLog) @getter(log, sender=Store) def store_log_getter(**kwargs_): return StoreLog @getter(log, sender=Unit) def unit_log_getter(**kwargs_): return UnitLog @getter(comparable_event, sender=(Log, StoreLog, UnitLog, UserLog)) def comparable_event_getter(**kwargs_): return ComparableLogEvent @getter(grouped_events, sender=(Log, StoreLog, UnitLog)) def grouped_log_events_getter(**kwargs_): return GroupedEvents @getter(log, sender=get_user_model()) def user_log_getter(**kwargs_): return UserLog
1,089
Python
.py
28
36.571429
77
0.773855
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,118
apps.py
translate_pootle/pootle/apps/pootle_log/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 PootleLogConfig(AppConfig): name = "pootle_log" verbose_name = "Pootle Log" version = "0.1.1" def ready(self): importlib.import_module("pootle_log.getters")
519
Python
.py
15
31.6
77
0.736948
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,119
utils.py
translate_pootle/pootle/apps/pootle_log/utils.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django.contrib.auth import get_user_model from django.utils.functional import cached_property from pootle.core.delegate import comparable_event from pootle.core.proxy import BaseProxy from pootle_statistics.models import ( Submission, SubmissionFields, SubmissionTypes) from pootle_store.models import Suggestion, UnitSource class LogEvent(object): def __init__(self, unit, user, timestamp, action, value, old_value=None, revision=None, **kwargs): self.unit = unit self.user = user self.timestamp = timestamp self.action = action self.value = value self.old_value = old_value self.revision = revision class ComparableLogEvent(BaseProxy): _special_names = (x for x in BaseProxy._special_names if x not in ["__lt__", "__gt__", "__call__"]) 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 if self.action == other.action == 'suggestion_created': if self.value.pk > other.value.pk: return 1 elif self.value.pk < other.value.pk: return -1 if self.unit.pk > other.unit.pk: return 1 elif self.unit.pk < other.unit.pk: return -1 return 0 class Log(object): include_meta = False @property def source_qs(self): return UnitSource.objects @property def suggestion_qs(self): return Suggestion.objects.exclude(creation_time__isnull=True) @property def submission_qs(self): return Submission.objects @property def created_units(self): return self.source_qs.select_related("unit", "created_by") @property def suggestions(self): return self.suggestion_qs.select_related( "unit", "user", "reviewer", "state", "unit__unit_source") @property def submissions(self): return self.submission_qs.select_related( "unit", "submitter", "unit__unit_source") @cached_property def event(self): return LogEvent @cached_property def subfields(self): return { getattr(SubmissionFields, n): n.lower() for n in ["SOURCE", "TARGET", "STATE", "COMMENT", "CHECK"]} @cached_property def subtypes(self): return { getattr(SubmissionTypes, n): n.lower() for n in ["WEB", "UPLOAD", "SYSTEM"]} def filter_path(self, qs, path=None, field="unit__store__pootle_path"): return ( qs.filter(**{"%s__startswith" % field: path}) if path is not None else qs) def filter_store(self, qs, store=None, field="unit__store_id"): return ( qs.filter(**{field: store}) if store is not None else qs) def filter_timestamps(self, qs, start=None, end=None, field="creation_time"): if start is not None: qs = qs.filter(**{"%s__gte" % field: start}) if end is not None: qs = qs.filter(**{"%s__lt" % field: end}) return qs def filter_users(self, qs, users=None, field="submitter_id", include_meta=None): if not users: if include_meta is None and self.include_meta or include_meta: return qs else: meta_users = get_user_model().objects.META_USERS return qs.exclude(**{"%s__username__in" % field: meta_users}) return ( qs.filter(**{field: list(users).pop()}) if len(users) == 1 else qs.filter(**{"%s__in" % field: users})) def filtered_suggestions(self, **kwargs): suggestions = self.suggestions added_suggestions = ( self.filter_users( suggestions, kwargs.get("users"), field="user_id", include_meta=kwargs.get("include_meta")) & self.filter_timestamps( suggestions, start=kwargs.get("start"), end=kwargs.get("end"))) reviewed_suggestions = ( self.filter_users( suggestions, kwargs.get("users"), field="reviewer_id", include_meta=kwargs.get("include_meta")) & self.filter_timestamps( suggestions, start=kwargs.get("start"), end=kwargs.get("end"), field="review_time")) suggestions = (added_suggestions | reviewed_suggestions) suggestions = self.filter_store( suggestions, kwargs.get("store")) suggestions = self.filter_path( suggestions, kwargs.get("path")) if kwargs.get("only") and kwargs["only"].get("suggestion"): suggestions = suggestions.only(*kwargs["only"]["suggestion"]) return suggestions def filtered_submissions(self, **kwargs): ordered = kwargs.get("ordered", True) submissions = ( self.filter_users( self.submissions, kwargs.get("users"), include_meta=kwargs.get("include_meta"))) submissions = self.filter_path( submissions, kwargs.get("path")) submissions = ( self.filter_timestamps( submissions, start=kwargs.get("start"), end=kwargs.get("end"))) submissions = self.filter_store( submissions, kwargs.get("store")) if kwargs.get("only") and kwargs["only"].get("submission"): submissions = submissions.only(*kwargs["only"]["submission"]) if ordered is False: submissions = submissions.order_by() return submissions def filtered_created_units(self, **kwargs): created_units = self.filter_store( self.created_units, kwargs.get("store")) created_units = self.filter_users( created_units, kwargs.get("users"), field="created_by_id", include_meta=kwargs.get("include_meta")) created_units = self.filter_path( created_units, kwargs.get("path")) created_units = self.filter_timestamps( created_units, start=kwargs.get("start"), end=kwargs.get("end"), field="unit__creation_time") return created_units def get_created_unit_events(self, **kwargs): for created_unit in self.filtered_created_units(**kwargs): yield self.event( created_unit.unit, created_unit.created_by, created_unit.unit.creation_time, "unit_created", created_unit) def get_submission_events(self, **kwargs): for submission in self.filtered_submissions(**kwargs): event_name = "state_changed" if submission.field == SubmissionFields.CHECK: event_name = ( "check_muted" if submission.new_value == "0" else "check_unmuted") elif submission.field == SubmissionFields.TARGET: event_name = "target_updated" elif submission.field == SubmissionFields.SOURCE: event_name = "source_updated" elif submission.field == SubmissionFields.COMMENT: event_name = "comment_updated" yield self.event( submission.unit, submission.submitter, submission.creation_time, event_name, submission, revision=submission.revision) def get_suggestion_events(self, **kwargs): users = kwargs.get("users") for suggestion in self.filtered_suggestions(**kwargs): add_event = ( ((not kwargs.get("start") or (suggestion.creation_time and suggestion.creation_time >= kwargs.get("start"))) and (not kwargs.get("end") or (suggestion.creation_time and suggestion.creation_time < kwargs.get("end"))) and (not users or (suggestion.user_id in users)))) review_event = ( not suggestion.is_pending and ((not kwargs.get("start") or (suggestion.review_time and suggestion.review_time >= kwargs.get("start"))) and (not kwargs.get("end") or (suggestion.review_time and suggestion.review_time < kwargs.get("end"))) and (not users or (suggestion.reviewer_id in users)))) if add_event: yield self.event( suggestion.unit, suggestion.user, suggestion.creation_time, "suggestion_created", suggestion) if review_event: event_name = ( "suggestion_accepted" if suggestion.is_accepted else "suggestion_rejected") yield self.event( suggestion.unit, suggestion.reviewer, suggestion.review_time, event_name, suggestion) def get_events(self, **kwargs): event_sources = kwargs.pop("event_sources", ("submission", "suggestion", "unit_source")) if "unit_source" in event_sources: for event in self.get_created_unit_events(**kwargs): yield event if "suggestion" in event_sources: for event in self.get_suggestion_events(**kwargs): yield event if "submission" in event_sources: for event in self.get_submission_events(**kwargs): yield event class StoreLog(Log): include_meta = True def __init__(self, store): self.store = store @property def created_units(self): return super( StoreLog, self).created_units.filter(unit__store_id=self.store.id) @property def suggestions(self): return super( StoreLog, self).suggestions.filter(unit__store_id=self.store.id) @property def submissions(self): return super( StoreLog, self).submissions.filter(unit__store_id=self.store.id) def filter_store(self, qs, store=None, field="unit__store_id"): return qs class UnitLog(Log): include_meta = True def __init__(self, unit): self.unit = unit @property def created_units(self): return super( UnitLog, self).created_units.filter(unit_id=self.unit.id) @property def suggestions(self): return super( UnitLog, self).suggestions.filter(unit_id=self.unit.id) @property def submissions(self): return super( UnitLog, self).submissions.filter(unit_id=self.unit.id) def filter_store(self, qs, store=None, field="unit__store_id"): return qs class GroupedEvents(object): def __init__(self, log): self.log = log def sorted_events(self, start=None, end=None, users=None, reverse=False): comparable_event_class = comparable_event.get(self.log.__class__) events = sorted( (comparable_event_class(x) for x in self.log.get_events(start=start, end=end, users=users)), reverse=reverse) for event in events: yield event class UserLog(Log): def __init__(self, user): self.user = user @property def source_qs(self): return self.user.created_units @property def suggestion_qs(self): return ( self.user.suggestions.exclude(creation_time__isnull=True).all() | self.user.reviews.all()) @property def submission_qs(self): return self.user.submission_set
13,235
Python
.py
336
27.571429
81
0.559579
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,120
__init__.py
translate_pootle/pootle/apps/pootle_log/__init__.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. default_app_config = 'pootle_log.apps.PootleLogConfig'
331
Python
.py
8
40.25
77
0.763975
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,121
models.py
translate_pootle/pootle/apps/pootle_project/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 os import shutil from collections import OrderedDict from translate.filters import checks from django.conf import settings from django.contrib.contenttypes.fields import GenericRelation from django.core.cache import cache from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.db import models from django.db.models import Q from django.db.models.signals import post_delete, post_save from django.dispatch import receiver from django.urls import reverse from django.utils.encoding import iri_to_uri from django.utils.functional import cached_property from sortedm2m.fields import SortedManyToManyField from pootle.core.cache import make_method_key from pootle.core.delegate import data_tool, filetype_tool, lang_mapper, tp_tool from pootle.core.mixins import CachedTreeItem from pootle.core.models import VirtualResource from pootle.core.url_helpers import get_editor_filter, split_pootle_path from pootle.i18n.gettext import ugettext_lazy as _ from pootle_app.models.directory import Directory from pootle_app.models.permissions import PermissionSet from pootle_config.utils import ObjectConfig from pootle_format.models import Format from pootle_format.utils import ProjectFiletypes from pootle_revision.models import Revision from staticpages.models import StaticPage RESERVED_PROJECT_CODES = ('admin', 'translate', 'settings') PROJECT_CHECKERS = { "standard": checks.StandardChecker, "minimal": checks.MinimalChecker, "reduced": checks.ReducedChecker, "openoffice": checks.OpenOfficeChecker, "libreoffice": checks.LibreOfficeChecker, "mozilla": checks.MozillaChecker, "kde": checks.KdeChecker, "wx": checks.KdeChecker, "gnome": checks.GnomeChecker, "creativecommons": checks.CCLicenseChecker, "drupal": checks.DrupalChecker, "terminology": checks.TermChecker, "l20n": checks.L20nChecker, } class ProjectManager(models.Manager): def create(self, *args, **kwargs): filetype_names = kwargs.pop("filetypes", ["po"]) filetypes = { ft.name: ft for ft in Format.objects.filter(name__in=filetype_names)} project = super(ProjectManager, self).create(*args, **kwargs) for filetype in filetype_names: if filetypes.get(filetype): project.filetypes.add(filetypes[filetype]) project.config["pootle_fs.fs_type"] = kwargs.pop("fs_type", "localfs") if project.config["pootle_fs.fs_type"] == "localfs": project.config["pootle_fs.fs_url"] = kwargs.pop( "fs_url", "{POOTLE_TRANSLATION_DIRECTORY}%s" % project.code) return project def get_or_create(self, *args, **kwargs): project, created = super( ProjectManager, self).get_or_create(*args, **kwargs) if created and not project.filetypes.count(): project.filetypes.add(Format.objects.get(name="po")) return project, created def cached_dict(self, user): """Return a cached ordered dictionary of projects tuples for `user`. - Admins always get all projects. - Regular users only get enabled projects accessible to them. :param user: The user for whom projects need to be retrieved for. :return: An ordered dictionary of project tuples including (`fullname`, `disabled`) and `code` is a key in the dictionary. """ if not user.is_superuser: cache_params = {'username': user.username} else: cache_params = {'is_admin': user.is_superuser} cache_key = iri_to_uri(make_method_key('Project', 'cached_dict', cache_params)) projects = cache.get(cache_key) if not projects: projects_dict = self.for_user(user).order_by('fullname') \ .values('code', 'fullname', 'disabled') projects = OrderedDict( (project.pop('code'), project) for project in projects_dict ) cache.set(cache_key, projects, settings.POOTLE_CACHE_TIMEOUT) return projects def enabled(self): return self.filter(disabled=False) def get_for_user(self, project_code, user): """Gets a `project_code` project for a specific `user`. - Admins can get the project even if it's disabled. - Regular users only get a project if it's not disabled and it is accessible to them. :param project_code: The code of the project to retrieve. :param user: The user for whom the project needs to be retrieved. :return: The `Project` matching the params, raises otherwise. """ if user.is_superuser: return self.get(code=project_code) return self.for_user(user).get(code=project_code) def for_user(self, user): """Filters projects for a specific user. - Admins always get all projects. - Regular users only get enabled projects accessible to them. :param user: The user for whom the projects need to be retrieved for. :return: A filtered queryset with `Project`s for `user`. """ if user.is_superuser: return self.all() return self.enabled().filter(code__in=Project.accessible_by_user(user)) class ProjectURLMixin(object): """Mixin class providing URL methods to be shared across project-related classes. """ def get_absolute_url(self): proj_code = split_pootle_path(self.pootle_path)[1] if proj_code is not None: pattern_name = 'pootle-project-browse' pattern_args = [proj_code, ''] else: pattern_name = 'pootle-projects-browse' pattern_args = [] return reverse(pattern_name, args=pattern_args) def get_translate_url(self, **kwargs): proj_code, dir_path, filename = split_pootle_path(self.pootle_path)[1:] if proj_code is not None: pattern_name = 'pootle-project-translate' pattern_args = [proj_code, dir_path, filename] else: pattern_name = 'pootle-projects-translate' pattern_args = [] return u''.join([ reverse(pattern_name, args=pattern_args), get_editor_filter(**kwargs), ]) def validate_not_reserved(value): if value in RESERVED_PROJECT_CODES: raise ValidationError( _('"%(code)s" cannot be used as a project code'), params={'code': value}, ) def validate_project_checker(value): if value not in PROJECT_CHECKERS.keys(): raise ValidationError( # Translators: this refers to the project quality checker _('"%(code)s" cannot be used as a project checker'), params={'code': value}, ) class Project(models.Model, CachedTreeItem, ProjectURLMixin): code_help_text = _('A short code for the project. This should only ' 'contain ASCII characters, numbers, and the underscore ' '(_) character.') # any changes to the `code` field may require updating the schema # see migration 0003_case_sensitive_schema.py code = models.CharField(max_length=255, null=False, unique=True, db_index=True, verbose_name=_('Code'), blank=False, validators=[validate_not_reserved], help_text=code_help_text) fullname = models.CharField(max_length=255, null=False, blank=False, verbose_name=_("Full Name")) checkstyle = models.CharField( max_length=50, default='standard', null=False, validators=[validate_project_checker], verbose_name=_('Quality Checks')) filetypes = SortedManyToManyField(Format) source_language = models.ForeignKey( 'pootle_language.Language', db_index=True, verbose_name=_('Source Language'), on_delete=models.CASCADE) ignoredfiles = models.CharField( max_length=255, blank=True, null=False, default="", verbose_name=_('Ignore Files')) directory = models.OneToOneField( 'pootle_app.Directory', db_index=True, editable=False, on_delete=models.CASCADE) report_email = models.EmailField( max_length=254, blank=True, verbose_name=_("Errors Report Email"), help_text=_('An email address where issues with the source text ' 'can be reported.')) screenshot_search_prefix = models.URLField( # Translators: This is the URL prefix to search for context screenshots blank=True, null=True, verbose_name=_('Screenshot Search Prefix')) creation_time = models.DateTimeField(auto_now_add=True, db_index=True, editable=False, null=True) disabled = models.BooleanField(verbose_name=_('Disabled'), default=False) revisions = GenericRelation(Revision) objects = ProjectManager() class Meta(object): ordering = ['code'] db_table = 'pootle_app_project' @classmethod def accessible_by_user(cls, user): """Returns a list of project codes accessible by `user`. Checks for explicit `view` permissions for `user`, and extends them with the `default` (if logged-in) and `nobody` users' `view` permissions. Negative `hide` permissions are also taken into account and they'll forbid project access as far as there's no `view` permission set at the same level for the same user. :param user: The ``User`` instance to get accessible projects for. """ if user.is_superuser: key = iri_to_uri('projects:all') else: username = user.username key = iri_to_uri('projects:accessible:%s' % username) user_projects = cache.get(key, None) if user_projects is not None: return user_projects # FIXME: use `cls.objects.cached_dict().keys()` ALL_PROJECTS = cls.objects.values_list('code', flat=True) if user.is_superuser: user_projects = ALL_PROJECTS else: ALL_PROJECTS = set(ALL_PROJECTS) if user.is_anonymous: allow_usernames = [username] forbid_usernames = [username, 'default'] else: allow_usernames = list(set([username, 'default', 'nobody'])) forbid_usernames = list(set([username, 'default'])) # Check root for `view` permissions root_permissions = PermissionSet.objects.filter( directory__pootle_path='/', user__username__in=allow_usernames, positive_permissions__codename='view', ) if root_permissions.count(): user_projects = ALL_PROJECTS else: user_projects = set() # Check specific permissions at the project level accessible_projects = cls.objects.filter( directory__permission_sets__positive_permissions__codename='view', directory__permission_sets__user__username__in=allow_usernames, ).values_list('code', flat=True) forbidden_projects = cls.objects.filter( directory__permission_sets__negative_permissions__codename='hide', directory__permission_sets__user__username__in=forbid_usernames, ).values_list('code', flat=True) allow_projects = set(accessible_projects) forbid_projects = set(forbidden_projects) - allow_projects user_projects = (user_projects.union( allow_projects)).difference(forbid_projects) user_projects = list(user_projects) cache.set(key, user_projects, settings.POOTLE_CACHE_TIMEOUT) return user_projects @cached_property def data_tool(self): return data_tool.get(self.__class__)(self) # # # # # # # # # # # # # # Properties # # # # # # # # # # # # # # # # # # @cached_property def config(self): return ObjectConfig(self) @cached_property def filetype_tool(self): return filetype_tool.get(self.__class__)(self) @cached_property def lang_mapper(self): return lang_mapper.get(self.__class__, instance=self) @cached_property def tp_tool(self): return tp_tool.get(self.__class__)(self) @property def local_fs_path(self): return os.path.join(settings.POOTLE_FS_WORKING_PATH, self.code) @property def name(self): return self.fullname @property def pootle_path(self): return "/projects/" + self.code + "/" @property def is_terminology(self): """Returns ``True`` if this project is a terminology project.""" return self.checkstyle == 'terminology' @cached_property def languages(self): """Returns a list of active :cls:`~pootle_languages.models.Language` objects for this :cls:`~pootle_project.models.Project`. """ from pootle_language.models import Language # FIXME: we should better have a way to automatically cache models with # built-in invalidation -- did I hear django-cache-machine? return Language.objects.filter(Q(translationproject__project=self), ~Q(code='templates')) # # # # # # # # # # # # # # Methods # # # # # # # # # # # # # # # # # # # def __unicode__(self): return self.fullname def save(self, *args, **kwargs): self.fullname = self.fullname.strip() self.code = self.code.strip() # Force validation of fields. self.full_clean() self.directory = Directory.objects.projects \ .get_or_make_subdir(self.code) super(Project, self).save(*args, **kwargs) def delete(self, *args, **kwargs): if os.path.exists(self.local_fs_path): shutil.rmtree(self.local_fs_path) directory = self.directory # Just doing a plain delete will collect all related objects in memory # before deleting: translation projects, stores, units, quality checks, # pootle_store suggestions, pootle_app suggestions and submissions. # This can easily take down a process. If we do a translation project # at a time and force garbage collection, things stay much more # managable. import gc gc.collect() for tp in self.translationproject_set.iterator(): tp.delete() gc.collect() super(Project, self).delete(*args, **kwargs) directory.delete() @property def is_gnustyle(self): mapping = self.config[ "pootle_fs.translation_mappings"]["default"] return bool( "/" not in mapping[ mapping.rfind("<language_code>") + 15:]) # # # TreeItem def get_children(self): return self.translationproject_set.live() # # # /TreeItem def get_children_for_user(self, user, select_related=None): """Returns children translation projects for a specific `user`.""" return ( self.translationproject_set.for_user(user, select_related) .select_related("language")) def get_announcement(self, user=None): """Return the related announcement, if any.""" return StaticPage.get_announcement_for(self.pootle_path, user) def is_accessible_by(self, user): """Returns `True` if the current project is accessible by `user`. """ if user.is_superuser: return True return self.code in Project.accessible_by_user(user) def file_belongs_to_project(self, filename, match_templates=True): """Tests if ``filename`` matches project filetype (ie. extension). If ``match_templates`` is ``True``, this will also check if the file matches the template filetype. """ ext = os.path.splitext(filename)[1][1:] filetypes = ProjectFiletypes(self) return ( ext in filetypes.filetype_extensions or (match_templates and ext in filetypes.template_extensions)) def get_template_translationproject(self): """Returns the translation project that will be used as a template for this project. First it tries to retrieve the translation project that has the special 'templates' language within this project, otherwise it falls back to the source language set for current project. """ try: return self.translationproject_set.get(language__code='templates') except ObjectDoesNotExist: try: return self.translationproject_set \ .get(language=self.source_language_id) except ObjectDoesNotExist: pass class ProjectResource(VirtualResource, ProjectURLMixin): def __eq__(self, other): return ( self.pootle_path == other.pootle_path and list(self.get_children()) == list(other.get_children())) @cached_property def data_tool(self): return data_tool.get(self.__class__)(self) def get_children_for_user(self, user, select_related=None): if select_related: return self.children.select_related(*select_related) return self.children class ProjectSet(VirtualResource, ProjectURLMixin): def __eq__(self, other): return ( self.pootle_path == other.pootle_path and list(self.get_children()) == list(other.get_children())) def __init__(self, resources, *args, **kwargs): self.directory = Directory.objects.projects super(ProjectSet, self).__init__(resources, self.directory.pootle_path) @cached_property def data_tool(self): return data_tool.get(self.__class__)(self) @receiver([post_delete, post_save]) def invalidate_accessible_projects_cache(**kwargs): instance = kwargs["instance"] # XXX: maybe use custom signals or simple function calls? if (instance.__class__.__name__ not in ['Project', 'TranslationProject', 'PermissionSet']): return cache.delete_pattern(make_method_key('Project', 'cached_dict', '*')) cache.delete('projects:all') cache.delete_pattern('projects:accessible:*')
18,947
Python
.py
413
36.377724
82
0.635362
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,122
getters.py
translate_pootle/pootle/apps/pootle_project/getters.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from pootle.core.delegate import lang_mapper, paths from pootle.core.plugin import getter from .lang_mapper import ProjectLanguageMapper from .models import Project from .utils import ProjectPaths @getter(lang_mapper, sender=Project) def get_lang_mapper(**kwargs): return ProjectLanguageMapper(kwargs["instance"]) @getter(paths, sender=Project) def get_project_paths(**kwargs): return ProjectPaths
687
Python
.py
18
36.388889
77
0.793363
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,123
lang_mapper.py
translate_pootle/pootle/apps/pootle_project/lang_mapper.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import logging from collections import OrderedDict from django.utils.functional import cached_property from django.utils.lru_cache import lru_cache from pootle_config.utils import SiteConfig from pootle_language.models import Language logger = logging.getLogger(__name__) class ProjectLanguageMapper(object): """For a given code find the relevant Pootle lang taking account of any lang mapping configuration. Presets can be defined with a dictionary of named mappings on the site_config `pootle.core.lang_mapping_presets`. Presets are enabled with a list on the project_config `pootle.core.use_lang_mapping_presets`. Lang mappings can also be configured per-project using the config setting `pootle.core.lang_mapping`, which should be a k, v dictionary of upstream_code, pootle_code. This will override any mappings in configured presets. """ def __init__(self, project): self.project = project def __getitem__(self, k): return self.get_lang(k) def __contains__(self, k): return self.get_lang(k) and True or False @cached_property def site_config(self): return SiteConfig() @property def site_presets(self): """Get the pret mappings from the site config""" return OrderedDict( self.site_config.get( "pootle.core.lang_mapping_presets", {})) @property def project_presets(self): """Get the projects mapping from the Project.config""" return self.project.config.get( "pootle.core.use_lang_mapping_presets", []) @property def project_mappings(self): """Get the projects mapping from the Project.config""" return OrderedDict( self.project.config.get( "pootle.core.lang_mapping", {})) @property def mappings_from_presets(self): mappings = OrderedDict() for preset_name in self.project_presets: if preset_name not in self.site_presets: logger.warning( "Unrecognised lang mapping preset: %s", preset_name) continue mappings.update(self.site_presets[preset_name]) return mappings @cached_property def lang_mappings(self): """Language mappings after Project.config and presets are parsed""" return self._parse_mappings() @cached_property def all_languages(self): return { lang.code: lang for lang in Language.objects.all()} @lru_cache() def get_lang(self, upstream_code): """Return a `Language` for a given code after mapping""" try: return self.all_languages[self.get_pootle_code(upstream_code)] except KeyError: return None def get_pootle_code(self, upstream_code): """Returns a pootle code for a given upstream code""" if upstream_code in self.lang_mappings: return self.lang_mappings[upstream_code] if upstream_code not in self.lang_mappings.values(): return upstream_code def get_upstream_code(self, pootle_code): """Returns an upstream code for a given pootle code""" for _upstream_code, _pootle_code in self.lang_mappings.items(): if pootle_code == _pootle_code: return _upstream_code if pootle_code not in self.lang_mappings: return pootle_code def _add_lang_to_mapping(self, upstream_code, pootle_code): # as its a 1 to 1 mapping remove any previous items with # same value if pootle_code in self._mapping.values(): for k, v in self._mapping.items(): if v == pootle_code: del self._mapping[k] break self._mapping[upstream_code] = pootle_code def _parse_mappings(self): self._mapping = OrderedDict() mappings = self.mappings_from_presets mappings.update(self.project_mappings) for upstream_code, pootle_code in mappings.items(): self._add_lang_to_mapping(upstream_code, pootle_code) return self._mapping
4,467
Python
.py
108
33.046296
81
0.652896
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,124
urls.py
translate_pootle/pootle/apps/pootle_project/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 ( ProjectAdminView, ProjectBrowseView, ProjectPathsJSON, ProjectsBrowseView, ProjectsTranslateView, ProjectTranslateView, project_admin_permissions) urlpatterns = [ # All projects url(r'^$', ProjectsBrowseView.as_view(), name='pootle-projects-browse'), url(r'^translate/$', ProjectsTranslateView.as_view(), name='pootle-projects-translate'), url(r'^(?P<project_code>[^/]*)' r'/paths/', ProjectPathsJSON.as_view(), name='pootle-project-paths'), # Admin url(r'^(?P<project_code>[^/]*)/admin/languages/$', ProjectAdminView.as_view(), name='pootle-project-admin-languages'), url(r'^(?P<project_code>[^/]*)/admin/permissions/$', project_admin_permissions, name='pootle-project-admin-permissions'), # Specific project url(r'^(?P<project_code>[^/]*)/translate/' r'(?P<dir_path>(.*/)*)(?P<filename>.*\.*)?$', ProjectTranslateView.as_view(), name='pootle-project-translate'), url(r'^(?P<project_code>[^/]*)/' r'(?P<dir_path>(.*/)*)(?P<filename>.*\.*)?$', ProjectBrowseView.as_view(), name='pootle-project-browse') ]
1,527
Python
.py
40
32.35
78
0.641407
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,125
apps.py
translate_pootle/pootle/apps/pootle_project/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 PootleProjectConfig(AppConfig): name = "pootle_project" verbose_name = "Pootle Project" version = "0.1.5" def ready(self): importlib.import_module("pootle_project.getters") importlib.import_module("pootle_project.receivers")
595
Python
.py
16
33.8125
77
0.743455
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,126
receivers.py
translate_pootle/pootle/apps/pootle_project/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.dispatch import receiver from pootle.core.signals import config_updated, update_revisions from pootle_project.models import Project @receiver(config_updated, sender=Project) def config_updated_handler(**kwargs): if kwargs["instance"] and kwargs["key"] == "pootle.core.lang_mapping": update_revisions.send( Project, instance=kwargs["instance"], keys=["stats"])
699
Python
.py
17
37.058824
77
0.728614
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,127
utils.py
translate_pootle/pootle/apps/pootle_project/utils.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from pootle.core.paths import Paths from pootle_store.models import Store from .apps import PootleProjectConfig class ProjectPaths(Paths): ns = "pootle.project" sw_version = PootleProjectConfig.version @property def store_qs(self): return Store.objects.filter( translation_project__project_id=self.context.id)
626
Python
.py
17
33.411765
77
0.753311
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,128
__init__.py
translate_pootle/pootle/apps/pootle_project/__init__.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. default_app_config = 'pootle_project.apps.PootleProjectConfig'
339
Python
.py
8
41.25
77
0.769697
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,129
forms.py
translate_pootle/pootle/apps/pootle_project/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.db import connection from django.forms.models import BaseModelFormSet from django_rq.queues import get_queue from pootle.core.utils.db import useable_connection from pootle.i18n.gettext import ugettext as _ from pootle_config.utils import ObjectConfig from pootle_language.models import Language from pootle_misc.forms import LiberalModelChoiceField from pootle_project.models import Project from pootle_translationproject.models import TranslationProject from pootle_translationproject.signals import (tp_init_failed_async, tp_inited_async) def update_translation_project(tp, response_url): """Wraps translation project initializing to allow it to be running as RQ job. """ try: with useable_connection(): tp.init_from_templates() except Exception as e: tp_init_failed_async.send(sender=tp.__class__, instance=tp) raise e tp_inited_async.send(sender=tp.__class__, instance=tp, response_url=response_url) class TranslationProjectFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): self.response_url = kwargs.pop("response_url") super(TranslationProjectFormSet, self).__init__(*args, **kwargs) self.queryset = self.queryset.select_related("language", "project") def save_new(self, form, commit=True): return form.save( response_url=self.response_url, commit=commit) def delete_existing(self, tp, commit=True): config = ObjectConfig(tp.project) mapping = config.get("pootle.core.lang_mapping", {}) if tp.language.code in mapping: del mapping[tp.language.code] config["pootle.core.lang_mapping"] = mapping super(TranslationProjectFormSet, self).delete_existing( tp, commit=commit) class TranslationProjectForm(forms.ModelForm): language = LiberalModelChoiceField( label=_("Language"), queryset=Language.objects.all(), widget=forms.Select( attrs={ 'class': 'js-select2 select2-language'})) project = forms.ModelChoiceField( queryset=Project.objects.all(), widget=forms.HiddenInput()) fs_code = forms.CharField( label=_("Filesystem language code"), required=False) class Meta(object): prefix = "existing_language" model = TranslationProject fields = ('language', 'project') def __init__(self, *args, **kwargs): """If this form is not bound, it must be called with an initial value for Project. """ super(TranslationProjectForm, self).__init__(*args, **kwargs) if kwargs.get("instance"): project_id = kwargs["instance"].project.pk project = kwargs["instance"].project language = kwargs["instance"].language mappings = project.config.get("pootle.core.lang_mapping", {}) mappings = dict((v, k) for k, v in mappings.iteritems()) mapped = mappings.get(language.code) self.fields["fs_code"].initial = mapped else: project_id = kwargs["initial"]["project"] self.fields["language"].queryset = ( self.fields["language"].queryset.exclude( translationproject__project_id=project_id)) self.fields["project"].queryset = self.fields[ "project"].queryset.filter(pk=project_id) def clean(self): project = self.cleaned_data.get("project") language = self.cleaned_data.get("language") if project and language: mapped_code = self.cleaned_data["fs_code"] mapping = project.config.get("pootle.core.lang_mapping", {}) if mapped_code: tps = project.translationproject_set.all() lang_codes = tps.values_list("language__code", flat=True) bad_fs_code = ( (mapped_code in mapping.keys() and not mapping.get(mapped_code) == language.code) or mapped_code in lang_codes) if bad_fs_code: self.errors["fs_code"] = self.error_class( [_("Unable to add mapped code '%(mapped_code)s' for " "language '%(code)s'. Mapped filesystem codes must " "be unique and cannot be in use with an existing " "Translation Project") % dict(mapped_code=mapped_code, code=language.code)]) if language.code in mapping.keys(): self.errors["language"] = self.error_class( [_("Unable to add language '%s'. " "Another language is already mapped to this code") % language.code]) def save(self, response_url=None, commit=True): tp = self.instance initialize_from_templates = False if tp.id is None: initialize_from_templates = tp.can_be_inited_from_templates() tp = super(TranslationProjectForm, self).save(commit) project = tp.project config = ObjectConfig(project) mappings = config.get("pootle.core.lang_mapping", {}) mappings = dict((v, k) for k, v in mappings.iteritems()) if not self.cleaned_data["fs_code"]: if tp.language.code in mappings: del mappings[tp.language.code] else: mappings[tp.language.code] = self.cleaned_data["fs_code"] config["pootle.core.lang_mapping"] = dict( (v, k) for k, v in mappings.iteritems()) if initialize_from_templates: def _enqueue_job(): queue = get_queue('default') queue.enqueue( update_translation_project, tp, response_url) connection.on_commit(_enqueue_job) return tp
6,315
Python
.py
137
35.277372
79
0.611201
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,130
views.py
translate_pootle/pootle/apps/pootle_project/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 posixpath from django.contrib import messages from django.forms.models import modelformset_factory from django.http import Http404 from django.shortcuts import get_object_or_404 from django.urls import reverse from django.utils.functional import cached_property from django.utils.html import escape from django.utils.lru_cache import lru_cache from django.utils.safestring import mark_safe from pootle.core.browser import ( make_language_item, make_project_list_item, make_xlanguage_item) from pootle.core.decorators import ( get_path_obj, permission_required, persistent_property) from pootle.core.helpers import get_sidebar_announcements_context from pootle.core.paginator import paginate from pootle.core.url_helpers import split_pootle_path from pootle.core.views import ( PootleAdminView, PootleBrowseView, PootleTranslateView) from pootle.core.views.paths import PootlePathsJSON from pootle.i18n.gettext import ugettext as _ from pootle_app.models import Directory from pootle_app.views.admin import util from pootle_app.views.admin.permissions import admin_permissions from pootle_misc.util import cmp_by_last_activity from pootle_project.forms import TranslationProjectForm from pootle_store.models import Store from pootle_translationproject.models import TranslationProject from .apps import PootleProjectConfig from .forms import TranslationProjectFormSet from .models import Project, ProjectResource, ProjectSet class ProjectPathsJSON(PootlePathsJSON): @cached_property def context(self): return get_object_or_404( Project.objects.all(), code=self.kwargs["project_code"]) class ProjectMixin(object): ns = "pootle.project" sw_version = PootleProjectConfig.version model = Project browse_url_path = "pootle-project-browse" translate_url_path = "pootle-project-translate" template_extends = 'projects/base.html' @property def ctx_path(self): return "/projects/%s/" % self.project.code @property def permission_context(self): return self.project.directory @cached_property def project(self): project = get_object_or_404( Project.objects.select_related("directory"), code=self.kwargs["project_code"]) if project.disabled and not self.request.user.is_superuser: raise Http404 return project @cached_property def cache_key(self): return ( "%s.%s.%s.%s::%s.%s.%s" % (self.page_name, self.view_name, self.project.data_tool.cache_key, self.kwargs["dir_path"], self.kwargs["filename"], self.show_all, self.request_lang)) @property def url_kwargs(self): return { "project_code": self.project.code, "dir_path": self.kwargs["dir_path"], "filename": self.kwargs["filename"]} def get_object(self): return self.object @cached_property def object(self): return self.object_with_children @persistent_property def object_with_children(self): if not (self.kwargs["dir_path"] or self.kwargs["filename"]): return self.project tp_path = ( "/%s%s" % (self.kwargs['dir_path'], self.kwargs['filename'])) if not self.kwargs["filename"]: dirs = Directory.objects.live().filter(tp__project=self.project) if self.kwargs['dir_path'].count("/"): dirs = dirs.select_related( "parent", "tp", "tp__language") resources = ( dirs.filter(tp_path=tp_path)) else: resources = ( Store.objects.live() .select_related("translation_project__language") .filter(translation_project__project=self.project) .filter(tp_path=tp_path)) if resources: return ProjectResource( resources, ("/projects/%(project_code)s/%(dir_path)s%(filename)s" % self.kwargs), context=self.project) raise Http404 @property def resource_path(self): return "%(dir_path)s%(filename)s" % self.kwargs class ProjectBrowseView(ProjectMixin, PootleBrowseView): view_name = "project" @property def is_templates_context(self): # this view is a "template context" only when # its a single .pot file or similar return ( len(self.object_children) == 1 and self.object_children[0]["code"] == "templates") @property def pootle_path(self): return self.object.pootle_path @property def permission_context(self): return self.project.directory @cached_property def sidebar_announcements(self): return get_sidebar_announcements_context( self.request, (self.project, )) @property def score_context(self): return self.project @property def url_kwargs(self): return self.kwargs @cached_property def object_children(self): item_func = ( make_xlanguage_item if (self.kwargs['dir_path'] or self.kwargs['filename']) else make_language_item) items = [ item_func(item) for item in self.object.get_children_for_user(self.request.user) ] items = self.add_child_stats(items) items.sort(cmp_by_last_activity) return items class ProjectTranslateView(ProjectMixin, PootleTranslateView): required_permission = "administrate" @property def pootle_path(self): return self.object.pootle_path class ProjectAdminView(PootleAdminView): queryset = Project.objects.select_related("directory") slug_field = 'code' slug_url_kwarg = 'project_code' template_name = 'projects/admin/languages.html' msg_form_error = _( "There are errors in the form. Please review " "the problems below.") model_formset_class = TranslationProject form_class = TranslationProjectForm msg = "" @cached_property def formset_class(self): return modelformset_factory( self.model_formset_class, formset=TranslationProjectFormSet, form=self.form_class, **dict( can_delete=True, extra=self.formset_extra, fields=["language", "project"])) @property def formset_extra(self): return ( self.object.get_template_translationproject() is not None) @property def form_initial(self): return [dict(project=self.object.pk)] @property def page(self): return paginate(self.request, self.qs) @property def qs(self): return self.model_formset_class.objects.filter( project=self.object).order_by('pootle_path') @property def response_url(self): return self.request.build_absolute_uri('/') @property def url_kwargs(self): return { 'project_code': self.object.code, 'dir_path': '', 'filename': ''} def get_context_data(self, **kwargs_): if self.request.method == 'POST' and self.request.POST: self.process_formset() formset = self.get_formset() template_path = "" layout_style = None if not self.formset_extra: layout_style = "nongnu" template_path = self.object.lang_mapper.get_upstream_code("templates") if self.object.is_gnustyle: layout_style = "gnu" mapping = self.object.config[ "pootle_fs.translation_mappings"]["default"] mapping_root, __ = posixpath.splitext(posixpath.basename(mapping)) template_path = mapping_root.replace( "<language_code>", template_path) template_extensions = self.object.filetypes.values_list( "template_extension__name", flat=True) template_path = ", ".join( ('"%(template_name)s.%(extension)s"' % dict( template_name=template_path, extension=ext)) for ext in template_extensions) else: template_path = '"%s"' % template_path return { 'page': 'admin-languages', 'browse_url': ( reverse( 'pootle-project-browse', kwargs=self.url_kwargs)), 'translate_url': ( reverse( 'pootle-project-translate', kwargs=self.url_kwargs)), 'project': { 'code': self.object.code, 'name': self.object.fullname}, 'formset_text': self.render_formset(formset), 'formset': formset, 'objects': self.page, 'error_msg': self.msg, 'template_path': template_path, 'layout_style': layout_style, 'can_add': self.formset_extra} def get_formset(self, post=None): return self.formset_class( post, initial=self.form_initial, queryset=self.page.object_list, response_url=self.response_url) def process_formset(self): formset = self.get_formset(self.request.POST) if formset.is_valid(): formset.save() for tp in formset.new_objects: messages.add_message( self.request, messages.INFO, _("Translation project (%s) has been created. We are " "now updating its files from file templates." % tp)) for tp in formset.deleted_objects: messages.add_message( self.request, messages.INFO, _("Translation project (%s) has been deleted" % tp)) else: for form in formset: for error in form.errors.values(): messages.add_message( self.request, messages.ERROR, error) def render_formset(self, formset): def generate_link(tp): path_args = split_pootle_path(tp.pootle_path)[:2] perms_url = reverse('pootle-tp-admin-permissions', args=path_args) return u'<a href="%s">%s</a>' % (perms_url, escape(tp.language)) return mark_safe( util.form_set_as_table( formset, generate_link, "language")) @get_path_obj @permission_required('administrate') def project_admin_permissions(request, project): ctx = { 'page': 'admin-permissions', 'browse_url': reverse('pootle-project-browse', kwargs={ 'project_code': project.code, 'dir_path': '', 'filename': '', }), 'translate_url': reverse('pootle-project-translate', kwargs={ 'project_code': project.code, 'dir_path': '', 'filename': '', }), 'project': project, 'directory': project.directory, } return admin_permissions(request, project.directory, 'projects/admin/permissions.html', ctx) class ProjectsMixin(object): ns = "pootle.project" sw_version = PootleProjectConfig.version template_extends = 'projects/all/base.html' browse_url_path = "pootle-projects-browse" translate_url_path = "pootle-projects-translate" @lru_cache() def get_object(self): user_projects = ( Project.objects.for_user(self.request.user) .select_related("directory")) return ProjectSet(user_projects) @property def permission_context(self): return self.get_object().directory @property def has_admin_access(self): return self.request.user.is_superuser @property def url_kwargs(self): return {} class ProjectsBrowseView(ProjectsMixin, PootleBrowseView): view_name = "projects" @cached_property def object_children(self): items = [ make_project_list_item(project) for project in self.object.children] items = self.add_child_stats(items) items.sort(cmp_by_last_activity) return items @property def sidebar_announcements(self): return {} def get(self, *args, **kwargs): response = super(ProjectsBrowseView, self).get(*args, **kwargs) response.set_cookie('pootle-language', "projects") return response class ProjectsTranslateView(ProjectsMixin, PootleTranslateView): required_permission = "administrate"
13,400
Python
.py
356
27.688202
82
0.602929
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,131
0017_remove_project_treestyle.py
translate_pootle/pootle/apps/pootle_project/migrations/0017_remove_project_treestyle.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-08-28 06:27 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pootle_project', '0016_change_treestyle_choices_label'), ] operations = [ migrations.RemoveField( model_name='project', name='treestyle', ), ]
416
Python
.py
14
23.785714
66
0.63728
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,132
0013_rename_treestyle_choice_to_pootle_fs.py
translate_pootle/pootle/apps/pootle_project/migrations/0013_rename_treestyle_choice_to_pootle_fs.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.10 on 2016-10-06 14:03 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pootle_project', '0012_set_pootle_fs_treestyle'), ] operations = [ migrations.AlterField( model_name='project', name='treestyle', field=models.CharField(choices=[('auto', 'Automatic detection of gnu/non-gnu file layouts (slower)'), ('gnu', 'GNU style: files named by language code'), ('nongnu', 'Non-GNU: Each language in its own directory'), ('pootle_fs', 'Allow pootle_fs to manage filesystems')], default='auto', max_length=20, verbose_name='Project Tree Style'), ), ]
765
Python
.py
15
44.6
348
0.661745
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,133
0015_rename_fs_treestyle.py
translate_pootle/pootle/apps/pootle_project/migrations/0015_rename_fs_treestyle.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-01-13 11:07 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pootle_project', '0014_just_rename_label_for_choice'), ] operations = [ migrations.AlterField( model_name='project', name='treestyle', field=models.CharField(choices=[('auto', 'Automatic detection of gnu/non-gnu file layouts (slower)'), ('gnu', 'GNU style: files named by language code'), ('nongnu', 'Non-GNU: Each language in its own directory'), ('pootle_fs', 'Allow Pootle FS to manage filesystems (Experimental)')], default='auto', max_length=20, verbose_name='Project Tree Style'), ), ]
785
Python
.py
15
45.933333
363
0.665359
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,134
0012_set_pootle_fs_treestyle.py
translate_pootle/pootle/apps/pootle_project/migrations/0012_set_pootle_fs_treestyle.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.10 on 2016-10-06 13:51 from __future__ import unicode_literals from django.db import migrations def set_pootle_fs_style(apps, schema_editor): Project = apps.get_model('pootle_project', 'Project') for project in Project.objects.filter(treestyle='none'): project.treestyle = 'pootle_fs' project.save() class Migration(migrations.Migration): dependencies = [ ('pootle_project', '0011_add_project_checker_validator'), ] operations = [ migrations.RunPython(set_pootle_fs_style), ]
588
Python
.py
16
31.875
65
0.690813
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,135
0009_set_code_as_fullname_when_no_fullname.py
translate_pootle/pootle/apps/pootle_project/migrations/0009_set_code_as_fullname_when_no_fullname.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models def set_all_fullnames(apps, schema_editor): Project = apps.get_model("pootle_project", "Project") for project in Project.objects.filter(fullname=""): project.fullname = project.code project.save() class Migration(migrations.Migration): dependencies = [ ('pootle_project', '0008_remove_project_localfiletype'), ] operations = [ migrations.RunPython(set_all_fullnames), ]
538
Python
.py
15
30.666667
64
0.69186
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,136
0010_add_reserved_code_validator.py
translate_pootle/pootle/apps/pootle_project/migrations/0010_add_reserved_code_validator.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import pootle_project.models class Migration(migrations.Migration): dependencies = [ ('pootle_project', '0009_set_code_as_fullname_when_no_fullname'), ] operations = [ migrations.AlterField( model_name='project', name='code', field=models.CharField(max_length=255, validators=[pootle_project.models.validate_not_reserved], help_text='A short code for the project. This should only contain ASCII characters, numbers, and the underscore (_) character.', unique=True, verbose_name='Code', db_index=True), ), ]
693
Python
.py
15
39.8
287
0.686478
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,137
0005_add_none_treestyle.py
translate_pootle/pootle/apps/pootle_project/migrations/0005_add_none_treestyle.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pootle_project', '0004_correct_checkerstyle_options_order'), ] operations = [ migrations.AlterField( model_name='project', name='treestyle', field=models.CharField(default='auto', max_length=20, verbose_name='Project Tree Style', choices=[('auto', 'Automatic detection of gnu/non-gnu file layouts (slower)'), ('gnu', 'GNU style: files named by language code'), ('nongnu', 'Non-GNU: Each language in its own directory'), ('none', 'Allow pootle_fs to manage filesystems')]), ), ]
722
Python
.py
14
44.785714
343
0.661451
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,138
0014_just_rename_label_for_choice.py
translate_pootle/pootle/apps/pootle_project/migrations/0014_just_rename_label_for_choice.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.10 on 2016-10-14 14:18 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pootle_project', '0013_rename_treestyle_choice_to_pootle_fs'), ] operations = [ migrations.AlterField( model_name='project', name='treestyle', field=models.CharField(choices=[('auto', 'Automatic detection of gnu/non-gnu file layouts (slower)'), ('gnu', 'GNU style: files named by language code'), ('nongnu', 'Non-GNU: Each language in its own directory'), ('pootle_fs', 'Allow Pootle FS to manage filesystems')], default='auto', max_length=20, verbose_name='Project Tree Style'), ), ]
778
Python
.py
15
45.466667
348
0.664908
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,139
0011_add_project_checker_validator.py
translate_pootle/pootle/apps/pootle_project/migrations/0011_add_project_checker_validator.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.9 on 2016-09-30 20:46 from __future__ import unicode_literals from django.db import migrations, models import pootle_project.models class Migration(migrations.Migration): dependencies = [ ('pootle_project', '0010_add_reserved_code_validator'), ] operations = [ migrations.AlterField( model_name='project', name='checkstyle', field=models.CharField(default='standard', max_length=50, validators=[pootle_project.models.validate_project_checker], verbose_name='Quality Checks'), ), ]
612
Python
.py
16
32.1875
162
0.678511
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,140
0007_migrate_localfiletype.py
translate_pootle/pootle/apps/pootle_project/migrations/0007_migrate_localfiletype.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from pootle.core.delegate import formats def migrate_localfiletype(apps, schema_editor): format_registry = formats.get() projects = apps.get_model("pootle_project.Project").objects.all() filetypes = apps.get_model("pootle_format.Format").objects.all() for project in projects: if project.localfiletype in format_registry: filetype = filetypes.get( pk=format_registry[project.localfiletype]['pk']) if filetype not in project.filetypes.all(): project.filetypes.add(filetype) class Migration(migrations.Migration): dependencies = [ ('pootle_format', '0002_default_formats'), ('pootle_project', '0006_project_filetypes'), ] operations = [ migrations.RunPython(migrate_localfiletype), ]
917
Python
.py
22
34.772727
69
0.684746
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,141
0003_case_sensitive_schema.py
translate_pootle/pootle/apps/pootle_project/migrations/0003_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_project_codes_cs(apps, schema_editor): cursor = schema_editor.connection.cursor() set_mysql_collation_for_column( apps, cursor, "pootle_project.Project", "code", "utf8_bin", "varchar(255)") class Migration(migrations.Migration): dependencies = [ ('pootle_project', '0002_remove_dynamic_model_choices_localfiletype'), ] operations = [ migrations.RunPython(make_project_codes_cs), ]
655
Python
.py
20
26.95
78
0.674641
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,142
0001_initial.py
translate_pootle/pootle/apps/pootle_project/migrations/0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import pootle.core.mixins.treeitem import pootle_project.models class Migration(migrations.Migration): dependencies = [ ('pootle_language', '0001_initial'), ('pootle_app', '0001_initial'), ] operations = [ migrations.CreateModel( name='Project', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('code', models.CharField(help_text='A short code for the project. This should only contain ASCII characters, numbers, and the underscore (_) character.', unique=True, max_length=255, verbose_name='Code', db_index=True)), ('fullname', models.CharField(max_length=255, verbose_name='Full Name')), ('checkstyle', models.CharField(default='standard', max_length=50, verbose_name='Quality Checks', choices=[('standard', 'standard'), ('creativecommons', 'creativecommons'), ('drupal', 'drupal'), ('gnome', 'gnome'), ('kde', 'kde'), ('libreoffice', 'libreoffice'), ('mozilla', 'mozilla'), ('openoffice', 'openoffice'), ('terminology', 'terminology'), ('wx', 'wx')])), ('localfiletype', models.CharField(default='po', max_length=50, verbose_name='File Type', choices=[('po', 'Gettext PO'), ('xlf', 'XLIFF'), ('xliff', 'XLIFF'), ('ts', 'Qt ts'), ('tmx', 'TMX'), ('tbx', 'TBX'), ('catkeys', 'Haiku catkeys'), ('csv', 'Excel CSV'), ('lang', 'Mozilla .lang')])), ('treestyle', models.CharField(default='auto', max_length=20, verbose_name='Project Tree Style', choices=[('auto', 'Automatic detection (slower)'), ('gnu', 'GNU style: files named by language code'), ('nongnu', 'Non-GNU: Each language in its own directory')])), ('ignoredfiles', models.CharField(default='', max_length=255, verbose_name='Ignore Files', blank=True)), ('report_email', models.EmailField(help_text='An email address where issues with the source text can be reported.', max_length=254, verbose_name='Errors Report Email', blank=True)), ('screenshot_search_prefix', models.URLField(null=True, verbose_name='Screenshot Search Prefix', blank=True)), ('creation_time', models.DateTimeField(db_index=True, auto_now_add=True, null=True)), ('disabled', models.BooleanField(default=False, verbose_name='Disabled')), ('directory', models.OneToOneField(editable=False, to='pootle_app.Directory', on_delete=models.CASCADE)), ('source_language', models.ForeignKey(verbose_name='Source Language', to='pootle_language.Language', on_delete=models.CASCADE)), ], options={ 'ordering': ['code'], 'db_table': 'pootle_app_project', }, bases=(models.Model, pootle.core.mixins.treeitem.CachedTreeItem, pootle_project.models.ProjectURLMixin), ), ]
3,014
Python
.py
35
74.685714
381
0.63349
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,143
0002_remove_dynamic_model_choices_localfiletype.py
translate_pootle/pootle/apps/pootle_project/migrations/0002_remove_dynamic_model_choices_localfiletype.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('pootle_project', '0001_initial'), ] operations = [ migrations.AlterField( model_name='project', name='localfiletype', field=models.CharField(default='po', max_length=50, verbose_name='File Type'), preserve_default=True, ), ]
481
Python
.py
15
24.866667
90
0.618221
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,144
0016_change_treestyle_choices_label.py
translate_pootle/pootle/apps/pootle_project/migrations/0016_change_treestyle_choices_label.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-20 12:57 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pootle_project', '0015_rename_fs_treestyle'), ] operations = [ migrations.AlterField( model_name='project', name='treestyle', field=models.CharField(choices=[('auto', 'Automatic detection of GNU/non-GNU file layouts (slower)'), ('gnu', 'GNU style: files named by language code'), ('nongnu', 'Non-GNU: Each language in its own directory'), ('pootle_fs', 'Allow Pootle FS to manage filesystems (Experimental)')], default='auto', max_length=20, verbose_name='Project Tree Style'), ), ]
776
Python
.py
15
45.333333
363
0.664021
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,145
0004_correct_checkerstyle_options_order.py
translate_pootle/pootle/apps/pootle_project/migrations/0004_correct_checkerstyle_options_order.py
# -*- coding: utf-8 -*- """The order of the checkerstyle options changed when we moved management from Translate Toolkit into Pootle. This simple migration realigns then to what is expected now, preventing false positive messages about still needing a migration. """ from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pootle_project', '0003_case_sensitive_schema'), ] operations = [ migrations.AlterField( model_name='project', name='checkstyle', field=models.CharField(default='standard', max_length=50, verbose_name='Quality Checks', choices=[('creativecommons', 'creativecommons'), ('drupal', 'drupal'), ('gnome', 'gnome'), ('kde', 'kde'), ('libreoffice', 'libreoffice'), ('mozilla', 'mozilla'), ('openoffice', 'openoffice'), ('standard', 'standard'), ('terminology', 'terminology'), ('wx', 'wx')]), ), ]
980
Python
.py
19
46.210526
367
0.678197
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,146
0008_remove_project_localfiletype.py
translate_pootle/pootle/apps/pootle_project/migrations/0008_remove_project_localfiletype.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pootle_project', '0007_migrate_localfiletype'), ('pootle_store', '0013_set_store_filetype_again') ] operations = [ migrations.RemoveField( model_name='project', name='localfiletype', ), ]
428
Python
.py
14
24.071429
57
0.628362
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,147
0006_project_filetypes.py
translate_pootle/pootle/apps/pootle_project/migrations/0006_project_filetypes.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import sortedm2m.fields class Migration(migrations.Migration): dependencies = [ ('pootle_format', '0001_initial'), ('pootle_project', '0005_add_none_treestyle'), ] operations = [ migrations.AddField( model_name='project', name='filetypes', field=sortedm2m.fields.SortedManyToManyField(help_text=None, to='pootle_format.Format'), ), ]
528
Python
.py
16
26.4375
100
0.64497
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,148
models.py
translate_pootle/pootle/apps/pootle_format/models.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django.db import models from .abstracts import AbstractFileExtension, AbstractFormat class FileExtension(AbstractFileExtension): class Meta(AbstractFileExtension.Meta): db_table = "pootle_fileextension" class Format(AbstractFormat): class Meta(AbstractFormat.Meta): db_table = "pootle_format" extension = models.ForeignKey( FileExtension, related_name="formats", on_delete=models.CASCADE) template_extension = models.ForeignKey( FileExtension, related_name="template_formats", on_delete=models.CASCADE) def __str__(self): return ( "%s (%s/%s)" % (self.title, self.extension, self.template_extension))
1,013
Python
.py
26
32.884615
77
0.698055
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,149
getters.py
translate_pootle/pootle/apps/pootle_format/getters.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from pootle.core.delegate import filetype_tool, formats from pootle.core.plugin import getter from pootle_project.models import Project from .registry import format_registry from .utils import ProjectFiletypes @getter(formats) def formats_getter(**kwargs_): return format_registry @getter(filetype_tool, sender=Project) def filetype_tool_getter(**kwargs_): return ProjectFiletypes
672
Python
.py
18
35.444444
77
0.797214
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,150
abstracts.py
translate_pootle/pootle/apps/pootle_format/abstracts.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django.db import models from pootle.i18n.gettext import ugettext_lazy as _ class AbstractFileExtension(models.Model): class Meta(object): abstract = True def __str__(self): return self.name name = models.CharField( 'Format filetype extension', max_length=15, unique=True, db_index=True) class AbstractFormat(models.Model): class Meta(object): abstract = True unique_together = ["title", "extension"] name = models.CharField( _('Format name'), max_length=30, unique=True, db_index=True) title = models.CharField( _('Format title'), max_length=255, db_index=False) enabled = models.BooleanField( verbose_name=_('Enabled'), default=True) monolingual = models.BooleanField( verbose_name=_('Monolingual format'), default=False)
1,182
Python
.py
36
26.861111
77
0.663436
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,151
default.py
translate_pootle/pootle/apps/pootle_format/default.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. POOTLE_FORMATS = [ ("po", dict(title='Gettext PO', extension="po", template_extension="pot")), ("xliff", dict(title='XLIFF', extension="xliff", template_extension="xliff")), ("xlf", dict(title='XLIFF', extension="xlf", template_extension="xlf")), ("ts", dict(title='TS', extension="ts", template_extension="ts")), ("lang", dict(title='Mozilla Lang', extension="lang", template_extension="lang"))]
819
Python
.py
28
23
77
0.596958
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,152
apps.py
translate_pootle/pootle/apps/pootle_format/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 PootleFormatConfig(AppConfig): name = "pootle_format" verbose_name = "Pootle Format" def ready(self): importlib.import_module("pootle_format.models") importlib.import_module("pootle_format.receivers") importlib.import_module("pootle_format.getters") importlib.import_module("pootle_format.providers") importlib.import_module("pootle_format.formats.providers")
750
Python
.py
18
37.444444
77
0.745179
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,153
receivers.py
translate_pootle/pootle/apps/pootle_format/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.db.models.signals import m2m_changed, pre_save from django.dispatch import receiver from pootle.core.signals import filetypes_changed from pootle_project.models import Project from .models import Format @receiver(pre_save, sender=Format) def format_pre_save_handler(**kwargs): instance = kwargs["instance"] if not instance.title: instance.title = instance.name.capitalize() @receiver(m2m_changed, sender=Project.filetypes.through) def project_filetypes_changed_handler(**kwargs): if kwargs["action"] in ["post_add", "post_remove", "post_clear"]: del kwargs["sender"] del kwargs["signal"] filetypes_changed.send(Project, **kwargs)
968
Python
.py
23
38.869565
77
0.751599
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,154
utils.py
translate_pootle/pootle/apps/pootle_format/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 logging import os from collections import OrderedDict from django.utils.functional import cached_property from pootle_fs.utils import PathFilter from .exceptions import UnrecognizedFiletype log = logging.getLogger(__name__) class ProjectFiletypes(object): def __init__(self, project): self.project = project @property def filetypes(self): return self.project.filetypes.all() def choose_filetype(self, filename): ext = os.path.splitext(filename)[1][1:] filetypes = self.filetypes.select_related( "extension", "template_extension") filetypes = list( filetypes.filter(extension__name=ext) | filetypes.filter(template_extension__name=ext)) for filetype in filetypes: if filetype.extension.name == ext: return filetype for filetype in filetypes: if filetype.template_extension.name == ext: return filetype raise self.unrecognized_file(filename) def unrecognized_file(self, filename): # The filename's extension is not recognised in this Project return UnrecognizedFiletype( "File '%s' is not recognized for Project " "'%s', available extensions are %s" % (filename, self.project.fullname, ", ".join(set(self.filetype_extensions)))) def unrecognized_filetype(self, filename): # The filetype is not recognized for the project return UnrecognizedFiletype( "Filetype '%s' is not recognized for Project " "'%s', available filetypes are %s" % (filename, self.project.fullname, ", ".join(str(ft) for ft in self.filetypes))) @cached_property def filetype_extensions(self): return list( self.filetypes.values_list( "extension__name", flat=True)) @cached_property def template_extensions(self): return list( self.filetypes.values_list( "template_extension__name", flat=True)) @cached_property def valid_extensions(self): """this is the equiv of combining 2 sets""" exts = [] template_exts = [] filetypes = self.filetypes.values_list( "extension__name", "template_extension__name") for ext, template_ext in filetypes.iterator(): exts.append(ext) template_exts.append(template_ext) return list( OrderedDict.fromkeys(exts + template_exts)) def add_filetype(self, filetype): """Adds a filetype to a Project""" if filetype not in self.filetypes: log.info( "Adding filetype '%s' to project '%s'", filetype, self.project) self.project.filetypes.add(filetype) self.clear_cache() def clear_cache(self): cached = [ "filetype_extensions", "template_extensions", "valid_extensions"] for cachetype in cached: if cachetype in self.__dict__: del self.__dict__[cachetype] def set_store_filetype(self, store, filetype): """Sets a Store to given filetype If `from_filetype` is given, only updates if current filetype matches """ if filetype not in self.filetypes: raise self.unrecognized_filetype(filetype) log.info( "Setting filetype '%s' to store '%s'", filetype, store.pootle_path) store.filetype = filetype # update the extension if required extension = ( store.is_template and str(filetype.template_extension) or str(filetype.extension)) root_name = os.path.splitext(store.name)[0] new_name = ( root_name.endswith(".%s" % extension) and root_name or ("%s.%s" % (root_name, extension))) if store.name != new_name: store.name = new_name store.save() def _tp_path_regex(self, tp, matching): """Creates a regex from /tp/path/$glob_converted_to_regex.($valid_extensions)$ """ extensions = ( (tp == self.project.get_template_translationproject()) and self.template_extensions or self.filetype_extensions) return ( r"^/%s\.%s$" % (PathFilter().path_regex(matching).rstrip("$"), r"(%s)" % ("|".join(extensions)))) def set_tp_filetype(self, tp, filetype, from_filetype=None, matching=None): """Set all Stores in TranslationProject to given filetype If `from_filetype` is given, only Stores of that type will be updated If `matching` is given its treated as a glob matching pattern to be appended to the tp part of the pootle_path - ie `/lang/proj/$glob` """ stores = tp.stores.exclude(filetype=filetype) if matching: stores = stores.filter( tp_path__regex=self._tp_path_regex(tp, matching)) if from_filetype: stores = stores.filter(filetype=from_filetype) for store in stores.iterator(): self.set_store_filetype(store, filetype) def set_filetypes(self, filetype, from_filetype=None, matching=None): """Set all Stores in Project to given filetype If `from_filetype` is given, only Stores of that type will be updated If `matching` is given its treated as a glob matching pattern to be appended to the tp part of the pootle_path - ie `/lang/proj/$glob` """ if filetype not in self.filetypes: raise self.unrecognized_filetype(filetype) templates = self.project.get_template_translationproject() if templates: # set the templates tp filetypes self.set_tp_filetype( templates, filetype, from_filetype=from_filetype, matching=matching) for tp in self.project.translationproject_set.all(): # set the other tp filetypes if tp == templates: continue self.set_tp_filetype( tp, filetype, from_filetype=from_filetype, matching=matching)
6,681
Python
.py
163
30.717791
79
0.603852
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,155
__init__.py
translate_pootle/pootle/apps/pootle_format/__init__.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. default_app_config = 'pootle_format.apps.PootleFormatConfig'
337
Python
.py
8
41
77
0.768293
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,156
providers.py
translate_pootle/pootle/apps/pootle_format/providers.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from collections import OrderedDict from pootle.core.delegate import format_registration from pootle.core.plugin import provider from .default import POOTLE_FORMATS @provider(format_registration) def register_formats(**kwargs_): return OrderedDict(POOTLE_FORMATS)
548
Python
.py
14
37.5
77
0.801512
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,157
exceptions.py
translate_pootle/pootle/apps/pootle_format/exceptions.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. class UnrecognizedFiletype(Exception): pass
325
Python
.py
9
34.444444
77
0.764331
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,158
registry.py
translate_pootle/pootle/apps/pootle_format/registry.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from collections import OrderedDict from django.utils.functional import cached_property from pootle.core.delegate import format_registration from pootle_format.models import FileExtension, Format class FormatRegistry(object): def initialize(self): for filetype, info in format_registration.gather().items(): self.register(filetype, **info) def register(self, name, extension, title=None, template_extension=None): template_extension = template_extension or extension exts = {} for ext in set([extension, template_extension]): exts[ext], __ = FileExtension.objects.get_or_create(name=ext) kwargs = dict( name=name, defaults=dict( extension=exts[extension], template_extension=exts[template_extension])) if title: kwargs["defaults"]["title"] = title filetype, created = self.format_qs.update_or_create(**kwargs) self.clear() return filetype def clear(self): if "formats" in self.__dict__: del self.__dict__["formats"] @property def format_qs(self): return Format.objects.select_related( "extension", "template_extension") @cached_property def formats(self): formats = OrderedDict() for filetype in self.format_qs.filter(enabled=True): formats[filetype.name] = dict( pk=filetype.pk, name=filetype.name, title=filetype.title, display_title=str(filetype), extension=str(filetype.extension), template_extension=str(filetype.template_extension)) return formats def __iter__(self): return self.formats.__iter__() def __getitem__(self, k): return self.formats.__getitem__(k) def keys(self): return self.formats.keys() def values(self): return self.formats.values() def items(self): return self.formats.items() format_registry = FormatRegistry()
2,352
Python
.py
60
30.85
77
0.643077
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,159
0003_remove_extra_indeces.py
translate_pootle/pootle/apps/pootle_format/migrations/0003_remove_extra_indeces.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-06-02 16:21 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pootle_format', '0002_default_formats'), ] operations = [ migrations.AlterField( model_name='format', name='title', field=models.CharField(max_length=255, verbose_name='Format title'), ), ]
483
Python
.py
15
25.8
80
0.632829
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,160
0002_default_formats.py
translate_pootle/pootle/apps/pootle_format/migrations/0002_default_formats.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from pootle.core.delegate import formats def add_default_formats(apps, schema_editor): formats.get().initialize() class Migration(migrations.Migration): dependencies = [ ('pootle_format', '0001_initial'), ] operations = [ migrations.RunPython(add_default_formats), ]
416
Python
.py
13
27.615385
50
0.708861
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,161
0001_initial.py
translate_pootle/pootle/apps/pootle_format/migrations/0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='FileExtension', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(unique=True, max_length=15, verbose_name='Format filetype extension', db_index=True)), ], options={ 'abstract': False, 'db_table': 'pootle_fileextension', }, ), migrations.CreateModel( name='Format', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(unique=True, max_length=30, verbose_name='Format name', db_index=True)), ('title', models.CharField(max_length=255, verbose_name='Format title', db_index=True)), ('enabled', models.BooleanField(default=True, verbose_name='Enabled')), ('monolingual', models.BooleanField(default=False, verbose_name='Monolingual format')), ('extension', models.ForeignKey(related_name='formats', to='pootle_format.FileExtension', on_delete=models.CASCADE)), ('template_extension', models.ForeignKey(related_name='template_formats', to='pootle_format.FileExtension', on_delete=models.CASCADE)), ], options={ 'abstract': False, 'db_table': 'pootle_format', }, ), migrations.AlterUniqueTogether( name='format', unique_together=set([('title', 'extension')]), ), ]
1,855
Python
.py
39
35.769231
151
0.582551
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,162
po.py
translate_pootle/pootle/apps/pootle_format/formats/po.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from translate.storage import poheader from django.core.exceptions import ObjectDoesNotExist from django.db.models import Max from django.utils import timezone from pootle.core.utils import dateformat from pootle.core.utils.timezone import datetime_min from pootle.core.utils.version import get_major_minor_version from pootle_statistics.models import Submission from pootle_store.syncer import StoreSyncer class PoStoreSyncer(StoreSyncer): def get_latest_submission(self, mtime): user_displayname = None user_email = None fields = ( "submitter__username", "submitter__full_name", "submitter__email") submissions = self.translation_project.submission_set.exclude( submitter__username="nobody") try: username, fullname, user_email = ( submissions.filter(creation_time=mtime) .values_list(*fields).latest()) except Submission.DoesNotExist: try: _mtime, username, fullname, user_email = ( submissions.values_list("creation_time", *fields) .latest()) mtime = min(_mtime, mtime) except ObjectDoesNotExist: pass if user_email: user_displayname = ( fullname.strip() if fullname.strip() else username) return mtime, user_displayname, user_email def get_po_revision_date(self, mtime): return ( "%s%s" % (mtime.strftime('%Y-%m-%d %H:%M'), poheader.tzstring())) def get_po_mtime(self, mtime): return ( '%s.%06d' % (int(dateformat.format(mtime, 'U')), mtime.microsecond)) def get_po_headers(self, mtime, user_displayname, user_email): headerupdates = { 'PO_Revision_Date': self.get_po_revision_date(mtime), 'X_Generator': "Pootle %s" % get_major_minor_version(), 'X_POOTLE_MTIME': self.get_po_mtime(mtime)} headerupdates['Last_Translator'] = ( user_displayname and user_email and ('%s <%s>' % (user_displayname, user_email)) or 'Anonymous Pootle User') return headerupdates def update_po_headers(self, disk_store, mtime, user_displayname, user_email): disk_store.updateheader( add=True, **self.get_po_headers(mtime, user_displayname, user_email)) if self.language.nplurals and self.language.pluralequation: disk_store.updateheaderplural( self.language.nplurals, self.language.pluralequation) def update_store_header(self, disk_store, **kwargs): super(PoStoreSyncer, self).update_store_header(disk_store, **kwargs) user = kwargs.get("user") mtime = self.store.units.aggregate(mtime=Max("mtime"))["mtime"] if mtime is None or mtime == datetime_min: mtime = timezone.now() user_displayname = None user_email = None if user is None: (mtime, user_displayname, user_email) = self.get_latest_submission(mtime) elif user.is_authenticated: user_displayname = user.display_name user_email = user.email self.update_po_headers(disk_store, mtime, user_displayname, user_email)
3,769
Python
.py
90
31.522222
81
0.609324
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,163
mozilla_lang.py
translate_pootle/pootle/apps/pootle_format/formats/mozilla_lang.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from translate.misc.multistring import multistring from pootle_store.constants import FUZZY, UNTRANSLATED from pootle_store.diff import DiffableStore from pootle_store.syncer import StoreSyncer, UnitSyncer class LangUnitSyncer(UnitSyncer): @property def target(self): if self.isfuzzy and not self.raw: return multistring("") return self.unit.target class LangStoreSyncer(StoreSyncer): unit_sync_class = LangUnitSyncer class DiffableLangStore(DiffableStore): def get_unit_state(self, file_unit): return ( FUZZY if (file_unit["unitid"] in self.target_units and self.target_units[file_unit["unitid"]]["state"] == FUZZY and file_unit["state"] == UNTRANSLATED) else file_unit["state"]) def get_unit_target(self, file_unit): return ( self.target_units[file_unit["unitid"]]["target_f"] if file_unit["state"] == FUZZY else file_unit["target"]) def get_file_unit(self, unit): file_unit = super(DiffableLangStore, self).get_file_unit(unit) file_unit["state"] = self.get_unit_state(file_unit) file_unit["target"] = self.get_unit_target(file_unit) return file_unit
1,544
Python
.py
37
34.891892
77
0.677592
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,164
providers.py
translate_pootle/pootle/apps/pootle_format/formats/providers.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from pootle.core.delegate import format_diffs, format_syncers from pootle.core.plugin import provider from .mozilla_lang import DiffableLangStore, LangStoreSyncer from .po import PoStoreSyncer @provider(format_syncers) def register_format_syncers(**kwargs_): return dict( po=PoStoreSyncer, lang=LangStoreSyncer) @provider(format_diffs) def lang_diff_provider(**kwargs_): return dict(lang=DiffableLangStore)
712
Python
.py
19
34.894737
77
0.780204
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,165
models.py
translate_pootle/pootle/apps/pootle_word/models.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django.db import models from pootle_store.models import Unit from .abstracts import AbstractStem class UnitStem(models.Model): class Meta(AbstractStem.Meta): unique_together = ["stem", "unit"] stem = models.ForeignKey("Stem") unit = models.ForeignKey(Unit) class Stem(AbstractStem): units = models.ManyToManyField( Unit, through="UnitStem", related_name="stems") class Meta(AbstractStem.Meta): db_table = "pootle_word_stem" def __unicode__(self): return ( "\"%s\", units: %s" % (self.root, list(self.units.values_list("id", flat=True))))
941
Python
.py
27
29.296296
77
0.668514
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,166
getters.py
translate_pootle/pootle/apps/pootle_word/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 stemming.porter2 import stem from pootle.core.delegate import stemmer, stopwords, text_comparison from pootle.core.plugin import getter from .utils import Stopwords, TextComparison site_stopwords = Stopwords() @getter(stemmer) def get_stemmer(**kwargs_): return stem @getter(stopwords) def get_stopwords(**kwargs_): return site_stopwords @getter(text_comparison) def get_text_comparison(**kwargs_): return TextComparison
724
Python
.py
21
32.380952
77
0.786127
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,167
abstracts.py
translate_pootle/pootle/apps/pootle_word/abstracts.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django.db import models class AbstractStem(models.Model): class Meta(object): abstract = True root = models.CharField( max_length=255, unique=True, null=False, blank=False) def save(self, *args, **kwargs): self.full_clean() super(AbstractStem, self).save(*args, **kwargs)
626
Python
.py
19
28.052632
77
0.682196
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,168
apps.py
translate_pootle/pootle/apps/pootle_word/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 PootleWordConfig(AppConfig): name = "pootle_word" verbose_name = "Pootle Word" version = "0.1.1" def ready(self): importlib.import_module("pootle_word.models") importlib.import_module("pootle_word.getters")
577
Python
.py
16
32.6875
77
0.735135
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,169
utils.py
translate_pootle/pootle/apps/pootle_word/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 os import re import Levenshtein import translate from django.utils.functional import cached_property from pootle.core.delegate import stemmer, stopwords class Stopwords(object): @cached_property def words(self): ttk_path = translate.__path__[0] fpath = ( os.path.join(ttk_path, "share", "stoplist-en") if "share" in os.listdir(ttk_path) else os.path.join(ttk_path, "..", "share", "stoplist-en")) words = set() with open(fpath) as f: for line in f.read().split("\n"): if not line: continue if line[0] in "<>=@": words.add(line[1:].strip().lower()) return words class TextStemmer(object): def __init__(self, context): self.context = context def split(self, words): return re.split(u"[^\w'-]+", words) @property def stopwords(self): return stopwords.get().words @property def tokens(self): return [ t.lower() for t in self.split(self.text) if (len(t) > 2 and t.lower() not in self.stopwords)] @property def text(self): return self.context.source_f @property def stemmer(self): return stemmer.get() @property def stems(self): return self.get_stems(self.tokens) def get_stems(self, tokens): return set(self.stemmer(t) for t in tokens) class TextComparison(TextStemmer): @property def text(self): return self.context def jaccard_similarity(self, other): return ( len(other.stems.intersection(self.stems)) / float(len(set(other.stems).union(self.stems)))) def levenshtein_distance(self, other): return ( Levenshtein.distance(self.text, other.text) / max(len(self.text), len(other.text))) def tokens_present(self, other): return ( len(set(self.tokens).intersection(other.tokens)) / float(len(other.tokens))) def stems_present(self, other): return ( len(set(self.stems).intersection(other.stems)) / float(len(other.stems))) def similarity(self, other): other = self.__class__(other) return ( (self.jaccard_similarity(other) + self.levenshtein_distance(other) + self.tokens_present(other) + self.stems_present(other)) / 4)
2,811
Python
.py
84
25.130952
77
0.596225
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,170
__init__.py
translate_pootle/pootle/apps/pootle_word/__init__.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. default_app_config = 'pootle_word.apps.PootleWordConfig'
333
Python
.py
8
40.5
77
0.765432
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,171
0003_add_word_stems.py
translate_pootle/pootle/apps/pootle_word/migrations/0003_add_word_stems.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-01-05 14:58 from __future__ import unicode_literals import re from django.db import migrations from stemming.porter2 import stem from pootle.core.delegate import stopwords from pootle_store.constants import TRANSLATED def stem_terminology_words(apps, schema_editor): Stem = apps.get_model("pootle_word.Stem") Unit = apps.get_model("pootle_store.Unit") units = Unit.objects.filter(state=TRANSLATED) units = ( units.filter(store__translation_project__project__code="terminology") | units.filter(store__name__startswith="pootle-terminology")) units = units.values_list("id", "source_f") site_stopwords = stopwords.get().words stems = {} delimiters = re.compile(u"[\W]+", re.U) for unit, source in units: source_words = set( s.strip().lower() for s in delimiters.split(source) if len(s) > 2) for word in source_words: if not word: continue if word in site_stopwords: continue stemmed = stem(word) stems[stemmed] = stems.get(stemmed, set()) stems[stemmed].add(unit) Stem.objects.bulk_create([Stem(root=st) for st in stems], batch_size=1000) added = dict(Stem.objects.values_list("root", "id")) m2m = Stem.units.through m2m_to_add = [] for stemmed in stems: for unit in stems[stemmed]: m2m_to_add.append(m2m(stem_id=added[stemmed], unit_id=unit)) m2m.objects.bulk_create(m2m_to_add, batch_size=1000) class Migration(migrations.Migration): dependencies = [ ('pootle_word', '0002_set_cs_schema'), ] operations = [ migrations.RunPython(stem_terminology_words), ]
1,797
Python
.py
47
31.234043
78
0.644828
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,172
0001_initial.py
translate_pootle/pootle/apps/pootle_word/migrations/0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-01-06 13:47 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('pootle_store', '0023_add_unit_store_idxs'), ] operations = [ migrations.CreateModel( name='Stem', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('root', models.CharField(max_length=255, unique=True)), ], options={ 'abstract': False, 'db_table': 'pootle_word_stem', }, ), migrations.CreateModel( name='UnitStem', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('stem', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='pootle_word.Stem')), ('unit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='pootle_store.Unit')), ], options={ 'abstract': False, }, ), migrations.AddField( model_name='stem', name='units', field=models.ManyToManyField(related_name='stems', through='pootle_word.UnitStem', to='pootle_store.Unit'), ), migrations.AlterUniqueTogether( name='unitstem', unique_together=set([('stem', 'unit')]), ), ]
1,641
Python
.py
43
27.72093
119
0.561558
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,173
0002_set_cs_schema.py
translate_pootle/pootle/apps/pootle_word/migrations/0002_set_cs_schema.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-01-07 13:29 from __future__ import unicode_literals from django.db import migrations from pootle.core.utils.db import set_mysql_collation_for_column def make_stem_root_cs(apps, schema_editor): cursor = schema_editor.connection.cursor() set_mysql_collation_for_column( apps, cursor, "pootle_word.Stem", "root", "utf8_bin", "varchar(255)") class Migration(migrations.Migration): dependencies = [ ('pootle_word', '0001_initial'), ] operations = [ migrations.RunPython(make_stem_root_cs), ]
652
Python
.py
21
25.095238
63
0.648475
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,174
getters.py
translate_pootle/pootle/apps/pootle_profile/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 membership, profile from pootle.core.plugin import getter from .utils import UserMembership, UserProfile User = get_user_model() @getter(profile, sender=User) def user_profile_getter(**kwargs_): return UserProfile @getter(membership, sender=User) def user_membership_getter(**kwargs_): return UserMembership
680
Python
.py
18
35.833333
77
0.788668
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,175
urls.py
translate_pootle/pootle/apps/pootle_profile/urls.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django.conf.urls import include, url from .views import UserAPIView, UserDetailView, UserSettingsView user_patterns = [ url(r'^(?P<username>[^/]+)/$', UserDetailView.as_view(), name='pootle-user-profile'), url(r'^(?P<username>[^/]+)/edit/?$', UserDetailView.as_view(), name='pootle-user-profile-edit'), url(r'^(?P<username>[^/]+)/settings/$', UserSettingsView.as_view(), name='pootle-user-settings'), ] api_patterns = [ url(r'^users/(?P<id>[0-9]+)/?$', UserAPIView.as_view(), name='pootle-xhr-user'), ] urlpatterns = [ url(r'^user/', include(user_patterns)), url(r'^xhr/', include(api_patterns)), ]
975
Python
.py
29
29.310345
77
0.647122
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,176
apps.py
translate_pootle/pootle/apps/pootle_profile/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 PootleProfileConfig(AppConfig): name = "pootle_profile" verbose_name = "Pootle Profile" def ready(self): importlib.import_module("pootle_profile.getters")
513
Python
.py
14
33.785714
77
0.756592
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,177
utils.py
translate_pootle/pootle/apps/pootle_profile/utils.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from datetime import timedelta from django.utils import timezone from django.utils.functional import cached_property from pootle.core.delegate import ( comparable_event, log, membership, scores, site_languages) from pootle.core.utils.templates import render_as_template from pootle.i18n.gettext import ugettext_lazy as _ class UserProfile(object): def __init__(self, user): self.user = user @cached_property def avatar(self): return render_as_template( "{% load common_tags %}{% avatar username email_hash 20 %}", context=dict( username=self.user.username, email_hash=self.user.email_hash)) @cached_property def log(self): return log.get(self.user.__class__)(self.user) @cached_property def membership(self): return membership.get(self.user.__class__)(self.user) @cached_property def scores(self): return scores.get(self.user.__class__)(self.user) @property def display_name(self): return ( self.user.display_name if not self.user.is_anonymous else _("Anonymous User")) def get_events(self, start=None, n=None): sortable = comparable_event.get(self.log.__class__) start = start or (timezone.now() - timedelta(days=30)) events = sorted( sortable(ev) for ev in self.log.get_events(start=start)) if n is not None: events = events[-n:] return reversed(events) class UserMembership(object): def __init__(self, user): self.user = user @cached_property def language_dirs(self): return dict( self.site_languages.site_languages.values_list( "directory", "code")) @cached_property def site_languages(self): return site_languages.get() @cached_property def teams_and_permissions(self): permsets = self.get_permission_set().values_list( "directory", "positive_permissions__codename") _teams = {} for lang, perm in permsets: lang = self.language_dirs.get(lang) _teams[lang] = _teams.get(lang, set()) _teams[lang].add(perm) return _teams @cached_property def teams_and_roles(self): teams = {} for team, permissions in self.teams_and_permissions.items(): teams[team] = dict(name=self.site_languages.languages[team]) if "administrate" in permissions: teams[team]["role"] = _("Admin") elif "review" in permissions: teams[team]["role"] = _("Reviewer") elif "translate" in permissions: teams[team]["role"] = _("Translator") else: teams[team]["role"] = "" return teams @property def teams(self): return self.teams_and_permissions.keys() def get_permission_set(self): return self.user.permissionset_set.filter( directory_id__in=self.language_dirs.keys())
3,366
Python
.py
90
29.1
77
0.621505
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,178
__init__.py
translate_pootle/pootle/apps/pootle_profile/__init__.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. default_app_config = 'pootle_profile.apps.PootleProfileConfig'
339
Python
.py
8
41.25
77
0.769697
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,179
forms.py
translate_pootle/pootle/apps/pootle_profile/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. import urlparse from django import forms from django.contrib.auth import get_user_model from pootle.i18n.gettext import ugettext_lazy as _ class EditUserForm(forms.ModelForm): class Meta(object): model = get_user_model() fields = ('full_name', 'twitter', 'linkedin', 'website', 'bio') def clean_linkedin(self): url = self.cleaned_data['linkedin'] if url != '': parsed = urlparse.urlparse(url) if 'linkedin.com' not in parsed.netloc or parsed.path == '/': raise forms.ValidationError( _('Please enter a valid LinkedIn user profile URL.') ) return url
956
Python
.py
24
33.375
77
0.659459
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,180
views.py
translate_pootle/pootle/apps/pootle_profile/views.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django.contrib import auth from django.utils.translation import get_language from django.views.generic import DetailView, UpdateView from pootle.core.delegate import profile from pootle.core.views import APIView from pootle.core.views.mixins import (NoDefaultUserMixin, TestUserFieldMixin, UserObjectMixin) from pootle.i18n.gettext import ugettext_lazy as _ from .forms import EditUserForm User = auth.get_user_model() class UserAPIView(TestUserFieldMixin, APIView): model = User restrict_to_methods = ('GET', 'PUT') test_user_field = 'id' edit_form_class = EditUserForm class UserDetailView(NoDefaultUserMixin, UserObjectMixin, DetailView): template_name = 'user/profile.html' @property def request_lang(self): return get_language() def get_context_data(self, **kwargs): context = super(UserDetailView, self).get_context_data(**kwargs) context["profile"] = profile.get(self.object.__class__)(self.object) return context class UserSettingsView(TestUserFieldMixin, UserObjectMixin, UpdateView): fields = ('unit_rows', 'alt_src_langs') template_name = 'user/settings.html' def get_form_kwargs(self): kwargs = super(UserSettingsView, self).get_form_kwargs() kwargs.update({'label_suffix': ''}) return kwargs def get_form(self, *args, **kwargs): form = super(UserSettingsView, self).get_form(*args, **kwargs) form.fields['alt_src_langs'].help_text = None form.fields['alt_src_langs'].widget.attrs['class'] = \ 'js-select2 select2-multiple' form.fields['alt_src_langs'].widget.attrs['data-placeholder'] = \ _('Select one or more languages') return form
2,051
Python
.py
46
38.73913
77
0.705231
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,181
profile_tags.py
translate_pootle/pootle/apps/pootle_profile/templatetags/profile_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 urllib from django import template from django.conf import settings from django.core.urlresolvers import reverse from django.utils.safestring import mark_safe from pootle.i18n.gettext import ugettext_lazy as _ register = template.Library() @register.filter def gravatar(user, size): return user.gravatar_url(size) @register.inclusion_tag("user/includes/profile_score.html") def profile_score(request, profile): context = dict(profile=profile) top_lang = profile.scores.top_language context["own_profile"] = request.user == profile.user if top_lang and not top_lang[0] == -1 and top_lang[1]: if context["own_profile"]: score_tweet_content = _( "My current score at %(pootle_title)s is %(score)s", dict(pootle_title=settings.POOTLE_TITLE, score=profile.scores.public_score)) context["score_tweet_message"] = _("Tweet this!") context["score_tweet_link"] = ( "https://twitter.com/share?text=%s" % urllib.quote_plus(score_tweet_content.encode("utf8"))) return context @register.inclusion_tag("user/includes/profile_ranking.html") def profile_ranking(request, profile): context = dict(request=request, profile=profile) top_lang = profile.scores.top_language context["own_profile"] = request.user == profile.user if top_lang and not top_lang[0] == -1 and top_lang[1]: context["ranking_text"] = _( "#%(rank)s contributor in %(language)s in the last 30 days", dict(rank=top_lang[0], language=top_lang[1].name)) if context["own_profile"]: ranking_tweet_content = _( "I am #%(rank)s contributor in %(language)s in the last 30 " "days at %(pootle_title)s!", dict(rank=top_lang[0], language=top_lang[1].name, pootle_title=settings.POOTLE_TITLE)) context["ranking_tweet_link"] = ( "https://twitter.com/share?text=%s" % urllib.quote_plus(ranking_tweet_content.encode("utf8"))) context["ranking_tweet_link_text"] = _("Tweet this!") else: context["no_ranking_text"] = _("No contributions in the last 30 days") return context @register.inclusion_tag("user/includes/profile_social.html") def profile_social(profile): links = [] if profile.user.website: links.append( dict(url=profile.user.website, icon="icon-user-website", text=_("My Website"))) if profile.user.twitter: links.append( dict(url=profile.user.twitter_url, icon="icon-user-twitter", text="@%s" % profile.user.twitter)) if profile.user.linkedin: links.append( dict(url=profile.user.linkedin, icon="icon-user-linkedin", text=_("My LinkedIn Profile"))) return dict(social_media_links=links) @register.inclusion_tag("user/includes/profile_teams.html") def profile_teams(request, profile): teams = profile.membership.teams_and_roles site_permissions = [] if not request.user.is_anonymous and profile.user.is_superuser: site_permissions.append(_("Site administrator")) for code, info in teams.items(): info["url"] = reverse( "pootle-language-browse", kwargs=dict(language_code=code)) teams_title = _( "%s's language teams" % profile.user.display_name) no_teams_message = _( "%s is not a member of any language teams" % profile.user.display_name) return dict( anon_request=request.user.is_anonymous, teams=teams, teams_title=teams_title, no_teams_message=no_teams_message, site_permissions=site_permissions) @register.inclusion_tag("user/includes/profile_user.html") def profile_user(request, profile): context = dict(request=request, profile=profile) context['request_user_is_manager'] = ( request.user.has_manager_permissions()) if profile.user.is_anonymous: context["bio"] = _( "Some translations are provided by anonymous volunteers. " "These are registered under this special meta-account.") elif profile.user.is_system(): context["bio"] = _( "Some translations are imported from external files. " "These are registered under this special meta-account.") else: if request.user == profile.user: context["can_edit_profile"] = True context["should_edit_profile"] = ( not profile.user.has_contact_details or not profile.user.bio) if context["should_edit_profile"]: context["edit_profile_message"] = mark_safe( _("Show others who you are, tell about yourself<br/>" "and make your public profile look gorgeous!")) context["user_title"] = _( "You can set or change your avatar image at www.gravatar.com") if profile.user.bio: context["bio"] = profile.user.bio return context @register.inclusion_tag("user/includes/profile_activity.html") def profile_activity(profile, request_lang=None): context = dict(profile=profile) if profile.user.is_meta: return context context["user_last_event"] = ( context["profile"].user.last_event(locale=request_lang)) return context
5,815
Python
.py
133
34.947368
78
0.633233
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,182
assets.py
translate_pootle/pootle/apps/pootle_app/assets.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_assets import Bundle, register from django.conf import settings # <Webpack> # These are handled by webpack and therefore have no filters applied # They're kept here so hash-based cache invalidation can be used js_vendor = Bundle( 'js/vendor.bundle.js', output='js/vendor.min.%(version)s.js') register('js_vendor', js_vendor) js_common = Bundle( 'js/common/app.bundle.js', output='js/common/app.min.%(version)s.js') register('js_common', js_common) js_admin_general_app = Bundle( 'js/admin/general/app.bundle.js', output='js/admin/general/app.min.%(version)s.js') register('js_admin_general_app', js_admin_general_app) js_admin_app = Bundle( 'js/admin/app.bundle.js', output='js/admin/app.min.%(version)s.js') register('js_admin_app', js_admin_app) js_user_app = Bundle( 'js/user/app.bundle.js', output='js/user/app.min.%(version)s.js') register('js_user_app', js_user_app) js_editor = Bundle( 'js/editor/app.bundle.js', output='js/editor/app.min.%(version)s.js') register('js_editor', js_editor) rel_path = os.path.join('js', 'select2_l10n') select2_l10n_dir = os.path.join(settings.WORKING_DIR, 'static', rel_path) l10n_files = [os.path.join(rel_path, f) for f in os.listdir(select2_l10n_dir) if (os.path.isfile(os.path.join(select2_l10n_dir, f)) and f.endswith('.js'))] for l10n_file in l10n_files: lang = l10n_file.split(os.sep)[-1].split('.')[-2] register('select2-l10n-%s' % lang, Bundle(l10n_file, output='js/select2-l10n-' + lang + '.min.%(version)s.js')) # </Webpack> css_common = Bundle( 'css/style.css', 'css/actions.css', 'css/breadcrumbs.css', 'css/buttons.css', 'css/contact.css', 'css/error.css', 'css/auth.css', 'css/magnific-popup.css', 'css/navbar.css', 'css/popup.css', 'css/react-select.css', 'css/tipsy.css', 'css/sprite.css', 'css/select2.css', 'css/select2-pootle.css', 'css/scores.css', 'css/user.css', 'css/welcome.css', filters='cssmin', output='css/common.min.%(version)s.css') register('css_common', css_common) css_admin = Bundle( 'css/admin.css', filters='cssmin', output='css/admin.min.%(version)s.css') register('css_admin', css_admin) css_editor = Bundle( 'css/editor.css', filters='cssmin', output='css/editor.min.%(version)s.css') register('css_editor', css_editor)
2,742
Python
.py
78
31.012821
78
0.67158
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,183
getters.py
translate_pootle/pootle/apps/pootle_app/getters.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from pootle.core.delegate import site from pootle.core.plugin import getter from .site import PootleSite pootle_site = PootleSite() @getter(site) def get_site(**kwargs_): return pootle_site
475
Python
.py
14
32.214286
77
0.773626
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,184
urls.py
translate_pootle/pootle/apps/pootle_app/urls.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django.conf.urls import include, url from .views.admin import urls as admin_urls urlpatterns = [ url(r'^admin/', include(admin_urls)), url(r'^xhr/admin/', include(admin_urls.api_patterns)), url(r'', include('pootle_app.views.index.urls')), ]
562
Python
.py
17
29.705882
77
0.702403
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,185
apps.py
translate_pootle/pootle/apps/pootle_app/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. """ Pootle App Config See https://docs.djangoproject.com/en/1.10/ref/applications/ """ import importlib from django.apps import AppConfig from django.core import checks # imported to force checks to run. FIXME use AppConfig from pootle import checks as pootle_checks # noqa from pootle.core.utils import deprecation class PootleConfig(AppConfig): name = "pootle_app" verbose_name = "Pootle" version = "0.0.8" def ready(self): checks.register(deprecation.check_deprecated_settings, "settings") importlib.import_module("pootle_app.getters") importlib.import_module("pootle_app.providers")
911
Python
.py
25
33.56
77
0.755404
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,186
site.py
translate_pootle/pootle/apps/pootle_app/site.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 urlparse import urlparse from django.conf import settings from django.contrib.sites.models import Site as ContribSite class PootleSite(object): @property def use_insecure_http(self): if not self.uses_sites: return urlparse(settings.POOTLE_CANONICAL_URL).scheme == "http" return ( getattr(settings, "USE_INSECURE_HTTP", False) and True or False) @property def use_http_port(self): if not self.uses_sites: return urlparse(settings.POOTLE_CANONICAL_URL).port or 80 return getattr(settings, "USE_HTTP_PORT", 80) @property def uses_sites(self): return ( "django.contrib.sites" not in settings.INSTALLED_APPS or not settings.POOTLE_CANONICAL_URL) @property def contrib_site(self): if self.uses_sites: return ContribSite.objects.get_current() @property def domain(self): if self.uses_sites: return self.contrib_site.domain return urlparse(settings.POOTLE_CANONICAL_URL).hostname @property def canonical_url(self): if not self.uses_sites: return settings.POOTLE_CANONICAL_URL protocol = ( "http" if self.use_insecure_http else "https") port = ( ":%s" % self.use_http_port if self.use_http_port != 80 else "") return ( "%s://%s%s" % (protocol, self.domain, port)) def build_absolute_uri(self, url): return "%s%s" % (self.canonical_url, url)
1,913
Python
.py
56
26
77
0.619718
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,187
providers.py
translate_pootle/pootle/apps/pootle_app/providers.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from pootle.core.delegate import panels from pootle.core.plugin import provider from pootle.core.views.browse import PootleBrowseView from .panels import ChildrenPanel @provider(panels, sender=PootleBrowseView) def children_panel_provider(**kwargs_): return dict(children=ChildrenPanel)
570
Python
.py
14
39.142857
77
0.802536
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,188
panels.py
translate_pootle/pootle/apps/pootle_app/panels.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.utils.safestring import mark_safe from pootle.core.browser import get_table_headings from pootle.core.decorators import persistent_property from pootle.core.views.panels import TablePanel from pootle.i18n.dates import timesince from .apps import PootleConfig class ChildrenPanel(TablePanel): ns = "pootle.app" sw_version = PootleConfig.version panel_name = "children" _table_fields = ( 'name', 'progress', 'activity', 'total', 'need-translation', 'suggestions', 'critical') @property def table_fields(self): fields = ( ("name", "total") if self.view.is_templates_context else self._table_fields) if self.view.has_admin_access: fields += ('last-updated', ) return fields @property def children(self): return self.view.object_children @property def table(self): if self.view.object_children: return { 'id': self.view.view_name, 'fields': self.table_fields, 'headings': get_table_headings(self.table_fields), 'rows': self.view.object_children} @persistent_property def _content(self): return self.render() @property def child_update_times(self): _times = {} for child in self.children: if not child.get("stats"): continue last_created_unit = ( timesince( child["stats"]["last_created_unit"]["creation_time"], locale=self.view.request_lang) if child["stats"].get("last_created_unit") else None) last_submission = ( timesince( child["stats"]["last_submission"]["mtime"], locale=self.view.request_lang) if child["stats"].get("last_submission") else None) _times[child["code"]] = (last_submission, last_created_unit) return _times @property def content(self): return self.update_times(self._content) def get_context_data(self): return dict( table=self.table, can_translate=self.view.can_translate) def update_times(self, content): times = {} update_times = self.child_update_times.items() for name, (last_submission, last_created_unit) in update_times: if last_submission: times[ "_XXX_LAST_SUBMISSION_%s_LAST_SUBMISSION_XXX_" % name] = last_submission if last_created_unit: times[ "_XXX_LAST_CREATED_%s_LAST_CREATED_XXX_" % name] = last_created_unit if times: regex = re.compile("(%s)" % "|".join(map(re.escape, times.keys()))) return mark_safe( regex.sub( lambda match: times[match.string[match.start():match.end()]], content)) return content
3,377
Python
.py
91
26.857143
81
0.577017
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,189
forms.py
translate_pootle/pootle/apps/pootle_app/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. import re import urlparse from collections import OrderedDict from django import forms from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError from pootle.i18n.gettext import ugettext_lazy as _ from pootle_fs.delegate import fs_plugins, fs_url_validator from pootle_language.models import Language from pootle_project.models import Project from pootle_store.models import Store LANGCODE_RE = re.compile("^[a-z]{2,}([_-]([a-z]{2,}|[0-9]{3}))*(@[a-z0-9]+)?$", re.IGNORECASE) class LanguageForm(forms.ModelForm): specialchars = forms.CharField(strip=False, required=False) class Meta(object): model = Language fields = ('id', 'code', 'fullname', 'specialchars', 'nplurals', 'pluralequation',) def clean_code(self): if (not self.cleaned_data['code'] == 'templates' and not LANGCODE_RE.match(self.cleaned_data['code'])): raise forms.ValidationError( _('Language code does not follow the ISO convention') ) return self.cleaned_data["code"] def clean_specialchars(self): """Ensures inputted characters are unique.""" chars = self.cleaned_data['specialchars'] return u''.join( OrderedDict((char, None) for char in list(chars)).keys() ) class ProjectForm(forms.ModelForm): source_language = forms.ModelChoiceField(queryset=Language.objects.none()) fs_plugin = forms.ChoiceField(choices=[], required=True) fs_url = forms.CharField(required=True) fs_mapping = forms.CharField(required=True) template_name = forms.CharField(required=False) class Meta(object): model = Project fields = ( 'id', 'code', 'fullname', 'checkstyle', 'filetypes', 'fs_plugin', 'fs_url', 'source_language', 'ignoredfiles', 'report_email', 'screenshot_search_prefix', 'disabled',) def __init__(self, *args, **kwargs): super(ProjectForm, self).__init__(*args, **kwargs) queryset = Language.objects.exclude(code='templates') self.fields['source_language'].queryset = queryset self.fields["filetypes"].initial = [ self.fields["filetypes"].queryset.get(name="po")] self.fields["fs_plugin"].choices = [(x, x) for x in fs_plugins.gather()] self.fields["template_name"].initial = ( self.instance.lang_mapper.get_upstream_code("templates")) def clean_filetypes(self): value = self.cleaned_data.get('filetypes', []) if not self.instance.pk: return value for filetype in self.instance.filetypes.all(): if filetype not in value: has_stores = Store.objects.filter( translation_project__project=self.instance, filetype=filetype) if has_stores.exists(): raise forms.ValidationError( _("You cannot remove a file type from a Project, " "if there are files of that file type ('%s')") % filetype) return value def clean_fullname(self): return self.cleaned_data['fullname'].strip() def clean_code(self): return self.cleaned_data['code'].strip() def clean_template_name(self): return self.cleaned_data['template_name'].strip() def clean_fs_mapping(self): fs_mapping = self.cleaned_data["fs_mapping"].strip() bad = ( not fs_mapping.startswith("/") or not fs_mapping.endswith(".<ext>") or "<language_code>" not in fs_mapping) if bad: raise forms.ValidationError( _('Path mapping must start with "/", end with ".<ext>", and ' 'contain "<language_code>"')) return fs_mapping def clean(self): fs_plugin = self.cleaned_data.get("fs_plugin") if not fs_plugin: return plugin = fs_plugins.gather()[fs_plugin] fs_url = self.cleaned_data.get("fs_url") if not fs_url: return validator = fs_url_validator.get(plugin)() try: validator.validate(fs_url) except ValidationError: self.errors["fs_url"] = self.error_class( [_("Invalid Path or URL for chosen Filesystem backend " "'%s'") % self.cleaned_data["fs_plugin"]]) def save(self, commit=True): project = super(ProjectForm, self).save(commit=commit) project.config["pootle_fs.fs_type"] = self.cleaned_data["fs_plugin"] project.config["pootle_fs.fs_url"] = self.cleaned_data["fs_url"] project.config["pootle_fs.translation_mappings"] = dict( default=self.cleaned_data["fs_mapping"]) lang_mapping = dict( (v, k) for k, v in project.config.get("pootle.core.lang_mapping", {}).iteritems()) if self.cleaned_data["template_name"] in ["templates", ""]: if "templates" in lang_mapping: del lang_mapping["templates"] else: lang_mapping["templates"] = self.cleaned_data["template_name"] project.config["pootle.core.lang_mapping"] = dict( (v, k) for k, v in lang_mapping.iteritems()) return project class UserForm(forms.ModelForm): password = forms.CharField(label=_('Password'), required=False, widget=forms.PasswordInput) class Meta(object): model = get_user_model() fields = ('id', 'username', 'is_active', 'full_name', 'email', 'is_superuser', 'twitter', 'linkedin', 'website', 'bio') def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) # Require setting the password for new users if self.instance.pk is None: self.fields['password'].required = True def save(self, commit=True): password = self.cleaned_data['password'] if password != '': user = super(UserForm, self).save(commit=False) user.set_password(password) if commit: user.save() else: user = super(UserForm, self).save(commit=commit) return user def clean_linkedin(self): url = self.cleaned_data['linkedin'] if url != '': parsed = urlparse.urlparse(url) if 'linkedin.com' not in parsed.netloc or parsed.path == '/': raise forms.ValidationError( _('Please enter a valid LinkedIn user profile URL.') ) return url class PermissionsUsersSearchForm(forms.Form): q = forms.CharField(max_length=255) def __init__(self, *args, **kwargs): self.directory = kwargs.pop("directory") super(PermissionsUsersSearchForm, self).__init__(*args, **kwargs) def search(self): existing_permission_users = ( self.directory.permission_sets.values_list("user")) users = get_user_model().objects.exclude( pk__in=existing_permission_users) return dict( results=[ dict(id=int(m["id"]), text=m["username"]) for m in (users.filter(username__contains=self.cleaned_data["q"]) .values("id", "username").order_by("username"))])
7,734
Python
.py
172
34.906977
82
0.601463
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,190
__init__.py
translate_pootle/pootle/apps/pootle_app/models/__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 pootle_app.models.directory import Directory from pootle_app.models.permissions import PermissionSet __all__ = ("Directory", "PermissionSet")
425
Python
.py
10
41.2
77
0.774272
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,191
directory.py
translate_pootle/pootle/apps/pootle_app/models/directory.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.contenttypes.fields import GenericRelation from django.core.exceptions import ValidationError from django.db import models from django.urls import reverse from django.utils.functional import cached_property from pootle.core.delegate import data_tool from pootle.core.mixins import CachedTreeItem from pootle.core.url_helpers import get_editor_filter, split_pootle_path from pootle_misc.baseurl import link from pootle_revision.models import Revision class DirectoryManager(models.Manager): def live(self): """Filters non-obsolete directories.""" return self.filter(obsolete=False) @cached_property def root(self): return self.get(pootle_path='/') @cached_property def projects(self): return self.get(pootle_path='/projects/') def validate_no_slashes(value): if '/' in value: raise ValidationError('Directory name cannot contain "/" characters') if '\\' in value: raise ValidationError('Directory name cannot contain "\\" characters') class Directory(models.Model, CachedTreeItem): # any changes to the `name` field may require updating the schema # see migration 0005_case_sensitive_schema.py name = models.CharField(max_length=255, null=False, blank=True, validators=[validate_no_slashes]) parent = models.ForeignKey('Directory', related_name='child_dirs', null=True, blank=True, db_index=True, on_delete=models.CASCADE) # any changes to the `pootle_path` field may require updating the schema # see migration 0005_case_sensitive_schema.py pootle_path = models.CharField(max_length=255, null=False, db_index=True, unique=True, default='/') tp = models.ForeignKey( 'pootle_translationproject.TranslationProject', related_name='dirs', on_delete=models.CASCADE, null=True, blank=True, db_index=True) tp_path = models.CharField( max_length=255, null=True, blank=True, db_index=True) obsolete = models.BooleanField(default=False) revisions = GenericRelation(Revision) is_dir = True objects = DirectoryManager() class Meta(object): ordering = ['name'] default_permissions = () app_label = "pootle_app" index_together = [ ["obsolete", "pootle_path"], ["obsolete", "tp", "tp_path"]] base_manager_name = "objects" @cached_property def data_tool(self): return data_tool.get(self.__class__)(self) # # # # # # # # # # # # # # Properties # # # # # # # # # # # # # # # # # # @property def code(self): return self.name.replace('.', '-') # # # # # # # # # # # # # # Cached properties # # # # # # # # # # # # # # @cached_property def path(self): """Returns just the path part omitting language and project codes.""" return self.tp_path @cached_property def translation_project(self): """Returns the translation project belonging to this directory.""" if self.tp_id is not None: return self.tp return self.translationproject # # # # # # # # # # # # # # Methods # # # # # # # # # # # # # # # # # # # def __unicode__(self): return self.pootle_path def __init__(self, *args, **kwargs): super(Directory, self).__init__(*args, **kwargs) def clean(self): if self.parent is not None: self.pootle_path = self.parent.pootle_path + self.name + '/' set_tp_path = ( self.parent is not None and self.parent.parent is not None and self.parent.name != "projects") if set_tp_path: self.tp_path = ( "/" if self.parent.tp_path is None else "/".join([self.parent.tp_path.rstrip("/"), self.name, ""])) if self.name == '' and self.parent is not None: raise ValidationError('Name can be empty only for root directory.') if self.parent is None and self.name != '': raise ValidationError('Parent can be unset only for root ' 'directory.') def save(self, *args, **kwargs): # Force validation of fields. self.full_clean(validate_unique=False) super(Directory, self).save(*args, **kwargs) def get_absolute_url(self): return link(self.pootle_path) def get_translate_url(self, **kwargs): lang_code, proj_code, dir_path = split_pootle_path(self.pootle_path)[:3] if lang_code and proj_code: pattern_name = 'pootle-tp-translate' pattern_args = [lang_code, proj_code, dir_path] elif lang_code: pattern_name = 'pootle-language-translate' pattern_args = [lang_code] elif proj_code: pattern_name = 'pootle-project-translate' pattern_args = [proj_code] else: pattern_name = 'pootle-projects-translate' pattern_args = [] return u''.join([ reverse(pattern_name, args=pattern_args), get_editor_filter(**kwargs), ]) # # # TreeItem def get_children(self): result = [] if not self.is_projects_root(): # FIXME: can we replace this with a quicker path query? result.extend([item for item in self.child_stores.live().iterator()]) result.extend([item for item in self.child_dirs.live().iterator()]) else: project_list = [item.project for item in self.child_dirs.iterator() if not item.project.disabled] result.extend(project_list) return result def get_parents(self): if self.parent: if self.is_translationproject(): return self.translationproject.get_parents() elif self.is_project(): return self.project.get_parents() elif self.is_language(): return self.language.get_parents() elif self.parent.is_translationproject(): return [self.parent.translationproject] else: return [self.parent] else: return [] # # # /TreeItem def get_or_make_subdir(self, child_name): child_dir, created = Directory.objects.get_or_create( name=child_name, parent=self) if created and self.tp: child_dir.tp = self.tp child_dir.save() return child_dir def trail(self, only_dirs=True): """Returns a list of ancestor directories excluding :cls:`~pootle_translationproject.models.TranslationProject` and above. """ path_parts = self.pootle_path.split('/') parents = [] if only_dirs: # skip language, and translation_project directories start = 4 else: start = 1 for i in xrange(start, len(path_parts)): path = '/'.join(path_parts[:i]) + '/' parents.append(path) if parents: return Directory.objects.live().filter(pootle_path__in=parents) \ .order_by('pootle_path') return Directory.objects.none() def is_language(self): """does this directory point at a language""" return (self.pootle_path.count('/') == 2 and not self.pootle_path.startswith('/projects/')) def is_project(self): return (self.pootle_path.startswith('/projects/') and self.pootle_path.count('/') == 3) def is_translationproject(self): """does this directory point at a translation project""" return (self.pootle_path.count('/') == 3 and not self.pootle_path.startswith('/projects/')) def is_projects_root(self): """is this directory a projects root directory""" return self.pootle_path == '/projects/' def delete(self, *args, **kwargs): self.initialize_children() for item in self.children: item.delete() super(Directory, self).delete(*args, **kwargs) def makeobsolete(self, *args, **kwargs): """Make this directory and all its children obsolete""" self.initialize_children() for item in self.children: item.makeobsolete() self.obsolete = True self.save()
8,901
Python
.py
213
32
80
0.593214
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,192
permissions.py
translate_pootle/pootle/apps/pootle_app/models/permissions.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType from django.db import models from .directory import Directory def get_permission_contenttype(): content_type = ContentType.objects.get_for_model(Directory) return content_type def get_pootle_permission(codename): # The content type of our permission content_type = get_permission_contenttype() # Get the pootle view permission return Permission.objects.get(content_type=content_type, codename=codename) def get_permissions_by_user(user, directory): pootle_path = directory.pootle_path path_parts = filter(None, pootle_path.split('/')) try: permissionset = user.permissionset_set.select_related("directory").filter( directory__in=directory.trail( only_dirs=False)).order_by('-directory__pootle_path')[0] except IndexError: permissionset = None check_project_permissions = ( (len(path_parts) > 1 and path_parts[0] != 'projects' and (permissionset is None or len( filter( None, permissionset.directory.pootle_path.split('/'))) < 2))) if check_project_permissions: # Active permission at language level or higher, check project # level permission try: project_path = '/projects/%s/' % path_parts[1] permissionset = user.permissionset_set.select_related("directory").get( directory__pootle_path=project_path) except PermissionSet.DoesNotExist: pass if permissionset: return permissionset.to_dict() else: return None def get_matching_permissions(user, directory, check_default=True): User = get_user_model() if user.is_authenticated: permissions = get_permissions_by_user(user, directory) if permissions is not None: return permissions if not check_default: return {} permissions = get_permissions_by_user( User.objects.get_default_user(), directory) if permissions is not None: return permissions permissions = get_permissions_by_user( User.objects.get_nobody_user(), directory) return permissions def check_user_permission(user, permission_codename, directory, check_default=True): """Checks if the current user has the permission to perform ``permission_codename``. """ if user.is_superuser: return True permissions = get_matching_permissions(user, directory, check_default) return ("administrate" in permissions or permission_codename in permissions) def check_permission(permission_codename, request): """Checks if the current user has `permission_codename` permissions. """ if request.user.is_superuser: return True # `view` permissions are project-centric, and we must treat them # differently if permission_codename == 'view': path_obj = None if hasattr(request, 'translation_project'): path_obj = request.translation_project elif hasattr(request, 'project'): path_obj = request.project if path_obj is None: return True # Always allow to view language pages return path_obj.is_accessible_by(request.user) return ("administrate" in request.permissions or permission_codename in request.permissions) class PermissionSet(models.Model): class Meta(object): unique_together = ('user', 'directory') app_label = "pootle_app" user = models.ForeignKey( settings.AUTH_USER_MODEL, db_index=False, on_delete=models.CASCADE) directory = models.ForeignKey('pootle_app.Directory', db_index=True, related_name='permission_sets', on_delete=models.CASCADE) positive_permissions = models.ManyToManyField( Permission, db_index=True, related_name='permission_sets_positive') negative_permissions = models.ManyToManyField( Permission, db_index=True, related_name='permission_sets_negative') def __unicode__(self): return "%s : %s" % (self.user.username, self.directory.pootle_path) def to_dict(self): permissions_iterator = self.positive_permissions.iterator() return dict((perm.codename, perm) for perm in permissions_iterator)
4,924
Python
.py
116
34.12069
83
0.668203
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,193
0016_set_directory_tp_again.py
translate_pootle/pootle/apps/pootle_app/migrations/0016_set_directory_tp_again.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.11 on 2016-11-02 18:58 from __future__ import unicode_literals from django.db import migrations def set_directory_tp_again(apps, schema_editor): dirs = apps.get_model("pootle_app.Directory").objects.all() TP = apps.get_model("pootle_translationproject.TranslationProject") for tp in TP.objects.all(): dirs.filter(pootle_path__startswith=tp.pootle_path).update(tp=tp) class Migration(migrations.Migration): dependencies = [ ('pootle_app', '0015_add_tp_path_idx'), ('pootle_translationproject', '0005_remove_empty_translationprojects'), ] operations = [ migrations.RunPython(set_directory_tp_again), ]
718
Python
.py
17
37.235294
79
0.705628
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,194
0013_directory_tp_path.py
translate_pootle/pootle/apps/pootle_app/migrations/0013_directory_tp_path.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.11 on 2016-11-04 09:15 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pootle_app', '0012_set_directory_tp'), ] operations = [ migrations.AddField( model_name='directory', name='tp_path', field=models.CharField(blank=True, db_index=True, max_length=255, null=True), ), ]
493
Python
.py
15
26.466667
89
0.630021
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,195
0018_set_directory_base_manager_name.py
translate_pootle/pootle/apps/pootle_app/migrations/0018_set_directory_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_app', '0017_drop_stray_directories'), ] operations = [ migrations.AlterModelOptions( name='directory', options={'base_manager_name': 'objects', 'default_permissions': (), 'ordering': ['name']}, ), ]
479
Python
.py
14
28.285714
102
0.632609
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,196
0002_mark_empty_dirs_as_obsolete.py
translate_pootle/pootle/apps/pootle_app/migrations/0002_mark_empty_dirs_as_obsolete.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def make_dir_obsolete(directory): """Make directory and its parents obsolete if a parent contains one empty directory only """ p = directory.parent if p is not None and p.child_dirs.filter(obsolete=False).count() == 1: make_dir_obsolete(p) directory.obsolete = True directory.save() def make_empty_directories_obsolete(apps, schema_editor): Directory = apps.get_model("pootle_app", "Directory") from pootle.core.url_helpers import split_pootle_path for d in Directory.objects.filter(child_stores__isnull=True, child_dirs__isnull=True, obsolete=False): lang_code, prj_code, dir_path = split_pootle_path(d.pootle_path)[:3] # makeobsolete translation project directories and lower # and do not touch language and project directories if lang_code and prj_code: make_dir_obsolete(d) class Migration(migrations.Migration): dependencies = [ ('pootle_app', '0001_initial'), ('pootle_store', '0001_initial'), ] operations = [ migrations.RunPython(make_empty_directories_obsolete), ]
1,298
Python
.py
31
33.806452
77
0.654459
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,197
0006_change_administrate_permission_name.py
translate_pootle/pootle/apps/pootle_app/migrations/0006_change_administrate_permission_name.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models def change_administrate_permission_name(apps, schema_editor): Permission = apps.get_model("auth", "Permission") Permission.objects.filter( codename='administrate' ).update( name='Can perform administrative tasks' ) class Migration(migrations.Migration): dependencies = [ ('pootle_app', '0005_case_sensitive_schema'), ] operations = [ migrations.RunPython(change_administrate_permission_name), ]
572
Python
.py
17
28.411765
66
0.698355
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,198
0003_drop_existing_directory_default_permissions.py
translate_pootle/pootle/apps/pootle_app/migrations/0003_drop_existing_directory_default_permissions.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models def drop_existing_directory_default_permissions(apps, schema_editor): Permission = apps.get_model("auth", "Permission") Permission.objects.filter( codename__in=['add_directory', 'change_directory', 'delete_directory'] ).delete() class Migration(migrations.Migration): dependencies = [ ('pootle_app', '0002_mark_empty_dirs_as_obsolete'), ] operations = [ migrations.RunPython(drop_existing_directory_default_permissions), ]
588
Python
.py
15
34.2
78
0.706195
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
15,199
0014_set_directory_tp_path.py
translate_pootle/pootle/apps/pootle_app/migrations/0014_set_directory_tp_path.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.10 on 2016-11-02 18:25 from __future__ import unicode_literals from django.db import migrations def set_directory_tp_path(apps, schema_editor): dirs = apps.get_model("pootle_app.Directory").objects.all() for directory in dirs: if not directory.parent: continue parts = directory.pootle_path.lstrip("/").split("/") if len(parts) > 2: directory.tp_path = '/'.join([""] + parts[2:]) directory.save() class Migration(migrations.Migration): dependencies = [ ('pootle_app', '0013_directory_tp_path'), ] operations = [ migrations.RunPython(set_directory_tp_path), ]
717
Python
.py
20
29.45
63
0.63135
translate/pootle
1,486
288
526
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)