def callback(request):
    req_id = request.POST.get("id")
    key = request.POST.get("key")
    state = int(request.POST.get("state"))

    if key != get_config("CALLBACKKEY", ""):
        return HttpResponse("Nay....")

    conn = r.connect("localhost", 28015, "wlps")

    item = r.table("episode").get(req_id).run(conn)

    r.table("episode").get(item["id"]).update({"state": state}).run(conn)

    if state == 4:

        notif_json = {
            "torrent_url": get_config("GS_URL", "") % (get_config("BUCKET", ""), item["title_slug"] + ".mp4?torrent")
        }

        episodes = r.table("notifications").filter({"episode_id": req_id}).update(notif_json).run(conn)

        for a in episodes:
            print a

    return HttpResponse("Yay!")
Exemple #2
0
def register(request):
    if request.user.is_authenticated():
        return redirect(reverse('home'))

    _request = None
    if request.method == 'POST':
        _request = request.POST.copy()
    else:
        _request = request.GET.copy()
    next_uri = _request.get(
        'next', get_config('FIRST_LOGIN_REDIRECT_URL', reverse('first_steps')))
    # rescuing poor users from infinite redirection loop
    if next_uri == get_config('LOGIN_URL', reverse('login')):
        next_uri = get_config('FIRST_LOGIN_REDIRECT_URL',
                              reverse('first_steps'))

    register_form = RegisterForm()

    if request.method == 'POST':
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            register_form.save()
            username = register_form.cleaned_data['username']
            password = register_form.cleaned_data['password1']
            user = authenticate(username=username, password=password)
            if user is not None:
                auth_login(request, user)
                messages.success(request, "Welcome aboard, {0}.".format(user))
                badges.possibly_award_badge("logged_in", user=user)
            return redirect(next_uri)

    return {
        'register_form': register_form,
        'next': next_uri,
    }
Exemple #3
0
def register(request):
    if request.user.is_authenticated:
        return redirect(reverse("home"))

    _request = None
    if request.method == "POST":
        _request = request.POST.copy()
    else:
        _request = request.GET.copy()
    next_uri = _request.get(
        "next", get_config("FIRST_LOGIN_REDIRECT_URL", reverse("first_steps"))
    )
    # rescuing poor users from infinite redirection loop
    if next_uri == get_config("LOGIN_URL", reverse("login")):
        next_uri = get_config("FIRST_LOGIN_REDIRECT_URL", reverse("first_steps"))

    register_form = RegisterForm()

    if request.method == "POST":
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            register_form.save()
            username = register_form.cleaned_data["username"]
            password = register_form.cleaned_data["password1"]
            user = authenticate(username=username, password=password)
            if user is not None:
                auth_login(request, user)
                messages.success(request, "Welcome aboard, {0}.".format(user))
                badges.possibly_award_badge("logged_in", user=user)
            return redirect(next_uri)

    return {"register_form": register_form, "next": next_uri}
Exemple #4
0
def register(request):
	if request.user.is_authenticated():
		return redirect(reverse('home'))

	next_uri = request.REQUEST.get('next',
		get_config('FIRST_LOGIN_REDIRECT_URL', reverse('first_steps')))
	# rescuing poor users from infinite redirection loop
	if next_uri == get_config('LOGIN_URL', reverse('login')):
		next_uri = get_config('FIRST_LOGIN_REDIRECT_URL',
			reverse('first_steps'))

	register_form = RegisterForm()

	if request.method == 'POST':
		register_form = RegisterForm(request.POST)
		if register_form.is_valid():
			register_form.save()
			username = register_form.cleaned_data['username']
			password = register_form.cleaned_data['password1']
			user = authenticate(username=username, password=password)
			if user is not None:
				auth_login(request, user)
				messages.success(request, "Welcome aboard, {0}.".format(user))
				badges.possibly_award_badge("logged_in",
					user=user)
			return redirect(next_uri)

	return {
		'register_form': register_form,
		'next': next_uri,
	}
Exemple #5
0
def login(request):
	if request.user.is_authenticated():
		return redirect(reverse('home'))

	_request = None
	if request.method == 'POST':
		_request = request.POST.copy()
	else:
		_request = request.GET.copy()

	next_uri = _request.get('next', get_config('LOGIN_REDIRECT_URL',
		reverse('home')))
	# rescuing poor users from infinite redirection loop
	if next_uri == get_config('LOGIN_URL', reverse('login')):
		next_uri = get_config('LOGIN_REDIRECT_URL', reverse('home'))

	login_form = LoginForm()

	if request.method == 'POST':
		login_form = LoginForm(request.POST)
		if login_form.is_valid() and login_form.user:
			auth_login(request, login_form.user)
			messages.success(request, "Hello, {0}.".format(login_form.user))
			badges.possibly_award_badge("logged_in",
				user=login_form.user)
			return redirect(next_uri)

	return {
		'login_form': login_form,
		'next': next_uri,
	}
Exemple #6
0
def register(request):
    if request.user.is_authenticated:
        return redirect(reverse("home"))

    _request = None
    if request.method == "POST":
        _request = request.POST.copy()
    else:
        _request = request.GET.copy()
    next_uri = _request.get(
        "next", get_config("FIRST_LOGIN_REDIRECT_URL", reverse("first_steps"))
    )
    # rescuing poor users from infinite redirection loop
    if not next_uri or next_uri == get_config("LOGIN_URL", reverse("login")):
        next_uri = get_config("FIRST_LOGIN_REDIRECT_URL", reverse("first_steps"))

    register_form = RegisterForm()

    if request.method == "POST":
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            register_form.save()
            username = register_form.cleaned_data["username"]
            password = register_form.cleaned_data["password1"]
            user = authenticate(username=username, password=password)
            if user is not None:
                auth_login(request, user)
                messages.success(request, "Welcome aboard, {0}.".format(user))
                badges.possibly_award_badge("logged_in", user=user)
            return redirect(next_uri)

    return {"register_form": register_form, "next": next_uri}
Exemple #7
0
def ejudge_kwargs(lang, timeout):
    """
    Common kwargs for run_code and grade_code functions.
    """

    timeout = timeout or get_config('CODESCHOOL_EXECUTION_TIMEOUT', 10)
    if timeout is None or timeout <= 0:
        raise ValueError('invalid timeout: %r' % timeout)

    is_testing = get_config('IS_RUNNING_TESTS', False)
    sandbox = get_config('CODESCHOOL_SANDBOX', True) and not is_testing
    if sandbox:
        logger.debug('running %s code in sandbox' % lang)
    else:
        logger.warning('running %s code outside sandbox!' % lang)

    if isinstance(lang, ProgrammingLanguage):
        lang = lang.ejudge_ref()

    return dict(
        raises=False,
        sandbox=sandbox,
        timeout=timeout,
        lang=lang
    )
Exemple #8
0
def login(request):
    if request.user.is_authenticated():
        return redirect(reverse('home'))

    _request = None
    if request.method == 'POST':
        _request = request.POST.copy()
    else:
        _request = request.GET.copy()

    next_uri = _request.get('next',
                            get_config('LOGIN_REDIRECT_URL', reverse('home')))
    # rescuing poor users from infinite redirection loop
    if next_uri == get_config('LOGIN_URL', reverse('login')):
        next_uri = get_config('LOGIN_REDIRECT_URL', reverse('home'))

    login_form = LoginForm()

    if request.method == 'POST':
        login_form = LoginForm(request.POST)
        if login_form.is_valid() and login_form.user:
            auth_login(request, login_form.user)
            messages.success(request, "Hello, {0}.".format(login_form.user))
            badges.possibly_award_badge("logged_in", user=login_form.user)
            return redirect(next_uri)

    return {
        'login_form': login_form,
        'next': next_uri,
    }
def forum_period(request):
    today = datetime.today()
    
    return {
        'REG_START' : get_config('REG_START', today),
        'REG_END': get_config('REG_END', today),
        'NOW': today,
    }
Exemple #10
0
class RegisterForm(forms.Form):
    username = forms.RegexField(label="Username",
                                regex=r'^\w+$',
                                min_length=2,
                                max_length=30)
    password1 = forms.CharField(label="Password",
                                min_length=4,
                                widget=forms.PasswordInput(render_value=False),
                                help_text="At least 4 chars long")
    password2 = forms.CharField(label="Password (again)",
                                min_length=4,
                                widget=forms.PasswordInput(render_value=False))
    email1 = forms.EmailField(
        label="E-mail address",
        help_text="We won't share this to any 3rd-parties!")
    email2 = forms.EmailField(label="E-mail address (again)")

    if get_config('ENABLE_CAPTCHA', False):
        if not (get_config('RECAPTCHA_PUBLIC_KEY', False)
                and get_config('RECAPTCHA_PRIVATE_KEY', False)):
            raise ImproperlyConfigured(
                "You must define the RECAPTCHA_PUBLIC_KEY"
                " and/or RECAPTCHA_PRIVATE_KEY setting in order to use reCAPTCHA."
            )
        recaptcha = RecaptchaField(label="Human test", required=True)

    def clean_username(self):
        username = self.cleaned_data.get('username')
        try:
            user = User.objects.get(username__iexact=username)
            del user
            raise forms.ValidationError("Username is already taken")
        except User.DoesNotExist:
            pass
        return username

    def clean_password2(self):
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')
        if password1 != password2:
            raise forms.ValidationError(
                "You must type the same password each time")
        return password2

    def clean_email2(self):
        email1 = self.cleaned_data.get('email1')
        email2 = self.cleaned_data.get('email2')
        if email1 != email2:
            raise forms.ValidationError(
                "You must type the same e-mail address each time")
        return email2

    def save(self):
        return User.objects.create_user(self.cleaned_data.get('username'),
                                        self.cleaned_data.get('email1'),
                                        self.cleaned_data.get('password1'))
