Commit e7de8b2a authored by Krophil's avatar Krophil
Browse files

Format core

parent 4f4ea5dd
...@@ -33,8 +33,9 @@ admin.site.unregister(AuthGroup) ...@@ -33,8 +33,9 @@ admin.site.unregister(AuthGroup)
admin.site.register(RealGroup) admin.site.register(RealGroup)
admin.site.register(Page) admin.site.register(Page)
@admin.register(SithFile) @admin.register(SithFile)
class SithFileAdmin(admin.ModelAdmin): class SithFileAdmin(admin.ModelAdmin):
form = make_ajax_form(SithFile, { form = make_ajax_form(SithFile, {
'parent': 'files', # ManyToManyField 'parent': 'files', # ManyToManyField
}) })
...@@ -23,9 +23,9 @@ ...@@ -23,9 +23,9 @@
# #
from django.apps import AppConfig from django.apps import AppConfig
from django.dispatch import receiver
from django.core.signals import request_started from django.core.signals import request_started
class SithConfig(AppConfig): class SithConfig(AppConfig):
name = 'core' name = 'core'
verbose_name = "Core app of the Sith" verbose_name = "Core app of the Sith"
...@@ -48,4 +48,3 @@ class SithConfig(AppConfig): ...@@ -48,4 +48,3 @@ class SithConfig(AppConfig):
request_started.connect(clear_cached_groups, weak=False, dispatch_uid="clear_cached_groups") request_started.connect(clear_cached_groups, weak=False, dispatch_uid="clear_cached_groups")
request_started.connect(clear_cached_memberships, weak=False, dispatch_uid="clear_cached_memberships") request_started.connect(clear_cached_memberships, weak=False, dispatch_uid="clear_cached_memberships")
# TODO: there may be a need to add more cache clearing # TODO: there may be a need to add more cache clearing
...@@ -31,16 +31,19 @@ from club.models import Club ...@@ -31,16 +31,19 @@ from club.models import Club
from counter.models import Product, Counter from counter.models import Product, Counter
from accounting.models import ClubAccount, Company from accounting.models import ClubAccount, Company
def check_token(request): def check_token(request):
return ('counter_token' in request.session.keys() and return ('counter_token' in request.session.keys() and
request.session['counter_token'] and request.session['counter_token'] and
Counter.objects.filter(token=request.session['counter_token']).exists()) Counter.objects.filter(token=request.session['counter_token']).exists())
class RightManagedLookupChannel(LookupChannel): class RightManagedLookupChannel(LookupChannel):
def check_auth(self, request): def check_auth(self, request):
if not request.user.was_subscribed and not check_token(request): if not request.user.was_subscribed and not check_token(request):
raise PermissionDenied raise PermissionDenied
@register('users') @register('users')
class UsersLookup(RightManagedLookupChannel): class UsersLookup(RightManagedLookupChannel):
model = User model = User
...@@ -54,6 +57,7 @@ class UsersLookup(RightManagedLookupChannel): ...@@ -54,6 +57,7 @@ class UsersLookup(RightManagedLookupChannel):
def format_item_display(self, item): def format_item_display(self, item):
return item.get_display_name() return item.get_display_name()
@register('groups') @register('groups')
class GroupsLookup(RightManagedLookupChannel): class GroupsLookup(RightManagedLookupChannel):
model = Group model = Group
...@@ -67,6 +71,7 @@ class GroupsLookup(RightManagedLookupChannel): ...@@ -67,6 +71,7 @@ class GroupsLookup(RightManagedLookupChannel):
def format_item_display(self, item): def format_item_display(self, item):
return item.name return item.name
@register('clubs') @register('clubs')
class ClubLookup(RightManagedLookupChannel): class ClubLookup(RightManagedLookupChannel):
model = Club model = Club
...@@ -80,6 +85,7 @@ class ClubLookup(RightManagedLookupChannel): ...@@ -80,6 +85,7 @@ class ClubLookup(RightManagedLookupChannel):
def format_item_display(self, item): def format_item_display(self, item):
return item.name return item.name
@register('counters') @register('counters')
class CountersLookup(RightManagedLookupChannel): class CountersLookup(RightManagedLookupChannel):
model = Counter model = Counter
...@@ -90,6 +96,7 @@ class CountersLookup(RightManagedLookupChannel): ...@@ -90,6 +96,7 @@ class CountersLookup(RightManagedLookupChannel):
def format_item_display(self, item): def format_item_display(self, item):
return item.name return item.name
@register('products') @register('products')
class ProductsLookup(RightManagedLookupChannel): class ProductsLookup(RightManagedLookupChannel):
model = Product model = Product
...@@ -101,6 +108,7 @@ class ProductsLookup(RightManagedLookupChannel): ...@@ -101,6 +108,7 @@ class ProductsLookup(RightManagedLookupChannel):
def format_item_display(self, item): def format_item_display(self, item):
return "%s (%s)" % (item.name, item.code) return "%s (%s)" % (item.name, item.code)
@register('files') @register('files')
class SithFileLookup(RightManagedLookupChannel): class SithFileLookup(RightManagedLookupChannel):
model = SithFile model = SithFile
...@@ -108,6 +116,7 @@ class SithFileLookup(RightManagedLookupChannel): ...@@ -108,6 +116,7 @@ class SithFileLookup(RightManagedLookupChannel):
def get_query(self, q, request): def get_query(self, q, request):
return self.model.objects.filter(name__icontains=q)[:50] return self.model.objects.filter(name__icontains=q)[:50]
@register('club_accounts') @register('club_accounts')
class ClubAccountLookup(RightManagedLookupChannel): class ClubAccountLookup(RightManagedLookupChannel):
model = ClubAccount model = ClubAccount
...@@ -118,6 +127,7 @@ class ClubAccountLookup(RightManagedLookupChannel): ...@@ -118,6 +127,7 @@ class ClubAccountLookup(RightManagedLookupChannel):
def format_item_display(self, item): def format_item_display(self, item):
return item.name return item.name
@register('companies') @register('companies')
class CompaniesLookup(RightManagedLookupChannel): class CompaniesLookup(RightManagedLookupChannel):
model = Company model = Company
......
...@@ -21,4 +21,3 @@ ...@@ -21,4 +21,3 @@
# Place - Suite 330, Boston, MA 02111-1307, USA. # Place - Suite 330, Boston, MA 02111-1307, USA.
# #
# #
...@@ -44,7 +44,6 @@ class Command(BaseCommand): ...@@ -44,7 +44,6 @@ class Command(BaseCommand):
args['precision'] = settings.SASS_PRECISION args['precision'] = settings.SASS_PRECISION
return sass.compile(**args) return sass.compile(**args)
def is_compilable(self, file, ext_list): def is_compilable(self, file, ext_list):
path, ext = os.path.splitext(file) path, ext = os.path.splitext(file)
return ext in ext_list return ext in ext_list
......
This diff is collapsed.
...@@ -23,9 +23,8 @@ ...@@ -23,9 +23,8 @@
# #
import os import os
from django.core.management.base import BaseCommand, CommandError from django.core.management.base import BaseCommand
from django.core.management import call_command from django.core.management import call_command
from django.conf import settings
class Command(BaseCommand): class Command(BaseCommand):
...@@ -37,7 +36,7 @@ class Command(BaseCommand): ...@@ -37,7 +36,7 @@ class Command(BaseCommand):
def handle(self, *args, **options): def handle(self, *args, **options):
root_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) root_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
try: try:
os.mkdir(os.path.join(root_path)+'/data') os.mkdir(os.path.join(root_path) + '/data')
print("Data dir created") print("Data dir created")
except Exception as e: except Exception as e:
repr(e) repr(e)
......
...@@ -24,7 +24,7 @@ ...@@ -24,7 +24,7 @@
import re import re
from mistune import Renderer, InlineGrammar, InlineLexer, Markdown, escape, escape_link from mistune import Renderer, InlineGrammar, InlineLexer, Markdown, escape, escape_link
from django.core.urlresolvers import reverse_lazy, reverse from django.core.urlresolvers import reverse
class SithRenderer(Renderer): class SithRenderer(Renderer):
...@@ -54,13 +54,16 @@ class SithRenderer(Renderer): ...@@ -54,13 +54,16 @@ class SithRenderer(Renderer):
src = original_src src = original_src
else: else:
width = m.group(1) width = m.group(1)
if not width.endswith('%'): width += "px" if not width.endswith('%'):
width += "px"
style = "width: %s; " % width style = "width: %s; " % width
try: try:
height = m.group(3) height = m.group(3)
if not height.endswith('%'): height += "px" if not height.endswith('%'):
height += "px"
style += "height: %s; " % height style += "height: %s; " % height
except: pass except:
pass
else: else:
params = None params = None
src = original_src src = original_src
...@@ -77,6 +80,7 @@ class SithRenderer(Renderer): ...@@ -77,6 +80,7 @@ class SithRenderer(Renderer):
return '%s />' % html return '%s />' % html
return '%s>' % html return '%s>' % html
class SithInlineGrammar(InlineGrammar): class SithInlineGrammar(InlineGrammar):
double_emphasis = re.compile( double_emphasis = re.compile(
r'^\*{2}([\s\S]+?)\*{2}(?!\*)' # **word** r'^\*{2}([\s\S]+?)\*{2}(?!\*)' # **word**
...@@ -94,6 +98,7 @@ class SithInlineGrammar(InlineGrammar): ...@@ -94,6 +98,7 @@ class SithInlineGrammar(InlineGrammar):
r'^<sub>([\s\S]+?)</sub>' # <sub>text</sub> r'^<sub>([\s\S]+?)</sub>' # <sub>text</sub>
) )
class SithInlineLexer(InlineLexer): class SithInlineLexer(InlineLexer):
grammar_class = SithInlineGrammar grammar_class = SithInlineGrammar
...@@ -159,15 +164,16 @@ class SithInlineLexer(InlineLexer): ...@@ -159,15 +164,16 @@ class SithInlineLexer(InlineLexer):
return self.renderer.emphasis(text) return self.renderer.emphasis(text)
def _process_link(self, m, link, title=None): def _process_link(self, m, link, title=None):
try: # Add page:// support for links try: # Add page:// support for links
page = re.compile( page = re.compile(
r'^page://(\S*)' # page://nom_de_ma_page r'^page://(\S*)' # page://nom_de_ma_page
) )
match = page.search(link) match = page.search(link)
page = match.group(1) or "" page = match.group(1) or ""
link = reverse('core:page', kwargs={'page_name': page}) link = reverse('core:page', kwargs={'page_name': page})
except: pass except:
try: # Add file:// support for links pass
try: # Add file:// support for links
file_link = re.compile( file_link = re.compile(
r'^file://(\d*)/?(\S*)?' # file://4000/download r'^file://(\d*)/?(\S*)?' # file://4000/download
) )
...@@ -175,9 +181,11 @@ class SithInlineLexer(InlineLexer): ...@@ -175,9 +181,11 @@ class SithInlineLexer(InlineLexer):
id = match.group(1) id = match.group(1)
suffix = match.group(2) or "" suffix = match.group(2) or ""
link = reverse('core:file_detail', kwargs={'file_id': id}) + suffix link = reverse('core:file_detail', kwargs={'file_id': id}) + suffix
except: pass except:
pass
return super(SithInlineLexer, self)._process_link(m, link, title) return super(SithInlineLexer, self)._process_link(m, link, title)
renderer = SithRenderer(escape=True) renderer = SithRenderer(escape=True)
inline = SithInlineLexer(renderer) inline = SithInlineLexer(renderer)
...@@ -222,4 +230,3 @@ Petit *test* _sur_ ^une^ **seule** ^ligne pour voir^ ...@@ -222,4 +230,3 @@ Petit *test* _sur_ ^une^ **seule** ^ligne pour voir^
""" """
print(markdown(text)) print(markdown(text))
...@@ -52,4 +52,3 @@ class AuthenticationMiddleware(DjangoAuthenticationMiddleware): ...@@ -52,4 +52,3 @@ class AuthenticationMiddleware(DjangoAuthenticationMiddleware):
"'account.middleware.AuthenticationMiddleware'." "'account.middleware.AuthenticationMiddleware'."
) )
request.user = SimpleLazyObject(lambda: get_cached_user(request)) request.user = SimpleLazyObject(lambda: get_cached_user(request))
...@@ -44,14 +44,17 @@ from datetime import datetime, timedelta, date ...@@ -44,14 +44,17 @@ from datetime import datetime, timedelta, date
import unicodedata import unicodedata
class RealGroupManager(AuthGroupManager): class RealGroupManager(AuthGroupManager):
def get_queryset(self): def get_queryset(self):
return super(RealGroupManager, self).get_queryset().filter(is_meta=False) return super(RealGroupManager, self).get_queryset().filter(is_meta=False)
class MetaGroupManager(AuthGroupManager): class MetaGroupManager(AuthGroupManager):
def get_queryset(self): def get_queryset(self):
return super(MetaGroupManager, self).get_queryset().filter(is_meta=True) return super(MetaGroupManager, self).get_queryset().filter(is_meta=True)
class Group(AuthGroup): class Group(AuthGroup):
is_meta = models.BooleanField( is_meta = models.BooleanField(
_('meta group status'), _('meta group status'),
...@@ -69,8 +72,10 @@ class Group(AuthGroup): ...@@ -69,8 +72,10 @@ class Group(AuthGroup):
""" """
return reverse('core:group_list') return reverse('core:group_list')
class MetaGroup(Group): class MetaGroup(Group):
objects = MetaGroupManager() objects = MetaGroupManager()
class Meta: class Meta:
proxy = True proxy = True
...@@ -78,20 +83,24 @@ class MetaGroup(Group): ...@@ -78,20 +83,24 @@ class MetaGroup(Group):
super(MetaGroup, self).__init__(*args, **kwargs) super(MetaGroup, self).__init__(*args, **kwargs)
self.is_meta = True self.is_meta = True
class RealGroup(Group): class RealGroup(Group):
objects = RealGroupManager() objects = RealGroupManager()
class Meta: class Meta:
proxy = True proxy = True
def validate_promo(value): def validate_promo(value):
start_year = settings.SITH_SCHOOL_START_YEAR start_year = settings.SITH_SCHOOL_START_YEAR
delta = (date.today()+timedelta(days=180)).year - start_year delta = (date.today() + timedelta(days=180)).year - start_year
if value < 0 or delta < value: if value < 0 or delta < value:
raise ValidationError( raise ValidationError(
_('%(value)s is not a valid promo (between 0 and %(end)s)'), _('%(value)s is not a valid promo (between 0 and %(end)s)'),
params={'value': value, 'end': delta}, params={'value': value, 'end': delta},
) )
class User(AbstractBaseUser): class User(AbstractBaseUser):
""" """
Defines the base user class, useable in every app Defines the base user class, useable in every app
...@@ -148,13 +157,13 @@ class User(AbstractBaseUser): ...@@ -148,13 +157,13 @@ class User(AbstractBaseUser):
) )
groups = models.ManyToManyField(RealGroup, related_name='users', blank=True) groups = models.ManyToManyField(RealGroup, related_name='users', blank=True)
home = models.OneToOneField('SithFile', related_name='home_of', verbose_name=_("home"), null=True, blank=True, home = models.OneToOneField('SithFile', related_name='home_of', verbose_name=_("home"), null=True, blank=True,
on_delete=models.SET_NULL) on_delete=models.SET_NULL)
profile_pict = models.OneToOneField('SithFile', related_name='profile_of', verbose_name=_("profile"), null=True, profile_pict = models.OneToOneField('SithFile', related_name='profile_of', verbose_name=_("profile"), null=True,
blank=True, on_delete=models.SET_NULL) blank=True, on_delete=models.SET_NULL)
avatar_pict = models.OneToOneField('SithFile', related_name='avatar_of', verbose_name=_("avatar"), null=True, avatar_pict = models.OneToOneField('SithFile', related_name='avatar_of', verbose_name=_("avatar"), null=True,
blank=True, on_delete=models.SET_NULL) blank=True, on_delete=models.SET_NULL)
scrub_pict = models.OneToOneField('SithFile', related_name='scrub_of', verbose_name=_("scrub"), null=True, scrub_pict = models.OneToOneField('SithFile', related_name='scrub_of', verbose_name=_("scrub"), null=True,
blank=True, on_delete=models.SET_NULL) blank=True, on_delete=models.SET_NULL)
sex = models.CharField(_("sex"), max_length=10, choices=[("MAN", _("Man")), ("WOMAN", _("Woman"))], default="MAN") sex = models.CharField(_("sex"), max_length=10, choices=[("MAN", _("Man")), ("WOMAN", _("Woman"))], default="MAN")
tshirt_size = models.CharField(_("tshirt size"), max_length=5, choices=[ tshirt_size = models.CharField(_("tshirt size"), max_length=5, choices=[
("-", _("-")), ("-", _("-")),
...@@ -165,7 +174,7 @@ class User(AbstractBaseUser): ...@@ -165,7 +174,7 @@ class User(AbstractBaseUser):
("XL", _("XL")), ("XL", _("XL")),
("XXL", _("XXL")), ("XXL", _("XXL")),
("XXXL", _("XXXL")), ("XXXL", _("XXXL")),
], default="-") ], default="-")
role = models.CharField(_("role"), max_length=15, choices=[ role = models.CharField(_("role"), max_length=15, choices=[
("STUDENT", _("Student")), ("STUDENT", _("Student")),
("ADMINISTRATIVE", _("Administrative agent")), ("ADMINISTRATIVE", _("Administrative agent")),
...@@ -174,9 +183,9 @@ class User(AbstractBaseUser): ...@@ -174,9 +183,9 @@ class User(AbstractBaseUser):
("DOCTOR", _("Doctor")), ("DOCTOR", _("Doctor")),
("FORMER STUDENT", _("Former student")), ("FORMER STUDENT", _("Former student")),
("SERVICE", _("Service")), ("SERVICE", _("Service")),
], blank=True, default="") ], blank=True, default="")
department = models.CharField(_("department"), max_length=15, choices=settings.SITH_PROFILE_DEPARTMENTS, department = models.CharField(_("department"), max_length=15, choices=settings.SITH_PROFILE_DEPARTMENTS,
default="NA", blank=True) default="NA", blank=True)
dpt_option = models.CharField(_("dpt option"), max_length=32, blank=True, default="") dpt_option = models.CharField(_("dpt option"), max_length=32, blank=True, default="")
semester = models.CharField(_("semester"), max_length=5, blank=True, default="") semester = models.CharField(_("semester"), max_length=5, blank=True, default="")
quote = models.CharField(_("quote"), max_length=256, blank=True, default="") quote = models.CharField(_("quote"), max_length=256, blank=True, default="")
...@@ -226,11 +235,12 @@ class User(AbstractBaseUser): ...@@ -226,11 +235,12 @@ class User(AbstractBaseUser):
_club_memberships = {} _club_memberships = {}
_group_names = {} _group_names = {}
_group_ids = {} _group_ids = {}
def is_in_group(self, group_name): def is_in_group(self, group_name):
"""If the user is in the group passed in argument (as string or by id)""" """If the user is in the group passed in argument (as string or by id)"""
group_id = 0 group_id = 0
g = None g = None
if isinstance(group_name, int): # Handle the case where group_name is an ID if isinstance(group_name, int): # Handle the case where group_name is an ID
if group_name in User._group_ids.keys(): if group_name in User._group_ids.keys():
g = User._group_ids[group_name] g = User._group_ids[group_name]
else: else:
...@@ -253,7 +263,7 @@ class User(AbstractBaseUser): ...@@ -253,7 +263,7 @@ class User(AbstractBaseUser):
return self.is_subscribed return self.is_subscribed
if group_id == settings.SITH_GROUP_OLD_SUBSCRIBERS_ID: if group_id == settings.SITH_GROUP_OLD_SUBSCRIBERS_ID:
return self.was_subscribed return self.was_subscribed
if group_name == settings.SITH_MAIN_MEMBERS_GROUP: # We check the subscription if asked if group_name == settings.SITH_MAIN_MEMBERS_GROUP: # We check the subscription if asked
return self.is_subscribed return self.is_subscribed
if group_name[-len(settings.SITH_BOARD_SUFFIX):] == settings.SITH_BOARD_SUFFIX: if group_name[-len(settings.SITH_BOARD_SUFFIX):] == settings.SITH_BOARD_SUFFIX:
name = group_name[:-len(settings.SITH_BOARD_SUFFIX)] name = group_name[:-len(settings.SITH_BOARD_SUFFIX)]
...@@ -315,7 +325,7 @@ class User(AbstractBaseUser): ...@@ -315,7 +325,7 @@ class User(AbstractBaseUser):
else: else:
create = True create = True
super(User, self).save(*args, **kwargs) super(User, self).save(*args, **kwargs)
if create and settings.IS_OLD_MYSQL_PRESENT: # Create user on the old site: TODO remove me! if create and settings.IS_OLD_MYSQL_PRESENT: # Create user on the old site: TODO remove me!
import MySQLdb import MySQLdb
try: try:
db = MySQLdb.connect(**settings.OLD_MYSQL_INFOS) db = MySQLdb.connect(**settings.OLD_MYSQL_INFOS)
...@@ -324,9 +334,9 @@ class User(AbstractBaseUser): ...@@ -324,9 +334,9 @@ class User(AbstractBaseUser):
(%s, %s, %s, %s, %s, %s)""", (self.id, self.last_name, self.first_name, self.email, "valid", "0")) (%s, %s, %s, %s, %s, %s)""", (self.id, self.last_name, self.first_name, self.email, "valid", "0"))
db.commit() db.commit()
except Exception as e: except Exception as e:
with open(settings.BASE_DIR+"/user_fail.log", "a") as f: with open(settings.BASE_DIR + "/user_fail.log", "a") as f:
print("FAIL to add user %s (%s %s - %s) to old site" % (self.id, self.first_name, self.last_name, print("FAIL to add user %s (%s %s - %s) to old site" % (self.id, self.first_name, self.last_name,
self.email), file=f) self.email), file=f)
print("Reason: %s" % (repr(e)), file=f) print("Reason: %s" % (repr(e)), file=f)
db.rollback() db.rollback()
...@@ -401,13 +411,13 @@ class User(AbstractBaseUser): ...@@ -401,13 +411,13 @@ class User(AbstractBaseUser):
Returns the generated username Returns the generated username
""" """
def remove_accents(data): def remove_accents(data):
return ''.join(x for x in unicodedata.normalize('NFKD', data) if \ return ''.join(x for x in unicodedata.normalize('NFKD', data) if
unicodedata.category(x)[0] == 'L').lower() unicodedata.category(x)[0] == 'L').lower()
user_name = remove_accents(self.first_name[0]+self.last_name).encode('ascii', 'ignore').decode('utf-8') user_name = remove_accents(self.first_name[0] + self.last_name).encode('ascii', 'ignore').decode('utf-8')
un_set = [u.username for u in User.objects.all()] un_set = [u.username for u in User.objects.all()]
if user_name in un_set: if user_name in un_set:
i = 1 i = 1
while user_name+str(i) in un_set: while user_name + str(i) in un_set:
i += 1 i += 1
user_name += str(i) user_name += str(i)
self.username = user_name self.username = user_name
...@@ -473,7 +483,7 @@ class User(AbstractBaseUser): ...@@ -473,7 +483,7 @@ class User(AbstractBaseUser):
self.profile_pict.get_download_url() if self.profile_pict else staticfiles_storage.url("core/img/unknown.jpg"), self.profile_pict.get_download_url() if self.profile_pict else staticfiles_storage.url("core/img/unknown.jpg"),
_("Profile"), _("Profile"),
escape(self.get_display_name()), escape(self.get_display_name()),
) )
@cached_property @cached_property
def subscribed(self): def subscribed(self):
...@@ -489,6 +499,7 @@ class User(AbstractBaseUser): ...@@ -489,6 +499,7 @@ class User(AbstractBaseUser):
infos.save() infos.save()
return infos return infos
class AnonymousUser(AuthAnonymousUser): class AnonymousUser(AuthAnonymousUser):
def __init__(self, request): def __init__(self, request):
super(AnonymousUser, self).__init__() super(AnonymousUser, self).__init__()
...@@ -530,7 +541,7 @@ class AnonymousUser(AuthAnonymousUser): ...@@ -530,7 +541,7 @@ class AnonymousUser(AuthAnonymousUser):
The anonymous user is only the public group The anonymous user is only the public group
""" """
group_id = 0 group_id = 0
if isinstance(group_name, int): # Handle the case where group_name is an ID if isinstance(group_name, int): # Handle the case where group_name is an ID
g = Group.objects.filter(id=group_name).first() g = Group.objects.filter(id=group_name).first()
if g: if g: