class IPPointMixin(): """ Mixin de méthodes pour les modèles pointant vers une adresse IP """ if apps.is_installed('scoop.user.access'): # Getter def get_ip(self): """ Renvoyer l'objet IP lié """ return self.ip def get_ip_address(self): """ Renvoyer l'adresse IP au format A.B.C.D """ return IP_(self.ip).strNormal() # Setter def set_ip(self, ip): """ Définir une IP pour l'objet :param ip: ip de la forme A.B.C.D """ from scoop.user.access.models.ip import IP # Ne pas sauvegarder automatiquement la modification self.ip = IP.objects.get_by_ip(ip) # Overrides def __str__(self): """ Renvoyer la représentation unicode de l'objet """ return _("{}").format(self.get_ip()) # Propriétés ip_address = property(get_ip, set_ip)
def get_country(self): """ Renvoyer l'instance Country pour l'IP """ if not apps.is_installed('scoop.location'): return None from scoop.location.models import Country # Renvoyer le pays correspondant au code, ou aucun si A1, A2 etc. return Country.objects.get_by_code2_or_none(self.country)
def backup_database(): """ Effectuer un backup de la base de données """ if apps.is_installed('dbbackup'): call_command('dbbackup', clean=True, compress=True, encrypt=False, database='default')
def can_send_email(xfer): from django.utils.module_loading import import_module from django.apps.registry import apps if apps.is_installed("lucterios.mailing"): fct_mailing_mod = import_module('lucterios.mailing.functions') return fct_mailing_mod.will_mail_send() else: return False
def clean_media_folders(): """ Nettoyer les fichiers orphelins des répertoires MEDIA """ if apps.is_installed('scoop.content'): from scoop.content.models.picture import Picture # Nettoyer les miniatures Picture.objects.clean_thumbnails() # Supprimer les fichiers sans référence clean_orphans(output_log=False, delete=True) clean_empty_folders(settings.MEDIA_ROOT)
class IPPointModel(models.Model, IPPointMixin): """ Mixin de modèle pointant vers une adresse IP """ if apps.is_installed('scoop.user.access'): ip = models.ForeignKey('access.IP', editable=False, verbose_name=_("IP")) # Métadonnées class Meta: abstract = True
class OptionGroup(TranslatableModel, PicturableModel if apps.is_installed('scoop.content') else Model): """ Groupe d'options """ # Choix de codes CODES = [[i, i] for i in range(100)] # Champs code = models.SmallIntegerField(null=False, blank=False, default=0, verbose_name=_("Code")) short_name = models.CharField(max_length=32, unique=True, verbose_name=_("Short name")) objects = OptionGroupManager() # Getter @addattr(short_description=_("Name")) def get_name(self): """ Renvoyer le nom du groupe """ try: return self.get_translation().name except MissingTranslation: return _("(No name)") @addattr(short_description=_("Description")) def get_description(self): """ Renvoyer la description du groupe """ try: return self.get_translation().description except MissingTranslation: return _("(No description)") def get_options(self, active_only=True): """ Renvoyer les options du groupe """ criteria = {'active': True} if active_only else {} return self.options.filter(**criteria).order_by('code') # Propriétés name = property(get_name) description = property(get_description) # Overrides def __str__(self): """ Renvoyer la représentation unicode de l'objet """ return "%(id)s : %(name)s" % {'id': self.id, 'name': self.get_name() or self.short_name, 'short': self.short_name} def save(self, *args, **kwargs): """ Enregistrer l'objet dans la base de données """ super(OptionGroup, self).save(*args, **kwargs) def natural_key(self): return self.short_name, # Métadonnées class Meta: verbose_name = _("option group") verbose_name_plural = _("option groups") ordering = ['id'] app_label = 'core'
def get_autocomplete_queryset(self, request, field_name): """ Renvoyer le queryset utilisé pour autocomplete """ if apps.is_installed('scoop.location') and field_name == 'city': from scoop.location.models import City # Uniquement les communes et villes return City.objects.filter(city=True) elif field_name == 'picture': from scoop.content.models import Picture # Toutes les images return Picture.objects.all() return None
class IPPointableModel(models.Model, IPPointMixin): """ Mixin de modèle pouvant pointer vers une IP """ if apps.is_installed('scoop.user.access'): ip = models.ForeignKey('access.IP', db_index=True, blank=True, null=True, on_delete=models.SET_NULL, related_name='+', verbose_name=_("IP")) # Métadonnées class Meta: abstract = True
def is_app_registered(app): """Return whether the app registry is tracking a given app. Args: app (module): The app to check for. Returns: bool: ``True`` if the app is tracked by the registry. ``False`` if not. """ if apps: # Django >= 1.7 return apps.is_installed(app.__name__) else: # Django < 1.7 return app in cache.app_store
def get_queryset(self, request): """ Renvoyer le queryset par défaut """ qs = super(ProfileAdmin, self).get_queryset(request) field_list = ( 'user__username', 'user__id', 'picture', 'picture__id', 'picture__image', 'gender', 'birth', 'user__email', 'user__date_joined', ) if apps.is_installed('scoop.location'): field_list += ('city__id', ) qs = qs.select_related('user', 'picture').only(*field_list) return qs
def get_closest_city(self): """ Renvoyer l'instance de City la plus proche des coordonnées GPS de l'adresse IP '""" if not apps.is_installed('scoop.location'): return None try: from scoop.location.models import City if self.string in settings.INTERNAL_IPS: return IP.objects.get_by_ip( settings.PUBLIC_IP).get_closest_city() # Trouver la ville la plus proche des coordonnées GPS de l'IP, portant idéalement un nom geoip = self.get_geoip() or dict() if geoip.get('latitude', 0) != 0: point, name = [geoip['latitude'], geoip['longitude']], geoip['city'] return City.objects.find_by_name(point, name=name) return None except Exception: return None
class Option(TranslatableModel, UUID64Model, PicturableModel if apps.is_installed('scoop.content') else Model): """ Option """ # Choix de codes CODES = [[i, i] for i in range(200)] # Champs group = models.ForeignKey('core.OptionGroup', null=False, blank=False, related_name='options', verbose_name=_("Group")) code = models.SmallIntegerField(null=False, blank=False, choices=CODES, db_index=False, verbose_name=_("Code")) active = models.BooleanField(default=True, verbose_name=pgettext_lazy( 'option', "Active")) parent = models.ForeignKey('core.Option', null=True, blank=True, related_name='children', on_delete=models.SET_NULL, verbose_name=_("Parent")) objects = OptionManager() # Getter def natural_key(self): """ Renvoyer la clé naturelle de l'objet """ return self.group, self.code @addattr(short_description=_("Name")) def get_name(self): """ Renvoyer le nom de l'option """ try: return self.get_translation().name except MissingTranslation: return ugettext("(No name)") @addattr(short_description=_("Description")) def get_description(self): """ Renvoyer la description de l'option """ try: return self.get_translation().description except MissingTranslation: return ugettext("(No description)") def get_children(self): """ Renvoyer les descendants de l'option """ return Option.objects.filter(parent=self) def has_children(self): """ Renvoyer si l'option a des descendants """ return self.get_children().exists() def get_tree(self): """ Renvoyer la hiérarchie de l'option """ instance, items = self, [] while instance is not None: items.append(instance) instance = instance.parent items.append(self.group) return items.reverse() def html(self, mode='default', **kwargs): """ Renvoyer une représentation HTML de l'option """ kwargs['item'] = self return render_to_string([ "mako/core/display/option-{mode}.html".format(mode=mode), "core/display/option-{mode}.html".format(mode=mode) ], kwargs) # Propriétés name = property(get_name) description = property(get_description) # Overrides def __str__(self): """ Renvoyer une représentation unicode de l'objet """ return self.get_name() def __repr__(self): """ Renvoyer une représentation ASCII de l'objet """ return unidecode(self.get_name()) def save(self, *args, **kwargs): """ Enregistrer l'objet dans la base de données """ super(Option, self).save(*args, **kwargs) # Métadonnées class Meta: verbose_name = _("option") verbose_name_plural = _("options") unique_together = [['group', 'code']] ordering = ['code'] app_label = 'core'
include_docs_urls(title=API_TITLE, description=API_DESCRIPTION, permission_classes=[permissions.IsAdminUser])), re_path(r'swagger(?P<format>.json|.yaml)', schema_view.without_ui(), name='schema-json'), path('swagger/', schema_view.with_ui(), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui('redoc'), name='schema-redoc') ] # Railgun S urlpatterns += [ re_path(r'download_url/(?P<cloud>(aliyun|oss))/$', download_url, name='download-url'), re_path(r'upload_params/(?P<cloud>(aliyun|oss|aws|s3))/$', upload_params, name='upload-params'), path( 'favicon.ico', RedirectView.as_view(url='{}favicon.ico'.format(settings.STATIC_URL), permanent=True)) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if apps.is_installed('rosetta'): urlpatterns += [path('rosetta/', include('rosetta.urls'))] admin.site.site_header = _('app_name') admin.site.site_title = _('app_name')
def wrapped(*args, **kwargs): app_names = app_name if type(app_name) == list else [app_name] if all(apps.is_installed(app_name) for app_name in app_names): return func(*args, **kwargs) return retval
class PrivacyModel(models.Model): """ Mixin de modèle avec contrôle d'accès """ # Constantes ACCESS_TYPES = [[0, _("Public")], [1, _("Friends")], [2, _("Personal")], [3, _("Friend groups")], [4, _("Registered users")]] PUBLIC, FRIENDS, PERSONAL, CUSTOM, REGISTERED = 0, 1, 2, 3, 4 if apps.is_installed('scoop.user.social'): # Champs access = models.SmallIntegerField(choices=ACCESS_TYPES, default=0, db_index=True, verbose_name=_("Access")) # Getter def is_user_granted_custom(self, user): """ Renvoyer si un utilisateur fait partie des utilisateurs/groupes autorisés """ from scoop.user.social.models import FriendGroup grants = self.get_data('privacy') users = grants.get('users', []) groups = grants.get('groups', []) # Si l'utilisateur lui-même est répertorié, c'est bon if user.pk in users: return True # Si l'un des groupes d'amis répertoriés contient l'utilisateur, c'est bon for grant in FriendGroup.objects.filter(pk__in=groups): if grant.group.has_member(user): return True return False def is_accessible(self, user): """ Renvoyer si un utilisateur a accès au contenu """ if user.has_perm('content.can_access_all_content'): return True elif self.access == PrivacyModel.PUBLIC: # Public return True elif self.access == PrivacyModel.FRIENDS: # Ami avec l'auteur from scoop.user.social.models import FriendList # C'est un succès si une amitié existe if FriendList.objects.exists(user, self.author): return True elif self.access == PrivacyModel.PERSONAL and user == self.author: # Seulement moi return True elif self.access == PrivacyModel.REGISTERED: # Membres connectés return user.is_authenticated() elif self.access == PrivacyModel.CUSTOM: # Dans un groupe d'amis autorisé return self.is_user_granted_custom(user) return False # Setter def set_user_grants(self, users): """ Définir les utilisateurs autorisés à afficher le contenu """ grants = self.get_data('privacy') grants['users'] = [user.pk for user in users] self.set_data('privacy', grants, save=True) def set_group_grants(self, groups): """ Définir les groupes autorisés à afficher le contenu """ grants = self.get_data('privacy') grants['groups'] = [group.pk for group in groups] self.set_data('privacy', grants, save=True) def reset_custom_grants(self): """ Réinitialiser les autorisations d'accès particulières """ self.set_data('privacy', dict(), save=True) # Métadonnées class Meta: abstract = True
rmtree(tmp_dir) makedirs(tmp_dir) try: self.item.extract_files(tmp_dir) with ZipFile(download_file, 'w') as zip_ref: for (dirpath, _dirs, filenames) in walk(tmp_dir): for filename in filenames: zip_ref.write(join(dirpath, filename), join(dirpath[len(tmp_dir):], filename)) finally: if exists(tmp_dir): rmtree(tmp_dir) self.open_zipfile('extract.zip') if not apps.is_installed("lucterios.contacts"): MenuManage.add_sub("office", None, "lucterios.documents/images/office.png", _("Office"), _("Office tools"), 70) MenuManage.add_sub("documents.actions", "office", "lucterios.documents/images/document.png", _("Documents management"), _("Documents storage tools"), 80) def docshow_modify_condition(xfer): if xfer.item.parent is not None and notfree_mode_connect( ) and not xfer.request.user.is_superuser: if xfer.item.parent.cannot_view(xfer.request.user): raise LucteriosException(IMPORTANT, _("No allow to view!")) if xfer.item.parent.is_readonly(xfer.request.user): return False