Exemple #11
0
 def __init__(self,
              image_tick,
              image_no_tick,
              attrs=None,
              prefix='',
              *a,
              **kw):
     super(ImageSwitch, self).__init__(attrs, *a, **kw)
     self.image_tick = get_config("STATIC_URL", "") + image_tick
     self.image_no_tick = get_config("STATIC_URL", "") + image_no_tick
     self.prefix = prefix + '_' if prefix else ''
    def __init__(self):

        conn = r.connect('localhost', 28015, 'wlps')
        items = r.table('queue').run(conn)

        for queued in items:

            run = True

            url = queued['url']
            episode_exists = r.table('episode').filter(lambda item: item.contains('url')).filter({'url': url}).count().run(conn)

            if int(episode_exists) == 0:
                allt = getjson(url)

                for obj in allt['objects']:
                    r.db('wlps').table('episode').insert(obj).run(conn)

            episode_exists = r.table('episode').filter(lambda item: item.contains('url')).filter({'url': url}).count().run(conn)
            if int(episode_exists) != 0:

                episode = r.table('episode').filter(lambda item: item.contains('url')).filter({'url': url}).nth(0).run(conn)
                r.table('episode').get(episode['id']).update({'state': 2}).run(conn)

                notif_json = {
                    'episode_id': episode['id'],
                    'user_id': int(queued['user_id'])
                }
                exists = int(r.table('notifications').filter(notif_json).count().run(conn))

                if int(exists) == 0:
                    notif_json.update(
                        {
                            'date_added': int(time.time())
                        })

                if hasattr(episode, 'state'):
                    if episode['state'] == 4:
                        notif_json.update(
                            {
                                'torrent_url': get_config('GS_URL', '') % (get_config('BUCKET', ''), episode['title_slug'] + '.mp4?torrent'),
                            }
                        )
                        run = False

                r.table('notifications').insert(notif_json).run(conn)
                r.table('queue').get(queued['id']).delete().run(conn)

                if run:
                    result = q.enqueue(download, episode['id'], episode['title_slug'], episode['url'], get_config('SVTGETSAVEFOLDER', os.path.join(get_config('PROJECT_DIR', 'FAILED'), 'episodes')), callback_url)
def worker_deploy():

    env.user = '******'

    with virtualenv(django_settings.RQ_DEPLOY_PATH):

        for item in django_settings.RQ_PIP:
            run('pip install %s' % item)

        run('mkdir -p '+ django_settings.SVTGETSAVEFOLDER)

        for item in django_settings.RQ_SETTINGS_NEEDED:
            files.append('rq_settings.py', '%s=\'%s\'' % (item, get_config(item, 'FAIL!')))

        for item in django_settings.RQ_IMPORTS:

            if os.path.isdir(os.path.join(django_settings.ROOT_DIR, item[0])):
                #If the source is a directory, create same directory on the target
                run('mkdir -p '+ item[1])
            if item[1].find('/') != -1:
                #If the target filename contains a directory name, create that, and create a __init__.py
                run('mkdir -p '+ '/'.join(item[1].split('/')[:-1]))
                run('touch '+ '/'.join(item[1].split('/')[:-1]) + '/__init__.py')

            put(item[0], item[1])
Exemple #14
0
def register(request):
	if request.user.is_authenticated():
		return redirect(reverse('home'))

	next_uri = request.REQUEST.get('next', reverse('home'))
	# rescuing poor users from infinite redirection loop
	if next_uri == get_config('LOGIN_URL', reverse('login')):
		next_uri = reverse('home')

	form = RegisterForm()

	if request.method == 'POST':
		form = RegisterForm(request.POST)
		if form.is_valid():
			form.save()
			username = form.cleaned_data['username']
			password = form.cleaned_data['password1']
			user = authenticate(username=username, password=password)
			if user is not None:
				auth_login(request, user)
				messages.success(request, "Welcome aboard, {0}.".format(user))
			return redirect(next_uri)

	return TemplateResponse(request, 'accounts/register.html', {
		'form': form,
		'next': next_uri,
	})
Exemple #15
0
class RegisterForm(forms.Form):
    username = forms.RegexField(label="Username",
                                regex=r"^\w+$",
                                min_length=2,
                                max_length=30)
    password1 = forms.CharField(
        label="Password",
        min_length=4,
        widget=forms.PasswordInput(render_value=False),
        help_text="At least 4 chars long",
    )
    password2 = forms.CharField(
        label="Password (again)",
        min_length=4,
        widget=forms.PasswordInput(render_value=False),
    )
    email1 = forms.EmailField(
        label="E-mail address",
        help_text="We won't share this to any 3rd-parties!")
    email2 = forms.EmailField(label="E-mail address (again)")

    if get_config("ENABLE_CAPTCHA", False):
        recaptcha = ReCaptchaField(label="Human test", required=True)

    def clean_username(self):
        username = self.cleaned_data.get("username")
        try:
            user = User.objects.get(username__iexact=username)
            del user
            raise forms.ValidationError("Username is already taken")
        except User.DoesNotExist:
            pass
        return username

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 != password2:
            raise forms.ValidationError(
                "You must type the same password each time")
        return password2

    def clean_email2(self):
        email1 = self.cleaned_data.get("email1")
        email2 = self.cleaned_data.get("email2")
        if email1 != email2:
            raise forms.ValidationError(
                "You must type the same e-mail address each time")
        return email2

    def save(self):
        return User.objects.create_user(
            self.cleaned_data.get("username"),
            self.cleaned_data.get("email1"),
            self.cleaned_data.get("password1"),
        )
Exemple #16
0
def create_profile_on_user_save(instance, created, **kwargs):
    """
    Create matching profile when users are created.
    """

    user = instance
    if created and user.username != 'AnonymousUser':
        profile, _ = Profile.objects.get_or_create(user=user)
        if get_config('CODESCHOOL_USERNAME_IS_SCHOOL_ID', False):
            profile.school_id = user.username
        profile.save()
Exemple #17
0
def create_profile_on_user_save(instance, created, **kwargs):
    """
    Create matching profile when users are created.
    """

    user = instance
    if created and user.username != 'AnonymousUser':
        profile, _ = Profile.objects.get_or_create(user=user)
        if get_config('CODESCHOOL_USERNAME_IS_SCHOOL_ID', False):
            profile.school_id = user.username
        profile.save()
Exemple #18
0
def grade_code(source, answer_key, lang=None):
    """
    Compare results of running the given source code with the iospec answer
    key.
    """

    return ejudge.grade(source,
                        answer_key,
                        lang,
                        raises=False,
                        sandbox=get_config('CODESCHOOL_USE_SANDBOX', True))
Exemple #19
0
def run_code(source, inputs, lang=None):
    """
    Runs source code with given inputs and return the corresponding IoSpec
    tree.
    """

    return ejudge.run(source,
                      inputs,
                      lang,
                      raises=False,
                      sandbox=get_config('CODESCHOOL_USE_SANDBOX', True))
Exemple #20
0
def get_category_ids(language):
    agregates = get_config('NEWS_AGREGATE_CATEGORIES', {}).get(language, None)

    if not agregates:
        return list()

    category_ids = list()
    for key, value in agregates.items():
        category_ids += list(value)

    return category_ids
Exemple #21
0
def ejudge_kwargs(lang, timeout):
    """
    Common kwargs for run_code and grade_code functions.
    """

    timeout = timeout or get_config('CODESCHOOL_EXECUTION_TIMEOUT', 10)
    if timeout is None or timeout <= 0:
        raise ValueError('invalid timeout: %r' % timeout)

    is_testing = get_config('IS_RUNNING_TESTS', False)
    sandbox = get_config('CODESCHOOL_SANDBOX', True) and not is_testing
    if sandbox:
        logger.debug('running %s code in sandbox' % lang)
    else:
        logger.warning('running %s code outside sandbox!' % lang)

    if isinstance(lang, ProgrammingLanguage):
        lang = lang.ejudge_ref()

    return dict(raises=False, sandbox=sandbox, timeout=timeout, lang=lang)
Exemple #22
0
def post_permalink(request, post_id):
	post = get_object_or_404(Post, pk=post_id)
	if not request.user.has_perm('forums.view_category', post.topic.category):
		raise Http404
	older_posts = Post.objects.filter(topic__pk=post.topic_id,
		created_at__lt=post.created_at).count()
	page = int(math.ceil((float(older_posts) + 1.0) /
		get_config('POSTS_PER_PAGE', 25)))
	return redirect("{0}{1}#post-{2}".format(
		post.topic.get_absolute_url(),
		"?page={0}".format(page) if page > 1 else '', post.id)
	)
