def gallery(request): ajax = request.path_info.startswith('/ajax/') context = ajaxContext(request) if ajax else getGlobalContext(request) context['ajax'] = ajax context['extends'] = 'base.html' if not context['ajax'] else 'ajax.html' context['page_title'] = _('Gallery') context['categories'] = [ { 'title': details['translation'], 'url': u'/assets/{}/'.format(type), 'icon': 'pictures', 'image': staticImageURL(type, folder='gallery', extension='png'), } for i_type, (type, details) in enumerate(models.Asset.TYPES.items()) ] + [ { 'icon': 'present', 'title': _('Area items'), 'url': '/areas/', 'image': staticImageURL('area_items', folder='gallery', extension='png'), }, { 'icon': 'star', 'title': _('Items'), 'url': '/items/', 'image': staticImageURL('items', folder='gallery', extension='png'), }, ] return render(request, 'pages/gallery.html', context)
def signup(request): if request.user.is_authenticated(): redirectToProfile(request) context = getGlobalContext(request) if context.get('launch_date', None): return redirect('/prelaunch/') if request.method == "POST": form = CreateUserForm(request.POST, request=request) if form.is_valid(): new_user = models.User.objects.create_user(**form.cleaned_data) user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password']) preferences = models.UserPreferences.objects.create( user=user, i_language=request.LANGUAGE_CODE, view_activities_language_only= ONLY_SHOW_SAME_LANGUAGE_ACTIVITY_BY_DEFAULT, ) login_action(request, user) url = '/accounts/add/{}{}'.format( ('?next={}'.format(urlquote(request.GET['next'])) if 'next' in request.GET else ''), ('&next_title={}'.format(request.GET['next_title']) if 'next' in request.GET and 'next_title' in request.GET else '')) return redirect(url) else: form = CreateUserForm(request=request) context['form'] = form context['next'] = request.GET.get('next', None) context['next_title'] = request.GET.get('next_title', None) return render(request, 'pages/signup.html', context)
def successdelete(request): ajax = request.path_info.startswith('/ajax/') context = ajaxContext(request) if ajax else getGlobalContext(request) context['success_sentence'] = _('Successfully deleted!') return render(request, 'pages/ajax/success.html' if ajax else 'pages/success.html', context)
def login(request): context = getGlobalContext(request) context['next'] = request.GET['next'] if 'next' in request.GET else None context['next_title'] = request.GET[ 'next_title'] if 'next_title' in request.GET else None del (context['form']) return login_view(request, template_name='pages/login.html', extra_context=context)
def collections(request): context = getGlobalContext(request) redirectWhenNotAuthenticated(request, context, next_title='Collections details') if not hasPermission(request.user, 'see_collections_details'): raise PermissionDenied() context['page_title'] = 'Dev / Collections' context['collections'] = getMagiCollections() context['groups_per_permissions'] = groupsForAllPermissions( request.user.preferences.GROUPS) return render(request, 'pages/dev/collections.html', context)
def custom_wiki(wiki, wiki_name, request, wiki_url): context = getGlobalContext(request) context['wiki_url'] = wiki_url context['page_title'] = wiki_name if wiki_url in [ 'Home', '_Sidebar' ] else u'{} - {}'.format( wiki_url.replace('_', ' ').replace('-', ' '), wiki_name) context['hide_side_bar'] = wiki_url == '_Sidebar' context['small_container'] = True context['wiki'] = wiki context['full_wiki_url'] = 'https://github.com/{}/{}/wiki/'.format( wiki[0], wiki[1]) context['js_files'] = [ 'bower/marked/lib/marked', 'bower/github-wiki/js/githubwiki', 'wiki' ] return render(request, 'pages/wiki.html', context)
def block(request, pk, unblock=False): context = getGlobalContext(request) redirectWhenNotAuthenticated(request, context, next_title=_('Settings')) user = get_object_or_404(models.User.objects.select_related('preferences'), pk=pk) block = True if request.user.preferences.blocked.filter(pk=user.pk).exists(): block = False context['info_message'] = _(u'You blocked {username}.').format( username=user.username) context['blocking'] = block title = _(u'Block {username}').format( username=user.username) if block else _(u'Unblock {username}').format( username=user.username) context['page_title'] = title context['extends'] = 'base.html' context['form'] = Confirm() context['alert_message'] = (_( u'Are you sure you want to block {username}? You will not be able to see any content created by {username}.' ) if block else _(u'Are you sure you want to unblock {username}?')).format( username=user.username) context['alert_type'] = 'danger' context['alert_flaticon'] = 'fingers' if request.method == 'POST': context['form'] = Confirm(request.POST) if context['form'].is_valid(): if block: request.user.preferences.blocked.add(user) request.user.preferences.following.remove(user) user.preferences.following.remove(request.user) redirect_url = context['current_url'] else: request.user.preferences.blocked.remove(user) redirect_url = user.item_url if 'next' in request.GET: redirect_url = request.GET['next'] request.user.preferences.update_cache('blocked_ids') request.user.preferences.save() user.preferences.update_cache('blocked_by_ids') user.preferences.save() raise HttpRedirectException(redirect_url) context['form'].submit_title = title return render(request, 'pages/block.html', context)
def mapDefaultContext(request): context = getGlobalContext(request) context['js_files'] = [ 'https://maps.googleapis.com/maps/api/js?key=AIzaSyDHtAPFTmOCQZrKSjZlIeoZrZYLJjKLupE', 'oms.min', ] if request.user.is_authenticated() and request.user.preferences.latitude: context['center'] = { 'latitude': request.user.preferences.latitude, 'longitude': request.user.preferences.longitude, } context['zoom'] = 10 if 'center' in request.GET: center = request.GET['center'].split(',') try: context['center'] = { 'latitude': center[0], 'longitude': center[1], } except IndexError: pass if 'zoom' in request.GET: context['zoom'] = request.GET['zoom'] return context
def teambuilder(request): context = getGlobalContext(request) redirectWhenNotAuthenticated(request, context, next_title=_('Team builder')) context['page_title'] = _('Team builder') context['side_bar_no_padding'] = True context['learn_more_sentence'] = _('Learn more') context['no_container'] = True context['js_files'] = ['teambuilder'] if len(request.GET) > 0: form = TeamBuilderForm(request.GET, request=request) if form.is_valid(): skill_type_main_value = SKILL_TYPE_TO_MAIN_VALUE.get(form.cleaned_data.get('i_skill_type', ''), '').format( perfect_accuracy=form.cleaned_data.get('perfect_accuracy', 0.8), stamina_accuracy=form.cleaned_data.get('stamina_accuracy', 0.8), ) extra_select = { 'overall_stats': u'CASE trained WHEN 1 THEN performance_trained_max + technique_trained_max + visual_trained_max ELSE performance_max + technique_max + visual_max END', } order_by = [] if form.cleaned_data['i_band']: extra_select['is_correct_band'] = u'i_band = {}'.format(form.cleaned_data['i_band']) order_by.append('-is_correct_band') if form.cleaned_data['i_attribute']: extra_select['is_correct_attribute'] = u'i_attribute = {}'.format(form.cleaned_data['i_attribute']) order_by.append('-is_correct_attribute') if form.cleaned_data['i_skill_type']: extra_select['is_correct_skill'] = u'i_skill_type = {}'.format(form.cleaned_data['i_skill_type']) extra_select['skill_real_duration'] = u'skill_duration + ((IFNULL(skill_level, 1) - 1) * 0.5)' extra_select['skill_main_value'] = skill_type_main_value extra_select['skill_significant_value'] = u'({}) * ({})'.format(extra_select['skill_real_duration'], extra_select['skill_main_value']) order_by += ['-skill_significant_value', '-is_correct_skill'] order_by += ['-overall_stats'] queryset = form.Meta.model.objects.extra(select=extra_select).order_by(*order_by).select_related('card', 'card__member') queryset = form.filter_queryset(queryset, request.GET, request) # Only allow one of each member per team added_members = [] team = [] for cc in queryset: if request.user.is_staff: cc.calculation_details = [ unicode(cc.card), mark_safe(u'Ordering: <ol>{}</ol>'.format(''.join([ u'<li>{}</li>'.format(o.replace('-', '').replace('_', ' ').capitalize()) for o in order_by ]))), ] if form.cleaned_data['i_skill_type']: cc.calculation_details += [ u'Skill type: {}'.format(unicode(cc.card.t_skill_type)), 'Skill: {}'.format(cc.card.full_skill), 'Base skill duration: {}'.format(cc.card.skill_duration), 'Skill level: {}'.format(cc.skill_level or 1), mark_safe(u'Real skill duration: {}<br><small class="text-muted">skill_duration + (skill_level - 1) * 0.5)</small>'.format(cc.skill_real_duration)), mark_safe(u'Main value of skill: {}<br><small class="text-muted">{}</small>'.format( cc.skill_main_value, skill_type_main_value, )), mark_safe(u'Skill significant value: {}<br><small class="text-muted">real_skill_duration * main_value</small>'.format(cc.skill_significant_value),), ] if cc.card.member_id in added_members: continue team.append(cc) added_members.append(cc.card.member_id) if len(team) == int(form.cleaned_data.get('total_cards', 5) or 5): break context['team'] = team else: context['hide_side_bar'] = True else: form = TeamBuilderForm(request=request) context['hide_side_bar'] = True cuteFormFieldsForContext({ 'i_band': { 'image_folder': 'band', 'to_cuteform': 'value', 'extra_settings': { 'modal': 'true', 'modal-text': 'true', }, }, 'i_attribute': {}, 'i_skill_type': { 'to_cuteform': lambda k, v: CardCollection._skill_icons[k], 'transform': CuteFormTransform.Flaticon, }, 'total_cards': { 'type': CuteFormType.HTML, }, }, context, form=form, prefix='#teambuilder-form ') context['filter_form'] = form return render(request, 'pages/teambuilder.html', context)
def _view(request, *args, **kwargs): # Check permissions permissions_context = { 'current_url': request.get_full_path() } if page.get('logout_required', False) and request.user.is_authenticated(): raise PermissionDenied() if page.get('authentication_required'): redirectWhenNotAuthenticated(request, permissions_context, next_title=page.get('title', '')) if page.get('staff_required', False): redirectWhenNotAuthenticated(request, permissions_context, next_title=page.get('title', '')) if not request.user.is_staff and not request.user.is_superuser: raise PermissionDenied() if page.get('prelaunch_staff_required', False): redirectWhenNotAuthenticated(request, permissions_context, next_title=page.get('title', '')) if not request.user.hasPermission('access_site_before_launch'): raise PermissionDenied() if page.get('permissions_required', []): redirectWhenNotAuthenticated(request, permissions_context, next_title=page.get('title', '')) if not hasPermissions(request.user, page['permissions_required']): raise PermissionDenied() if page.get('one_of_permissions_required', []): redirectWhenNotAuthenticated(request, permissions_context, next_title=page.get('title', '')) if not hasOneOfPermissions(request.user, page['one_of_permissions_required']): raise PermissionDenied() if boilerplate: # Context context = getGlobalContext(request=request) context['extends'] = 'base.html' if not context['ajax'] else 'ajax.html' context['disqus_identifier'] = context['current'] # Settings from page context['show_small_title'] = page.get('show_small_title', True) context['show_title'] = page.get('show_title', False) context['share_image'] = staticImageURL(page.get('share_image', None)) context['page_description'] = page.get('page_description', None) context['comments_enabled'] = page.get('comments_enabled', False) context['template'] = page.get('template', name) # Set title and prefixes context['title_prefixes'] = [] if 'navbar_link_list' in page: getNavbarPrefix(page['navbar_link_list'], request, context, append_to=context['title_prefixes']) default_page_title = page.get('title', None) if callable(default_page_title): default_page_title = default_page_title(context) h1 = { 'title': default_page_title, 'icon': page.get('icon', None), 'image': page.get('image', None), } h1ToContext(h1, context) context['page_title'] = pageTitleFromPrefixes(context['title_prefixes'], default_page_title) # Call function if function: result = function(request, context, *args, **kwargs) # Render with full template if page.get('full_template', False): return render(request, u'pages/{}.html'.format( name if page['full_template'] == True else page['full_template']), context) # Render with boilerplate if page.get('as_json', False): if result is None: return HttpResponse('') return JsonResponse(result) elif page.get('as_form', False): return render(request, 'form.html', context) elif page.get('as_sidebar', False): context['sidebar_show_title'] = True context['sidebar_template'] = 'include/{}.html'.format( page.get('sidebar_template', '{}_sidebar'.format(name))) context['template'] = 'pages/{}.html'.format(context['template']) return render(request, 'sidebar.html', context) return render(request, 'pages/boilerplate.html', context) else: # Render expected to be called by function return function(request, *args, **kwargs)
def settings(request): context = getGlobalContext(request) redirectWhenNotAuthenticated(request, context, next_title=_('Settings')) context['preferences'] = request.user.preferences context['accounts'] = request.user.accounts.all() context['add_account_sentence'] = _(u'Add {thing}').format( thing=_('Account')) context['add_link_sentence'] = _(u'Add {thing}').format(thing=_('Link')) context['delete_link_sentence'] = _(u'Delete {thing}').format( thing=_('Link')) context['global_outside_permissions'] = GLOBAL_OUTSIDE_PERMISSIONS context['forms'] = OrderedDict([ ('preferences', UserPreferencesForm(instance=context['preferences'], request=request)), ('form', UserForm(instance=request.user, request=request)), ('changePassword', ChangePasswordForm(request=request)), ('emails', EmailsPreferencesForm(request=request)), ('security', SecurityPreferencesForm(instance=context['preferences'], request=request)), ('addLink', AddLinkForm(request=request)), ]) if request.method == 'POST': for (form_name, form) in context['forms'].items(): if form_name in request.POST: if form_name == 'form': form = UserForm(request.POST, instance=request.user, request=request) if form.is_valid(): form.save() models.onUserEdited(request.user) if ON_USER_EDITED: ON_USER_EDITED(request.user) redirectToProfile(request) elif form_name == 'preferences': form = UserPreferencesForm(request.POST, instance=context['preferences'], request=request) if form.is_valid(): form.save() models.onPreferencesEdited(request.user) if ON_PREFERENCES_EDITED: ON_PREFERENCES_EDITED(request.user) redirectToProfile(request) elif form_name == 'addLink': form = AddLinkForm(request.POST, request=request) if form.is_valid(): form.save() elif form_name == 'changePassword': form = ChangePasswordForm(request.POST, request=request) if form.is_valid(): form.save() redirectToProfile(request) elif form_name == 'emails': form = EmailsPreferencesForm(request.POST, request=request) if form.is_valid(): form.save() redirectToProfile(request) elif form_name == 'security': form = SecurityPreferencesForm( request.POST, instance=context['preferences'], request=request) if form.is_valid(): form.save() models.onPreferencesEdited(request.user) if ON_PREFERENCES_EDITED: ON_PREFERENCES_EDITED(request.user) redirectToProfile(request) context['forms'][form_name] = form context['links'] = list(request.user.links.all()) context['blocked'] = list(request.user.preferences.blocked.all()) for blocked_user in context['blocked']: blocked_user.block_message = _(u'You blocked {username}.').format( username=blocked_user.username) blocked_user.unblock_message = _(u'Unblock {username}').format( username=blocked_user.username) context['js_files'] = ['settings'] filter_cuteform = { 'i_language': { 'type': CuteFormType.Images, 'image_folder': 'language', }, 'color': { 'type': CuteFormType.Images, }, } for i in range(1, 4): filter_cuteform['favorite_character{}'.format(i)] = { 'to_cuteform': lambda k, v: FAVORITE_CHARACTERS_IMAGES[k], 'extra_settings': { 'modal': 'true', 'modal-text': 'true', }, } cuteFormFieldsForContext(filter_cuteform, context, context['forms']['preferences']) cuteFormFieldsForContext( { 'type': { 'image_folder': 'links', }, 'relevance': { 'type': CuteFormType.HTML, }, }, context, context['forms']['addLink']) return render(request, 'pages/settings.html', context)
def about_game(request): context = getGlobalContext(request) context['game_description'] = GAME_DESCRIPTION context['game_url'] = GAME_URL return render(request, 'ajax/about_game.html', context)
def aboutDefaultContext(request): context = getGlobalContext(request) context['about_description_template'] = 'include/about_description' context['about_photo'] = ABOUT_PHOTO context['site_long_description'] = SITE_LONG_DESCRIPTION context['feedback_form'] = FEEDBACK_FORM context['contact_methods'] = [ ('Discord', 'discord', CONTACT_DISCORD), ('Twitter', 'twitter', u'https://twitter.com/{}/'.format(TWITTER_HANDLE) if TWITTER_HANDLE else None), ('Reddit', 'reddit', u'https://www.reddit.com/user/{}/'.format(CONTACT_REDDIT) if CONTACT_REDDIT else None), ('Facebook', 'facebook', u'https://facebook.com/{}/'.format(CONTACT_FACEBOOK) if CONTACT_FACEBOOK else None), (_('Email'), 'flaticon-contact', CONTACT_EMAIL if CONTACT_EMAIL else None), ('GitHub', 'github', u'https://github.com/{}/{}/'.format( GITHUB_REPOSITORY[0], GITHUB_REPOSITORY[1]) if GITHUB_REPOSITORY else None), ('Bug tracker', 'flaticon-album', BUG_TRACKER_URL if BUG_TRACKER_URL and not FEEDBACK_FORM else None), ] context['franchise'] = _( '{site} is not a representative and is not associated with {game}. Its logos and images are Trademarks of {company}.' ).format(site=_(SITE_NAME), game=_(GAME_NAME), company=_('the company that owns {game}').format(game=GAME_NAME)) context['staff'] = models.User.objects.filter( is_staff=True).select_related( 'preferences', 'staff_details').prefetch_related( Prefetch( 'links', queryset=models.UserLink.objects.order_by('-i_relevance'), to_attr='all_links'), ).extra( select={ 'length_of_groups': 'Length(c_groups)', 'is_manager': 'CASE WHEN c_groups LIKE "%%manager%%" THEN 1 ELSE 0 END', }).order_by('-is_manager', '-length_of_groups') try: my_timezone = request.user.staff_details.timezone if request.user.is_staff else None except ObjectDoesNotExist: my_timezone = None for staff_member in context['staff']: # Add staff member location URL if staff_member.preferences.location: latlong = '{},{}'.format( staff_member.preferences.latitude, staff_member.preferences. longitude) if staff_member.preferences.latitude else None staff_member.location_url = u'/map/?center={}&zoom=10'.format( latlong ) if 'map' in context[ 'all_enabled'] and latlong else u'https://www.google.com/maps?q={}'.format( staff_member.preferences.location) # Add staff member birthday URL and formatting if staff_member.preferences.birthdate: staff_member.formatted_birthday = dateformat.format( staff_member.preferences.birthdate, "F d") today = datetime.date.today() birthday = staff_member.preferences.birthdate.replace( year=today.year) if birthday < today: birthday = birthday.replace(year=today.year + 1) staff_member.birthday_url = 'https://www.timeanddate.com/countdown/birthday?iso={date}T00&msg={username}%27s+birthday'.format( date=dateformat.format(birthday, "Ymd"), username=staff_member.username) # Availability calendar try: staff_member.has_staff_details = bool( staff_member.staff_details.id ) if staff_member.is_staff else None except models.StaffDetails.DoesNotExist: staff_member.has_staff_details = False staff_member.staff_details = models.StaffDetails() if request.user.is_staff and staff_member.has_staff_details and ( staff_member.staff_details.d_availability or staff_member.staff_details.d_weekend_availability): staff_member.show_calendar = True if my_timezone and staff_member.staff_details.timezone: staff_member.availability_calendar = staff_member.staff_details.availability_calendar_timezone( my_timezone) staff_member.calendar_with_timezone = True else: staff_member.availability_calendar = staff_member.staff_details.availability_calendar staff_member.calendar_with_timezone = False # Stats staff_member.stats = {} for group, details in staff_member.preferences.groups_and_details.items( ): stats = details.get('stats', []) staff_member.stats[group] = [] if stats: for stat in stats: model = getattr(models, stat['model']) total = model.objects.filter( **{ stat.get('selector_to_owner', model.selector_to_owner()): staff_member }).filter(**(stat.get('filters', {}))).count() if total: staff_member.stats[group].append( mark_safe( unicode(stat['template']).format( total=u'<strong>{}</strong>'.format( total)))) context['now'] = timezone.now() context['api_enabled'] = False context['contribute_url'] = CONTRIBUTE_URL context['other_sites'] = [s for s in other_sites if s['name'] != SITE_NAME] context['other_sites_colsize'] = int( math.ceil(12 / (len(context['other_sites'])))) context['ajax'] = context['current_url'].startswith('/ajax/') context['extends'] = 'base.html' if not context['ajax'] else 'ajax.html' return context
def prelaunch(request, *args, **kwargs): context = getGlobalContext(request) if not context.get('launch_date', None): return redirect('signup') context['twitter'] = TWITTER_HANDLE return render(request, 'pages/prelaunch.html', context)
def index(request): context = getGlobalContext(request) indexExtraContext(context) return render(request, 'pages/index.html', context)