Exemple #23
0
class RSA(object):
	PADDING = M2C_RSA.pkcs1_oaep_padding
	LENGTH = 2048
	PUBLIC_EXPONENT = 3
	public_key = private_key = None
	rsa_public = rsa_private = None

	PROJECT_DIR = get_config('PROJECT_DIR', '')
	public_key_filename = PROJECT_DIR + '/public_key.pem'
	private_key_filename = PROJECT_DIR + '/private_key.pem'

	def __init__(self, public_key=None, private_key=None, no_import=False):
		if public_key:
			self.public_key = public_key
		if private_key:
			self.private_key = private_key
		if not no_import:
			self._import_keys()

	def _import_keys(self):
		public_bio = BIO.MemoryBuffer(self.public_key) if self.public_key \
			else None
		self.rsa_public = M2C_RSA.load_pub_key_bio(public_bio) \
			if public_bio else M2C_RSA.load_pub_key(self.public_key_filename)

		private_bio = BIO.MemoryBuffer(self.private_key) if self.private_key \
			else None
		self.rsa_private = M2C_RSA.load_key_bio(private_bio) \
			if private_bio else M2C_RSA.load_key(self.private_key_filename,
				callback=self.dpc)

	def generate_keys(self):
		keys = M2C_RSA.gen_key(self.LENGTH, self.PUBLIC_EXPONENT)
		keys.save_key(self.private_key_filename, callback=self.dpc)
		keys.save_pub_key(self.public_key_filename)

	def decrypt(self, string):
		if not self.rsa_private:
			raise AttributeError("private_key.pem file missing.")
		return self.rsa_private.private_decrypt(string, self.PADDING)

	def encrypt(self, string):
		if not self.rsa_public:
			raise AttributeError("public_key.pem file missing.")
		return self.rsa_public.public_encrypt(string, self.PADDING)

	@staticmethod
	def dpc(*args):
		""" dummy passphrase callback """
		return 'teerace'
Exemple #24
0
def login(request):
	if request.user.is_authenticated():
		return redirect(reverse('home'))

	next_uri = request.REQUEST.get('next', get_config('LOGIN_REDIRECT_URL',
		reverse('home')))
	# rescuing poor users from infinite redirection loop
	if next_uri == get_config('LOGIN_URL', reverse('login')):
		next_uri = get_config('LOGIN_REDIRECT_URL', reverse('home'))

	form = LoginForm()

	if request.method == 'POST':
		form = LoginForm(request.POST)
		if form.is_valid() and form.user:
			auth_login(request, form.user)
			messages.success(request, "Hello, {0}.".format(form.user))
			return redirect(next_uri)

	return TemplateResponse(request, 'accounts/login.html', {
		'form': form,
		'next': next_uri,
	})
def send_mail(subject, template, context, to, from_email=settings.DEFAULT_FROM_EMAIL,
              template_variant=get_config('DEFAULT_TEMPLATE_TYPE', 'html'), attachment=None):
    """
    Render template and send it as a mail.

    Usage:
        > ctx = { 'some_var': True }
        > send_mail('E-mail subject', 'default_file_extensiontension/emails/bar', context=ctx, to=['*****@*****.**'])
    """
    template_path = os.path.normcase("{}.{}".format(template, template_variant))

    context_instance = Context(context)
    current_language = translation.get_language()

    try:
        # TODO Allow to activate different language
        translation.activate(current_language)
        html_message = render_to_string(template_path, context_instance)
    finally:
        translation.activate(current_language)

    premailer = Premailer(
        html_message,
        base_url=get_config('BASE_URL_FOR_EMAIL_LINK', None),
        base_path=settings.STATIC_ROOT
    )

    html_message = premailer.transform()

    mail = EmailMessage(settings.EMAIL_SUBJECT_PREFIX + subject, html_message, to=to, from_email=from_email)
    if template_variant == "html":
        mail.content_subtype = "html"

    if attachment:
        mail.attach_file(attachment)

    mail.send()
Exemple #26
0
    def get_context(self, request, *args, **kwargs):
        context = dict(super().get_context(request, *args, **kwargs),
                       form=True)

        # Select default mode for the ace editor
        if self.language:
            context['default_mode'] = self.language.ace_mode()
        else:
            context['default_mode'] = get_config('CODESCHOOL_DEFAULT_ACE_MODE',
                                                 'python')

        # Enable language selection
        if self.language is None:
            context['select_language'] = True
            context['languages'] = ProgrammingLanguage.supported.all()
        else:
            context['select_language'] = False

        return context
Exemple #27
0
    def get_context(self, request, *args, **kwargs):
        context = dict(super().get_context(request, *args, **kwargs),
                       form=True)

        # Select default mode for the ace editor
        if self.language:
            context['default_mode'] = self.language.ace_mode()
        else:
            context['default_mode'] = get_config('CODESCHOOL_DEFAULT_ACE_MODE',
                                                 'python')

        # Enable language selection
        if self.language is None:
            context['select_language'] = True
            context['languages'] = ProgrammingLanguage.supported.all()
        else:
            context['select_language'] = False

        return context
def parse_date(grej, typ):
    grej = unicode(grej)
    tz = timezone(get_config('TIME_ZONE', None))
    hoj = datetime.utcnow().replace(tzinfo=tz)
    if grej.find('dag') != -1:
        days = numerics(grej)
        if typ == '+':
            ret = hoj + timedelta(days=days)
        else:
            ret = hoj - timedelta(days=days)
    elif grej.find('tim') != -1:
        hours = numerics(grej)
        if typ == '+':
            ret = hoj + timedelta(hours=hours)
        else:
            ret = hoj - timedelta(hours=hours)
    else:
        return hoj

    return ret
Exemple #29
0
def get_solr_tagcloud(language='ru'):
    tag_info = {}
    try:
        solr = Solr(get_config('HAYSTACK_SOLR_URL', 'http://127.0.0.1:8983/solr'))

        kwargs = {
            'facet': 'on',
            'facet.field': 'tags',
            'rows': 0,
            'start': 1
        }
        result = solr.search(q = 'language:%s' % language, **kwargs)
        tags = result.facets['facet_fields']['tags']
        tags_len = len(tags)
        for i, item in enumerate(tags):
            if not i%2:
                if i < tags_len-1:
                    tag_info.update({ item: {'count': tags[i+1], 'font': None }})
    except:
        pass

    return tag_info
Exemple #30
0
 def dbfile(self):
     return get_config('DATABASES')['default']['NAME']
 def __init__(self, image_tick, image_no_tick, attrs=None, prefix='', *a, **kw):
     super(ImageSwitch, self).__init__(attrs, *a, **kw)
     self.image_tick = get_config("STATIC_URL", "") + image_tick
     self.image_no_tick = get_config("STATIC_URL", "") + image_no_tick
     self.prefix = prefix + '_' if prefix else ''
Exemple #32
0
class Run(models.Model):
    """Representation of one map finish"""

    map = models.ForeignKey('Map', on_delete=models.CASCADE)
    server = models.ForeignKey('Server',
                               blank=True,
                               null=True,
                               related_name='runs',
                               on_delete=models.SET_NULL)
    user = models.ForeignKey(User,
                             blank=True,
                             null=True,
                             on_delete=models.SET_NULL)
    nickname = models.CharField(max_length=15)
    clan = models.CharField(max_length=11, blank=True, null=True)

    # yep, 24 semicolons and 25 time decimals,
    # which length is MAX_DIGITS + decimal separator (.)
    # 24 + 25 * (12 + 1) = 349
    checkpoints = models.CharField(max_length=349, blank=True)

    DECIMAL_PLACES = get_config('RESULT_PRECISION', 3)
    MAX_DIGITS = DECIMAL_PLACES + 9

    time = models.DecimalField(max_digits=MAX_DIGITS,
                               decimal_places=DECIMAL_PLACES)
    created_at = models.DateTimeField(auto_now_add=True)

    def set_personal_record(self):
        try:
            current_best = BestRun.objects.get(map=self.map, user=self.user)
            if self.time < current_best.run.time:
                self.promote_to_best()
        except BestRun.DoesNotExist:
            self.promote_to_best()

    def promote_to_best(self):
        if self.user == None:
            return
        best_run, created = BestRun.objects.get_or_create(
            map=self.map, user=self.user, defaults={'run': self})
        if not created:
            best_run.run = self
            best_run.save()

    def checkpoints_list(self):
        return self.checkpoints.split(';')

    class Meta:
        get_latest_by = 'created_at'
        ordering = ['time', 'created_at']

    def __unicode__(self):
        return u"{0} - {1} - {2:.{precision}f}s".format(
            self.map, self.user, self.time, precision=self.DECIMAL_PLACES)

    def save(self, *args, **kwargs):
        # imitate overriding create()
        created = True if not self.pk else False
        super(Run, self).save(*args, **kwargs)
        if created:
            self.set_personal_record()

    def delete(self, *args, **kwargs):
        was_bestrun = bool(self.bestrun_set.count())
        map_id = self.map_id
        user_id = self.user_id
        super(Run, self).delete(*args, **kwargs)
        if not was_bestrun:
            return
        runs = Run.objects.filter(map=map_id, user=user_id)
        if runs.count():
            from race import tasks
            tasks.redo_ranks.delay(runs[0])
Exemple #33
0
from django.utils.translation import ugettext
from django.core.exceptions import ImproperlyConfigured
from annoying.functions import get_config

fdow_default = 0  # Sunday

# Look for FIRST_DAY_OF_WEEK as a locale setting
fdow = ugettext("FIRST_DAY_OF_WEEK")
try:
    FIRST_DAY_OF_WEEK = int(fdow)
except ValueError:
    # Let's try our settings
    fdow = get_config("FIRST_DAY_OF_WEEK", fdow_default)
    FIRST_DAY_OF_WEEK = int(fdow)
except ValueError:
    raise ImproperlyConfigured("FIRST_DAY_OF_WEEK must be an integer between 0 and 6")

AUTH_USER_MODEL = get_config("AUTH_USER_MODEL")
# whether to display cancelled occurrences
# (if they are displayed then they have a css class "cancelled")
# this controls behaviour of Period.classify_occurrence method
SHOW_CANCELLED_OCCURRENCES = get_config("SHOW_CANCELLED_OCCURRENCES", False)

# Callable used to check if a user has edit permissions to event
# (and occurrence). Used by check_edit_permission decorator
# if ob==None we check permission to add occurrence
CHECK_EVENT_PERM_FUNC = get_config("CHECK_EVENT_PERM_FUNC", None)

if not CHECK_EVENT_PERM_FUNC:
    CHECK_EVENT_PERM_FUNC = get_config("CHECK_PERMISSION_FUNC", None)
Exemple #34
0
	def award(self, **state):
		if get_config('BETA', False):
			return BadgeAwarded(level=1)
Exemple #35
0
from django.contrib.auth import authenticate, login, logout as do_logout
from django.contrib.auth.decorators import login_required
from django.db import transaction
from django.shortcuts import redirect, render
from django.utils.translation import ugettext as _
from rest_framework import viewsets
from . import bricks
from . import models
from . import serializers
from .forms import LoginForm, UserForm, ProfileForm
from rest_framework.decorators import detail_route, list_route
from rest_framework.response import Response
from rest_framework.permissions import IsAdminUser
from .permissions import UserPermissions

authentication_backend = get_config('AUTHENTICATION_BACKENDS')[-1]

#
# REST endpoints
#


class ProfileViewSet(viewsets.ModelViewSet):
    permission_classes = (UserPermissions, )
    method = 'put'
    queryset = models.Profile.objects.all()
    serializer_class = serializers.ProfileSerializer


class UserViewSet(viewsets.ModelViewSet):
    """
Exemple #36
0
try:
    from hashlib import md5
except ImportError:
    from md5 import md5
import urllib

from django.core.paginator import Paginator, EmptyPage, InvalidPage
from django.contrib.sites.models import Site
from annoying.functions import get_config

import defaults
MEDIA_URL = get_config('MEDIA_URL', None)

#def paginate(items, request, per_page, total_count=None):
#    try:
#        page_number = int(request.GET.get('page', 1))
#    except ValueError:
#        page_number = 1
#
#    paginator = Paginator(items, per_page)
#    if total_count:
#        paginator._count = total_count
#
#    try:
#        page = paginator.page(page_number)
#    except (EmptyPage, InvalidPage):
#        page = paginator.page(1)
#
#    # generate 1 ... 6 7 8 *9* 10 11 12 ... 16
#    #                ^    middle      ^
#    # maximum 4 items for left and right position,
Exemple #37
0
 def dbfile(self):
     return get_config('DATABASES')['default']['NAME']
from annoying.functions import get_config

AUTH_USER_MODEL = get_config('AUTH_USER_MODEL')
# whether to display cancelled occurrences
# (if they are displayed then they have a css class "cancelled")
# this controls behaviour of Period.classify_occurrence method
SHOW_CANCELLED_OCCURRENCES = get_config('SHOW_CANCELLED_OCCURRENCES', False)

# Callable used to check if a user has edit permissions to event.
# Used by check_edit_permission decorator
# if ob==None we check permission to add occurrence
CHECK_EVENT_PERM_FUNC = get_config('CHECK_EVENT_PERM_FUNC', None)

if not CHECK_EVENT_PERM_FUNC:
    CHECK_EVENT_PERM_FUNC = get_config('CHECK_PERMISSION_FUNC', None)

if not CHECK_EVENT_PERM_FUNC:
    def check_event_permission(ob, user):
        return user.is_authenticated()

    CHECK_EVENT_PERM_FUNC = check_event_permission

# Callable used to check if a user has edit permissions to occurrence
CHECK_OCCURRENCE_PERM_FUNC = get_config('CHECK_OCCURRENCE_PERM_FUNC', None)

if not CHECK_OCCURRENCE_PERM_FUNC:
    def check_occurrence_permission(ob, user):
        return CHECK_EVENT_PERM_FUNC(ob.event, user)
    CHECK_OCCURRENCE_PERM_FUNC = check_occurrence_permission

#Used to check whether the admin wants to use permissions
from six.moves.builtins import str
from django.core.exceptions import ImproperlyConfigured
from annoying.functions import get_config

AUTH_USER_MODEL = get_config('AUTH_USER_MODEL')
# whether to display cancelled occurrences
# (if they are displayed then they have a css class "cancelled")
# this controls behaviour of Period.classify_occurrence method
SHOW_CANCELLED_OCCURRENCES = get_config('SHOW_CANCELLED_OCCURRENCES', False)

# Callable used to check if a user has edit permissions to event
# (and occurrence). Used by check_edit_permission decorator
# if ob==None we check permission to add occurrence
CHECK_EVENT_PERM_FUNC = get_config('CHECK_EVENT_PERM_FUNC', None)

if not CHECK_EVENT_PERM_FUNC:
    CHECK_EVENT_PERM_FUNC = get_config('CHECK_PERMISSION_FUNC', None)

if not CHECK_EVENT_PERM_FUNC:
    def check_event_permission(ob, user):
        return user.is_authenticated()

    CHECK_EVENT_PERM_FUNC = check_event_permission

# Callable used to check if a user has edit permissions to calendar
CHECK_CALENDAR_PERM_FUNC = get_config('CHECK_CALENDAR_PERM_FUNC', None)

if not CHECK_CALENDAR_PERM_FUNC:
    def check_calendar_permission(ob, user):
        return user.is_authenticated()
Exemple #40
0
from annoying.functions import get_config

# whether to display cancelled occurrences
# (if they are displayed then they have a css class "cancelled")
# this controls behaviour of Period.classify_occurrence method
SHOW_CANCELLED_OCCURRENCES = get_config('SHOW_CANCELLED_OCCURRENCES', False)

# Callable used to check if a user has edit permissions to event
# (and occurrence). Used by check_edit_permission decorator
# if ob==None we check permission to add occurrence
CHECK_EVENT_PERM_FUNC = get_config('CHECK_EVENT_PERM_FUNC', None)

if not CHECK_EVENT_PERM_FUNC:
    def check_event_permission(ob, user):
        return user.is_authenticated()

    CHECK_EVENT_PERM_FUNC = check_event_permission

# Callable used to check if a user has edit permissions to occurrence
CHECK_OCCURRENCE_PERM_FUNC = get_config('CHECK_OCCURRENCE_PERM_FUNC', False)

if not CHECK_OCCURRENCE_PERM_FUNC:
    def check_occurrence_permission(ob, user):
        return CHECK_EVENT_PERM_FUNC(ob.event, user)
    CHECK_OCCURRENCE_PERM_FUNC = check_occurrence_permission

CALENDAR_VIEW_PERM = get_config('CALENDAR_VIEW_PERM', False)

# Callable used to check if a user has edit permissions to calendar
CHECK_CALENDAR_PERM_FUNC = get_config('CHECK_CALENDAR_PERM_FUNC', None)
from django.utils.translation import ugettext_lazy
from django.core.exceptions import ImproperlyConfigured
from annoying.functions import get_config

fdow_default = 0  # Sunday

# Look for FIRST_DAY_OF_WEEK as a locale setting
fdow = ugettext_lazy('FIRST_DAY_OF_WEEK')
try:
    FIRST_DAY_OF_WEEK = int(str(fdow))
except ValueError:
    # Let's try our settings
    fdow = get_config('FIRST_DAY_OF_WEEK', fdow_default)
    FIRST_DAY_OF_WEEK = int(fdow)
except ValueError:
    raise ImproperlyConfigured("FIRST_DAY_OF_WEEK must be an integer between 0 and 6")

AUTH_USER_MODEL = get_config('AUTH_USER_MODEL')
# whether to display cancelled occurrences
# (if they are displayed then they have a css class "cancelled")
# this controls behaviour of Period.classify_occurrence method
SHOW_CANCELLED_OCCURRENCES = get_config('SHOW_CANCELLED_OCCURRENCES', False)

# Callable used to check if a user has edit permissions to event
# (and occurrence). Used by check_edit_permission decorator
# if ob==None we check permission to add occurrence
CHECK_EVENT_PERM_FUNC = get_config('CHECK_EVENT_PERM_FUNC', None)

if not CHECK_EVENT_PERM_FUNC:
    CHECK_EVENT_PERM_FUNC = get_config('CHECK_PERMISSION_FUNC', None)
Exemple #42
0
try:
    from hashlib import md5
except ImportError:
    from md5 import md5
import urllib

from django.core.paginator import Paginator, EmptyPage, InvalidPage
from django.contrib.sites.models import Site
from annoying.functions import get_config

import defaults
MEDIA_URL = get_config('MEDIA_URL', None)

#def paginate(items, request, per_page, total_count=None):
#    try:
#        page_number = int(request.GET.get('page', 1))
#    except ValueError:
#        page_number = 1
#
#    paginator = Paginator(items, per_page)
#    if total_count:
#        paginator._count = total_count
#
#    try:
#        page = paginator.page(page_number)
#    except (EmptyPage, InvalidPage):
#        page = paginator.page(1)
#
#    # generate 1 ... 6 7 8 *9* 10 11 12 ... 16
#    #                ^    middle      ^
#    # maximum 4 items for left and right position,