Compare commits

..
6 Commits
125 changed files with 2091 additions and 334 deletions

No files matched your search

View File
Whitespace-only changes.
View File
Whitespace-only changes.
+30
View File
@@ -54,3 +54,33 @@ Open `http://127.0.0.1:8000/admin/`. Local mode uses SQLite. Run `python manage.
## Updating Studio v1.0 ## Updating Studio v1.0
Keep the same project directory, `.env`, `secrets/`, `data/`, and Docker volumes. After making a database backup, unpack the updated project files into that directory and run `docker compose up -d --build`. Startup applies the migration. It locks the displayed title to SLUMP X LAND and keeps existing chapters, editorial content, and site settings. Keep the same project directory, `.env`, `secrets/`, `data/`, and Docker volumes. After making a database backup, unpack the updated project files into that directory and run `docker compose up -d --build`. Startup applies the migration. It locks the displayed title to SLUMP X LAND and keeps existing chapters, editorial content, and site settings.
### Pages, chapter samples and Fan Club checkout
- **Pages → Manage pages**: edit a page title, slug, navigation label/placement,
local destination, or plain-text body. Clear the destination to publish an
original content page. Select a published row and use **Use the selected
published page as homepage** to switch. **Restore the Sol’Terra map as homepage**
restores the map; the map is always available at `/map/`.
- **Chapters**: set **Chapter price (USD)** to $0.50 or more to enable a Stripe
one-time purchase. A paid order unlocks that chapter in the reader for the
signed-in purchaser. A physical book does not automatically unlock the reader.
- **Shop products**: select a **Sample chapter** on a listing. The storefront
links to that published chapter. The newest three published chapters are free in full; older chapters require access.
A physical product with that association appears in the reader's purchase options.
- The migration creates two inactive monthly Fan Club product records: **Early
Access** and **Studio Vault**. Replace the placeholder price with your real
monthly price and optionally set the matching same-mode Stripe recurring
Price ID before making each product active. If using a Price ID, match the
displayed Studio price to the amount charged by Stripe. Both tiers unlock the
published chapter library; member posts still follow tier requirements.
- In Stripe create an endpoint at
`https://slumpxland-official.com/shop/webhooks/stripe/` for
`checkout.session.completed`, `checkout.session.async_payment_succeeded`,
`customer.subscription.updated`, `customer.subscription.deleted`,
`invoice.paid`, `invoice.payment_failed`, and `charge.refunded`.
Set the new endpoint's signing secret in the live `.env` as
`SLX_COMMERCE_STRIPE_WEBHOOK_SECRET`. The existing Stripe API key and
`SLX_STRIPE_ORIGIN` can be reused. A separate endpoint signing secret keeps
the existing legacy checkout endpoint independent. Test in Stripe test mode
before accepting live payments, and don't put payment keys into this ZIP.
View File
Whitespace-only changes.
View File
Whitespace-only changes.
+133 -18
View File
@@ -16,7 +16,7 @@ from django.utils.html import format_html
from .models import SiteSettings, Chapter, Page, Entry, DiscussionComment, FanNotice, ChapterReview, SeriesReview, BookListing, ChapterPurchase, StreamComment, FanMembership, SupportCredit, AIChapterReview from .models import SiteSettings, Chapter, Page, Entry, DiscussionComment, FanNotice, ChapterReview, SeriesReview, BookListing, ChapterPurchase, StreamComment, FanMembership, SupportCredit, AIChapterReview
from .fans import live, notify from .fans import live, notify
from .newsletter_admin import CampaignAdmin, SubscriberAdmin from .newsletter_admin import CampaignAdmin, SubscriberAdmin
from .models import NewsletterCampaign, NewsletterSubscriber, PageBackground, FloatingArtwork, ProductVariant, PageSharePreview from .models import NewsletterCampaign, NewsletterSubscriber, PageBackground, FloatingArtwork, ProductVariant, PageSharePreview, ShopOrder, MemberPost, MemberArtwork
from .backgrounds import PAGE_CHOICES from .backgrounds import PAGE_CHOICES
from .sharing import validate_share_path from .sharing import validate_share_path
from .uploads import ShareImageUploadField from .uploads import ShareImageUploadField
@@ -39,22 +39,22 @@ class Studio(admin.AdminSite):
def each_context(self, request): def each_context(self, request):
context = super().each_context(request) context = super().each_context(request)
channels = [ channels = [
('SLUMP X LAND', [ ('Publishing', [('▤', 'Chapters', 'chapter', None), ('▧', 'Blog', 'entry', Entry.Kind.NEWS),
('▤', 'Chapters', 'chapter', None), ('◎', 'Cast', 'entry', Entry.Kind.CAST), ('◇', 'World archive', 'entry', Entry.Kind.WORLD)]),
('▧', 'Blog', 'entry', Entry.Kind.NEWS), ('Website & navigation', [('▤', 'Pages & homepage', 'managedpage', None),
('◎', 'Cast', 'entry', Entry.Kind.CAST), ('◎', 'Map locations', 'maplocation', None), ('↗', 'Link previews', 'pagesharepreview', None)]),
('◇', 'World archive', 'entry', Entry.Kind.WORLD), ('Design & artwork', [('▧', 'Page backgrounds', 'pagebackground', None), ('✦', 'Floating artwork', 'floatingartwork', None)]),
]), ('Shop & orders', [('▤', 'Shop products', 'shop.product', None), ('◈', 'Orders', 'shop.order', None),
('Community', [('◎', 'Fan memberships', 'fanmembership', None), ('◈', 'Verified support', 'supportcredit', None), ('◉', 'Moderate comments', 'discussioncomment', None), ('★', 'Moderate chapter reviews', 'chapterreview', None), ('★', 'Moderate series reviews', 'seriesreview', None), ('◉', 'Stream comments', 'streamcomment', None)]), ('▤', 'Legacy book listings', 'booklisting', None), ('▧', 'Legacy shop orders', 'shoporder', None),
('◈', 'Chapter purchases', 'chapterpurchase', None)]),
('Memberships & collectors', [('◎', 'Subscriptions', 'shop.subscription', None),
('◎', 'Fan memberships', 'fanmembership', None), ('▧', 'Member content', 'memberpost', None),
('◈', 'Verified support', 'supportcredit', None), ('◆', 'Collector profiles', 'collectorprofile', None)]),
('Comments & reviews', [('◉', 'Discussion comments', 'discussioncomment', None),
('★', 'Chapter reviews', 'chapterreview', None), ('★', 'Series reviews', 'seriesreview', None),
('◉', 'Stream comments', 'streamcomment', None)]),
('Newsletter', [('✉', 'Campaigns', 'newslettercampaign', None), ('◎', 'Subscribers', 'newslettersubscriber', None)]), ('Newsletter', [('✉', 'Campaigns', 'newslettercampaign', None), ('◎', 'Subscribers', 'newslettersubscriber', None)]),
('Commerce', [ ('General settings', [('◈', 'Site settings', 'sitesettings', None)]),
('▤', 'Shop products', 'shop.product', None),
('◈', 'Orders', 'shop.order', None),
('◎', 'Subscriptions', 'shop.subscription', None),
('▤', 'Book listings', 'booklisting', None),
('◈', 'Chapter purchases', 'chapterpurchase', None),
]),
('Studio', [('◈', 'Site settings', 'sitesettings', None), ('▧', 'Page backgrounds', 'pagebackground', None), ('✦', 'Floating artwork', 'floatingartwork', None), ('↗', 'Link previews', 'pagesharepreview', None)]),
] ]
groups = [] groups = []
for name, items in channels: for name, items in channels:
@@ -73,6 +73,19 @@ class Studio(admin.AdminSite):
if links: if links:
groups.append({'name': name, 'links': links}) groups.append({'name': name, 'links': links})
row = SiteSettings.objects.filter(pk=1).only('site_palette').first() row = SiteSettings.objects.filter(pk=1).only('site_palette').first()
if self.can_edit_countdown(request, row):
shortcuts = [
('Website & navigation', '◉', 'Homepage countdown & map placement', 'homepage_countdown'),
('Website & navigation', '↗', 'Public menu', 'public_menu'),
('Design & artwork', '✦', 'Site and Studio colors', 'site_theme'),
]
for category, icon, title, route in shortcuts:
group = next((group for group in groups if group['name'] == category), None)
if group is None:
group = {'name': category, 'links': []}
groups.append(group)
url = reverse(f'admin:{route}')
group['links'].append({'icon': icon, 'title': title, 'url': url, 'active': request.path == url})
context['studio_theme_vars'] = css_variables(row.site_palette, STUDIO_KEYS) if row else '' context['studio_theme_vars'] = css_variables(row.site_palette, STUDIO_KEYS) if row else ''
context['can_edit_theme'] = self.can_edit_countdown(request, row) context['can_edit_theme'] = self.can_edit_countdown(request, row)
context['studio_groups'] = groups context['studio_groups'] = groups
@@ -215,6 +228,7 @@ class SettingsAdmin(admin.ModelAdmin):
('Background', {'fields': ['hero_art', 'blur_hero']}), ('Background', {'fields': ['hero_art', 'blur_hero']}),
('Links', {'fields': ['publisher_url', 'shop_url']}), ('Links', {'fields': ['publisher_url', 'shop_url']}),
('Community tiers', {'fields': ['support_url', 'caster_threshold', 'striker_threshold', 'seat_threshold']}), ('Community tiers', {'fields': ['support_url', 'caster_threshold', 'striker_threshold', 'seat_threshold']}),
('SLX Monthly', {'fields': ['membership_popup', 'member_scout_url', 'member_vault_url']}),
('Author comments', {'fields': ['author_comment_name', 'author_comment_avatar', 'author_comment_signature']}), ('Author comments', {'fields': ['author_comment_name', 'author_comment_avatar', 'author_comment_signature']}),
('Coming soon', {'fields': ['next_release_title', 'next_release_at', 'countdown_creator_note', 'countdown_art', ('Coming soon', {'fields': ['next_release_title', 'next_release_at', 'countdown_creator_note', 'countdown_art',
'blur_countdown', 'show_chapter_countdowns']}), 'blur_countdown', 'show_chapter_countdowns']}),
@@ -624,12 +638,44 @@ class PageSharePreviewAdmin(admin.ModelAdmin):
@admin.register(BookListing, site=studio) @admin.register(BookListing, site=studio)
class BookListingAdmin(admin.ModelAdmin): class BookListingAdmin(admin.ModelAdmin):
list_display = ['title', 'category', 'visible'] list_display = ['title', 'category', 'price_usd', 'visible']
list_editable = ['price_usd']
list_filter = ['category', 'visible'] list_filter = ['category', 'visible']
search_fields = ['title'] search_fields = ['title']
inlines = [ProductVariantInline] inlines = [ProductVariantInline]
@admin.register(ShopOrder, site=studio)
class ShopOrderAdmin(admin.ModelAdmin):
list_display = ['reference', 'item', 'amount_usd', 'status', 'livemode', 'fulfilled', 'created_at']
list_filter = ['status', 'livemode', 'fulfilled']
search_fields = ['item', 'email', '=reference', '=stripe_session', '=payment_intent']
fields = ['reference', 'item', 'amount_usd', 'status', 'livemode', 'email', 'stripe_session',
'payment_intent', 'stripe_dashboard', 'created_at', 'paid_at', 'fulfilled']
readonly_fields = fields[:-1]
@admin.display(description='Amount', ordering='amount_cents')
def amount_usd(self, obj):
return f'${obj.amount_cents // 100}.{obj.amount_cents % 100:02d}'
@admin.display(description='Order in Stripe')
def stripe_dashboard(self, obj):
if obj and obj.payment_intent:
path = 'payments/' if obj.livemode else 'test/payments/'
return format_html('<a href="{}">View in Stripe</a>',
'https://dashboard.stripe.com/' + path + obj.payment_intent)
return 'Available after payment.'
def get_readonly_fields(self, request, obj=None):
return self.fields if obj and obj.status != ShopOrder.Status.PAID else self.readonly_fields
def has_add_permission(self, request):
return False
def has_delete_permission(self, request, obj=None):
return False
@admin.register(ChapterPurchase, site=studio) @admin.register(ChapterPurchase, site=studio)
class ChapterPurchaseAdmin(admin.ModelAdmin): class ChapterPurchaseAdmin(admin.ModelAdmin):
list_display = ['chapter', 'user', 'mode', 'amount', 'paid_at', 'revoked'] list_display = ['chapter', 'user', 'mode', 'amount', 'paid_at', 'revoked']
@@ -667,11 +713,23 @@ class StreamCommentAdmin(admin.ModelAdmin):
@admin.register(FanMembership, site=studio) @admin.register(FanMembership, site=studio)
class FanMembershipAdmin(admin.ModelAdmin): class FanMembershipAdmin(admin.ModelAdmin):
autocomplete_fields = ['user'] autocomplete_fields = ['user']
list_display = ['user', 'subscriber_until', 'sol_seat'] list_display = ['user', 'member_tier', 'subscriber_until', 'sol_seat']
list_filter = ['sol_seat'] list_filter = ['sol_seat']
search_fields = ['user__username'] search_fields = ['user__username']
class MemberArtworkInline(admin.TabularInline):
model = MemberArtwork
extra = 1
@admin.register(MemberPost, site=studio)
class MemberPostAdmin(admin.ModelAdmin):
list_display = ['title', 'kind', 'required_tier', 'published', 'publish_at']
list_filter = ['published', 'required_tier', 'kind']
inlines = [MemberArtworkInline]
@admin.register(SupportCredit, site=studio) @admin.register(SupportCredit, site=studio)
class SupportCreditAdmin(admin.ModelAdmin): class SupportCreditAdmin(admin.ModelAdmin):
autocomplete_fields = ['user'] autocomplete_fields = ['user']
@@ -684,3 +742,60 @@ class SupportCreditAdmin(admin.ModelAdmin):
def has_delete_permission(self, request, obj=None): def has_delete_permission(self, request, obj=None):
return False return False
from .models import ManagedPage
@admin.register(ManagedPage, site=studio)
class ManagedPageAdmin(admin.ModelAdmin):
list_display = ('title', 'slug', 'published', 'show_in_menu', 'homepage')
prepopulated_fields = {'slug': ('title',)}
search_fields = ('title', 'slug', 'link')
actions = ('use_as_homepage', 'use_map_homepage')
@admin.action(description='Use the selected published page as homepage', permissions=['change'])
def use_as_homepage(self, request, queryset):
if queryset.count() != 1 or not queryset.first().published:
self.message_user(request, 'Select exactly one published page.', level='error')
return
with transaction.atomic():
ManagedPage.objects.filter(homepage=True).update(homepage=False)
queryset.update(homepage=True)
self.message_user(request, 'Homepage updated.')
@admin.action(description='Restore the Sol’Terra map as homepage', permissions=['change'])
def use_map_homepage(self, request, queryset):
ManagedPage.objects.filter(homepage=True).update(homepage=False)
self.message_user(request, 'The Sol’Terra map is the homepage.')
from .models import MapLocation
@admin.register(MapLocation, site=studio)
class MapLocationAdmin(admin.ModelAdmin):
change_form_template = 'admin/catalog/maplocation/change_form.html'
list_display = ('title', 'page', 'path', 'visible', 'position')
list_filter = ('visible',)
search_fields = ('title', 'key', 'path')
prepopulated_fields = {'key': ('title',)}
class Media:
js = ('studio-map-picker.js',)
from .models import CollectorProfile
@admin.register(CollectorProfile, site=studio)
class CollectorProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'display_name', 'public')
readonly_fields = ('user', 'display_name', 'public', 'photo')
search_fields = ('user__username', 'display_name')
def has_add_permission(self, request):
return False
def has_change_permission(self, request, obj=None):
return False
+33
View File
@@ -0,0 +1,33 @@
from django.conf import settings
from django.db.models import Q
from .fans import live
from .models import Chapter
FREE_ARCHIVE_SIZE = 3
def rolling_chapter_ids():
return live(Chapter).order_by("-publish_at", "-number").values("pk")[:FREE_ARCHIVE_SIZE]
def stripe_live_mode():
return settings.SLX_STRIPE_SECRET_KEY.startswith(('sk_live_', 'rk_live_'))
def full_chapters(user):
from .membership import active_tier
from .models import ChapterPurchase
from shop.models import Order, OrderItem
chapters = live(Chapter)
if not user.is_authenticated or not user.is_active:
return chapters.filter(pk__in=rolling_chapter_ids())
if (user.is_staff and user.has_perm('catalog.view_chapter')) or active_tier(user):
return chapters
paid = ChapterPurchase.objects.filter(user=user, mode='sandbox' if settings.SLX_PAYPAL_MODE == 'sandbox' else 'live',
paid_at__isnull=False, revoked=False)
orders = OrderItem.objects.filter(order__user=user, order__gateway=Order.Gateway.STRIPE,
order__stripe_live=stripe_live_mode(), order__status__in=[
Order.Status.PAID, Order.Status.SHIPPED, Order.Status.DELIVERED])
return chapters.filter(Q(pk__in=rolling_chapter_ids()) | Q(pk__in=paid.values('chapter_id')) | Q(pk__in=orders.values('chapter_id')))
+33
View File
@@ -0,0 +1,33 @@
from django import forms
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render
from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_http_methods
from shop.models import Order
from .models import CollectorProfile
def recognized_collectors():
paid = Order.objects.filter(status__in=[Order.Status.PAID, Order.Status.SHIPPED, Order.Status.DELIVERED])
return CollectorProfile.objects.filter(public=True, user__is_active=True,
user_id__in=paid.values('user_id')).select_related('user').order_by('display_name', 'pk')
class CollectorForm(forms.ModelForm):
class Meta:
model = CollectorProfile
fields = ('public', 'display_name', 'photo')
labels = {'public': 'Show my public name and photo in the collector thank-you section'}
@login_required
@never_cache
@require_http_methods(['GET', 'POST'])
def preferences(request):
profile = CollectorProfile.objects.filter(user=request.user).first() or CollectorProfile(user=request.user)
form = CollectorForm(request.POST or None, request.FILES or None, instance=profile)
if request.method == 'POST' and form.is_valid():
form.save()
return redirect('collector-preferences')
return render(request, 'collector-preferences.html', {'form': form})
+10 -5
View File
@@ -10,9 +10,9 @@ MENU = (
('read', 'Read', 'chapters'), ('blog', 'Blog', 'blog'), ('read', 'Read', 'chapters'), ('blog', 'Blog', 'blog'),
('reviews', 'Reviews', 'slx-series-reviews'), ('upcoming', 'Upcoming', 'upcoming'), ('reviews', 'Reviews', 'slx-series-reviews'), ('upcoming', 'Upcoming', 'upcoming'),
('live', 'SLX Live', 'stream'), ('cast', 'Cast', 'entries'), ('live', 'SLX Live', 'stream'), ('cast', 'Cast', 'entries'),
('world', 'World archive', 'entries'), ('books', 'Shop', 'books'), ('world', 'World archive', 'entries'),
('shop', 'Shop', None), ('search', 'Search', 'search'), ('shop', 'Shop', None), ('search', 'Search', 'search'),
('community', 'Community', 'slx-community'), ('library', 'My library', 'library'), ('community', 'Community', 'slx-community'), ('membership', 'Membership', 'membership'), ('library', 'My library', 'library'),
('notices', 'Fan notifications', 'fan-notices'), ('account', 'Fan corner', 'fan-login'), ('notices', 'Fan notifications', 'fan-notices'), ('account', 'Fan corner', 'fan-login'),
) )
RANKS = ( RANKS = (
@@ -21,14 +21,14 @@ RANKS = (
) )
def rank_for(membership, total, config, now): def rank_for(membership, total, config, now, stripe_active=False):
if (membership and membership.sol_seat) or (config.seat_threshold is not None and total >= config.seat_threshold): if (membership and membership.sol_seat) or (config.seat_threshold is not None and total >= config.seat_threshold):
return RANKS[4] return RANKS[4]
if total >= config.striker_threshold: if total >= config.striker_threshold:
return RANKS[3] return RANKS[3]
if total >= config.caster_threshold: if total >= config.caster_threshold:
return RANKS[2] return RANKS[2]
if membership and membership.subscriber_until and membership.subscriber_until > now: if stripe_active or (membership and membership.subscriber_until and membership.subscriber_until > now):
return RANKS[1] return RANKS[1]
return RANKS[0] return RANKS[0]
@@ -41,4 +41,9 @@ def load_ranks(ids, config):
sums = dict(SupportCredit.objects.filter(user_id__in=ids, voided=False).values('user_id') sums = dict(SupportCredit.objects.filter(user_id__in=ids, voided=False).values('user_id')
.annotate(total=Sum('amount')).values_list('user_id', 'total')) .annotate(total=Sum('amount')).values_list('user_id', 'total'))
now = timezone.now() now = timezone.now()
return {pk: rank_for(memberships.get(pk), sums.get(pk, Decimal(0)), config, now) for pk in ids} from .chapter_access import stripe_live_mode
from shop.models import Order, Subscription
active = set(Subscription.objects.filter(user_id__in=ids, gateway=Order.Gateway.STRIPE,
stripe_live=stripe_live_mode(), status=Subscription.Status.ACTIVE, current_period_end__gt=now,
entitlement_tier__isnull=False).values_list('user_id', flat=True))
return {pk: rank_for(memberships.get(pk), sums.get(pk, Decimal(0)), config, now, pk in active) for pk in ids}
+13 -3
View File
@@ -4,7 +4,7 @@ from django.urls import reverse
from .community import MENU from .community import MENU
from .fans import unread_count from .fans import unread_count
from .backgrounds import SAFE_ROUTES from .backgrounds import SAFE_ROUTES
from .models import FloatingArtwork, PageBackground, TitleFollow from .models import FloatingArtwork, PageBackground, TitleFollow, ManagedPage
from .newsletter import SignupForm, signup_open from .newsletter import SignupForm, signup_open
from .views import settings_row from .views import settings_row
from .theme import HEX_COLOR, css_variables from .theme import HEX_COLOR, css_variables
@@ -46,14 +46,24 @@ def site_context(request):
hidden = settings.hidden_menu if isinstance(settings.hidden_menu, list) else [] hidden = settings.hidden_menu if isinstance(settings.hidden_menu, list) else []
links = [] links = []
for key, label, route in MENU: for key, label, route in MENU:
if key in hidden or (key == 'shop' and not settings.shop_url): if key in hidden:
continue continue
if key in ('library', 'notices') and not request.user.is_authenticated: if key in ('library', 'notices') and not request.user.is_authenticated:
continue continue
if key == 'account' and request.user.is_authenticated: if key == 'account' and request.user.is_authenticated:
continue continue
url = settings.shop_url if key == 'shop' else reverse(route, args=[key] if key in ('cast', 'world') else []) url = (settings.shop_url or reverse('shop-index')) if key == 'shop' else reverse(route, args=[key] if key in ('cast', 'world') else [])
links.append({'key': key, 'label': label, 'url': url, 'active': key == active_nav}) links.append({'key': key, 'label': label, 'url': url, 'active': key == active_nav})
custom = list(ManagedPage.objects.filter(published=True, show_in_menu=True).order_by('pk'))
replacements = {page.menu_key: page for page in custom if page.menu_key}
for link in links:
page = replacements.pop(link['key'], None)
if page:
link.update(label=page.title, url=page.get_absolute_url(), active=request.path == page.get_absolute_url())
for page in custom:
if not page.menu_key:
links.append({'key': page.slug, 'label': page.title, 'url': page.get_absolute_url(),
'active': request.path == page.get_absolute_url()})
context['public_menu'] = links context['public_menu'] = links
if request.user.is_authenticated: if request.user.is_authenticated:
follow = TitleFollow.objects.filter(user=request.user).first() follow = TitleFollow.objects.filter(user=request.user).first()
+1 -1
View File
@@ -78,7 +78,7 @@ class HomepageCountdownForm(forms.ModelForm):
class Meta: class Meta:
model = SiteSettings model = SiteSettings
fields = ['homepage_countdown_enabled', 'homepage_countdown_title', 'homepage_countdown_at', fields = ['countdown_map_position', 'homepage_countdown_enabled', 'homepage_countdown_title', 'homepage_countdown_at',
'homepage_countdown_start_at', 'homepage_countdown_bar_color', 'homepage_countdown_start_at', 'homepage_countdown_bar_color',
'homepage_countdown_landing', 'homepage_countdown_cover', 'homepage_countdown_background', 'homepage_countdown_landing', 'homepage_countdown_cover', 'homepage_countdown_background',
'homepage_countdown_tint', 'homepage_countdown_tint_strength', 'homepage_countdown_note', 'homepage_countdown_tint', 'homepage_countdown_tint_strength', 'homepage_countdown_note',
+58
View File
@@ -0,0 +1,58 @@
from django.shortcuts import get_object_or_404, render
from django.utils import timezone
from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_safe
from .models import FanMembership, MemberPost
def active_tier(user):
from .chapter_access import stripe_live_mode
from shop.models import Order, Subscription
if not user.is_authenticated or not user.is_active:
return 0
now = timezone.now()
manual = FanMembership.objects.filter(user=user, subscriber_until__gt=now).values_list('member_tier', flat=True).first()
stripe = Subscription.objects.filter(user=user, gateway=Order.Gateway.STRIPE, stripe_live=stripe_live_mode(),
status=Subscription.Status.ACTIVE, current_period_end__gt=now,
entitlement_tier__isnull=False).order_by('-entitlement_tier').values_list('entitlement_tier', flat=True).first()
return max(manual or 0, stripe or 0)
def accessible_posts(user):
if not user.is_authenticated or not user.is_active:
return MemberPost.objects.none()
if user.is_staff and user.has_perm('catalog.view_memberpost'):
return MemberPost.objects.all()
now = timezone.now()
tier = active_tier(user)
return MemberPost.objects.filter(published=True, publish_at__lte=now, required_tier__lte=tier or 0)
@never_cache
@require_safe
def index(request):
from shop.models import Product
plans = Product.objects.filter(active=True, kind=Product.Kind.SUBSCRIPTION, member_tier__isnull=False)
return render(request, 'membership.html', {'posts': accessible_posts(request.user), 'plans': plans, 'comparison_rows': comparison_rows(plans)})
@never_cache
@require_safe
def detail(request, pk):
return render(request, 'member-post.html', {'post': get_object_or_404(accessible_posts(request.user), pk=pk)})
def comparison_rows(plans):
rows = {}
plans = list(plans)
for index, plan in enumerate(plans):
defaults = ['Published chapter library: Full access']
if plan.member_tier >= 2:
defaults.append('Draft pages and process notes: Included')
for line in (plan.comparison.splitlines() if plan.comparison else defaults):
title, sep, value = line.partition(':')
if sep and title.strip() and value.strip():
rows.setdefault(title.strip(), ['—'] * len(plans))[index] = value.strip()
return list(rows.items())
@@ -0,0 +1,57 @@
# Generated by Django 5.2.19 on 2026-11-23 22:47
import catalog.models
import django.core.validators
import uuid
from decimal import Decimal
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalog', '0024_page_share_previews'),
]
operations = [
migrations.CreateModel(
name='ShopOrder',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('reference', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
('item', models.CharField(max_length=320)),
('amount_cents', models.PositiveIntegerField()),
('livemode', models.BooleanField()),
('status', models.CharField(choices=[('open', 'Awaiting payment'), ('paid', 'Paid'), ('expired', 'Expired'), ('failed', 'Checkout unavailable')], db_index=True, default='open', max_length=10)),
('stripe_session', models.CharField(blank=True, max_length=255, null=True, unique=True)),
('payment_intent', models.CharField(blank=True, max_length=255)),
('email', models.EmailField(blank=True, max_length=254)),
('created_at', models.DateTimeField(auto_now_add=True)),
('paid_at', models.DateTimeField(blank=True, null=True)),
('fulfilled', models.BooleanField(default=False)),
],
options={
'ordering': ['-created_at'],
},
),
migrations.AddField(
model_name='booklisting',
name='price_usd',
field=models.DecimalField(blank=True, decimal_places=2, help_text='Charged by Stripe when this product has no variants.', max_digits=8, null=True, validators=[django.core.validators.MinValueValidator(Decimal('0.50'))], verbose_name='Stripe price (USD)'),
),
migrations.AddField(
model_name='booklisting',
name='ships',
field=models.BooleanField(default=True, help_text='Collect a shipping address at Stripe Checkout.', verbose_name='Ship this product'),
),
migrations.AlterField(
model_name='productvariant',
name='paypal_url',
field=models.URLField(blank=True, validators=[catalog.models.validate_book_checkout], verbose_name='PayPal Payment Link'),
),
migrations.AlterField(
model_name='productvariant',
name='price_usd',
field=models.DecimalField(blank=True, decimal_places=2, help_text='Charged by Stripe. If using a PayPal link, set the PayPal price separately.', max_digits=8, null=True, validators=[django.core.validators.MinValueValidator(Decimal('0.01'))], verbose_name='Price (USD)'),
),
]
+64
View File
@@ -0,0 +1,64 @@
# Generated by Django 5.2.19 on 2026-11-24 18:42
import catalog.models
import django.core.validators
import django.db.models.deletion
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalog', '0025_stripe_shop_orders'),
]
operations = [
migrations.CreateModel(
name='MemberPost',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=160)),
('body', models.TextField(blank=True)),
('kind', models.CharField(choices=[('note', 'Creator note'), ('early', 'Early chapter'), ('draft', 'Draft pages')], default='note', max_length=12)),
('required_tier', models.PositiveSmallIntegerField(choices=[(1, 'Early Access'), (2, 'Studio Vault')], default=1)),
('published', models.BooleanField(default=False)),
('publish_at', models.DateTimeField(default=django.utils.timezone.now)),
],
options={
'ordering': ['-publish_at', '-pk'],
},
),
migrations.AddField(
model_name='fanmembership',
name='member_tier',
field=models.PositiveSmallIntegerField(choices=[(1, 'Early Access'), (2, 'Studio Vault')], default=1, verbose_name='Content tier'),
),
migrations.AddField(
model_name='sitesettings',
name='member_scout_url',
field=models.URLField(blank=True, validators=[django.core.validators.URLValidator(schemes=['https'])], verbose_name='Early Access monthly checkout link'),
),
migrations.AddField(
model_name='sitesettings',
name='member_vault_url',
field=models.URLField(blank=True, validators=[django.core.validators.URLValidator(schemes=['https'])], verbose_name='Studio Vault monthly checkout link'),
),
migrations.AddField(
model_name='sitesettings',
name='membership_popup',
field=models.BooleanField(default=False, verbose_name='Offer membership after newsletter signup'),
),
migrations.CreateModel(
name='MemberArtwork',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('order', models.PositiveSmallIntegerField(default=0)),
('art', catalog.models.StudioImageField(upload_to=catalog.models.image_path, validators=[catalog.models.validate_image])),
('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='pages', to='catalog.memberpost')),
],
options={
'ordering': ['order', 'pk'],
},
),
]
@@ -0,0 +1,37 @@
# Generated by Django 5.2.19 on 2026-11-26 11:05
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalog', '0026_member_content'),
]
operations = [
migrations.AlterField(
model_name='chapter',
name='price_usd',
field=models.DecimalField(blank=True, decimal_places=2, help_text='Set at least $0.50 for a Stripe chapter purchase. Leave blank if this chapter is only available to members.', max_digits=7, null=True, validators=[django.core.validators.MinValueValidator(0)], verbose_name='Chapter price (USD)'),
),
migrations.CreateModel(
name='ManagedPage',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=160)),
('map_slot', models.CharField(blank=True, editable=False, max_length=50)),
('slug', models.SlugField(unique=True)),
('body', models.TextField(blank=True)),
('link', models.CharField(blank=True, help_text='Optional local destination, such as /shop/. Leave blank to publish the page body.', max_length=240)),
('menu_key', models.CharField(blank=True, help_text='Optional existing menu key to replace, such as read, blog, or shop.', max_length=32)),
('published', models.BooleanField(default=False)),
('show_in_menu', models.BooleanField(default=False)),
('homepage', models.BooleanField(default=False)),
],
options={
'constraints': [models.UniqueConstraint(condition=models.Q(('homepage', True)), fields=('homepage',), name='slx_single_managed_home')],
},
),
]
@@ -0,0 +1,33 @@
from django.db import migrations
def seed(apps, schema_editor):
Page = apps.get_model('catalog', 'ManagedPage')
rows = [
('solterra-map', 'Explore Sol’Terra', '/map/', ''),
('about', 'Series introduction', '/about/', ''),
('chapters', 'Read', '/chapters/', 'read'),
('blog', 'Blog', '/blog/', 'blog'),
('reviews', 'Reviews', '/reviews/', 'reviews'),
('upcoming', 'Upcoming', '/upcoming/', 'upcoming'),
('live', 'SLX Live', '/live/', 'live'),
('cast', 'Cast', '/cast/', 'cast'),
('world', 'World archive', '/world/', 'world'),
('shop', 'Shop', '/shop/', 'shop'),
('cart', 'Shopping cart', '/shop/cart/', ''),
('newsletter', 'Newsletter', '/newsletter/', ''),
('membership', 'Membership', '/membership/', 'membership'),
('library', 'My library', '/fan/library/', 'library'),
('countdown', 'Release countdown', '/coming-soon/', ''),
('djinnii', 'Djinnii', '/djinnii/', ''),
('community', 'Community', '/community/', 'community'),
('search', 'Search', '/search/', 'search'),
]
for slug, title, path, key in rows:
Page.objects.using(schema_editor.connection.alias).get_or_create(
slug=slug, defaults={'title':title, 'link':path, 'published':True, 'menu_key':key, 'map_slot':slug})
class Migration(migrations.Migration):
dependencies = [('catalog','0027_alter_chapter_price_usd_managedpage')]
operations = [migrations.RunPython(seed, migrations.RunPython.noop)]
+33
View File
@@ -0,0 +1,33 @@
# Generated by Django 5.2.19 on 2026-11-26 11:24
import django.core.validators
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalog', '0028_default_managed_pages'),
]
operations = [
migrations.CreateModel(
name='MapLocation',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=80)),
('key', models.SlugField(unique=True)),
('path', models.CharField(blank=True, help_text='Optional override, e.g. /chapters/9/. Leave blank to follow the selected page.', max_length=240)),
('fallback_path', models.CharField(blank=True, editable=False, max_length=240)),
('x', models.DecimalField(decimal_places=5, max_digits=8, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100)])),
('y', models.DecimalField(decimal_places=5, max_digits=8, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100)])),
('visible', models.BooleanField(default=True)),
('position', models.PositiveIntegerField(default=0)),
('page', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='catalog.managedpage')),
],
options={
'ordering': ['position', 'pk'],
},
),
]
@@ -0,0 +1,21 @@
from django.db import migrations
ROWS = [('about', 'start', '8.88672', '3.41880', 'Series introduction'), ('upcoming', 'upcoming', '55.46875', '6.58120', 'Next releases'), ('cast', 'cast', '66.65039', '17.09402', 'Meet the cast'), ('world', 'world', '88.47656', '26.66667', 'World archive'), ('blog', 'blog', '13.81836', '39.40171', 'Studio blog'), ('chapters', 'chapters', '35.44922', '43.33333', 'Read chapters'), ('reviews', 'reviews', '53.36914', '48.97436', 'Reader reviews'), ('live', 'live', '62.45117', '60.76923', 'SLX Live'), ('membership', 'membership', '41.55273', '67.43590', 'Membership'), ('shop', 'shop', '74.90234', '73.33333', 'Shop'), ('cart', 'cart', '96.53320', '73.58974', 'Shopping cart'), ('newsletter', 'newsletter', '11.37695', '81.11111', 'Newsletter'), ('library', 'library', '15.18555', '84.87179', 'My library'), ('countdown', 'release', '61.13281', '88.88889', 'Release countdown')]
def seed(apps, schema_editor):
Page = apps.get_model('catalog', 'ManagedPage')
Location = apps.get_model('catalog', 'MapLocation')
db = schema_editor.connection.alias
for position, (slot, key, x, y, title) in enumerate(ROWS):
page = Page.objects.using(db).filter(map_slot=slot).first()
fallback = {'cart': '/shop/cart/', 'library': '/fan/library/', 'release': '/coming-soon/'}.get(key, '/' + slot + '/')
Location.objects.using(db).get_or_create(key=key, defaults=dict(
title=title, x=x, y=y, page_id=page.pk if page else None,
fallback_path=fallback, position=position))
class Migration(migrations.Migration):
dependencies = [('catalog', '0029_map_location')]
operations = [migrations.RunPython(seed, migrations.RunPython.noop)]
@@ -0,0 +1,32 @@
# Generated by Django 5.2.19 on 2026-11-26 12:55
import catalog.models
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalog', '0030_seed_map_locations'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.AddField(
model_name='sitesettings',
name='countdown_map_position',
field=models.CharField(choices=[('above', 'Above countdown content'), ('below', 'Below countdown content')], default='below', max_length=6),
),
migrations.CreateModel(
name='CollectorProfile',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('display_name', models.CharField(blank=True, max_length=80)),
('photo', catalog.models.StudioImageField(blank=True, upload_to=catalog.models.image_path, validators=[catalog.models.validate_image])),
('public', models.BooleanField(default=False)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
+23
View File
@@ -0,0 +1,23 @@
# Generated by Django 5.2.19 on 2026-11-26 13:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalog', '0031_sitesettings_countdown_map_position_collectorprofile'),
]
operations = [
migrations.AlterField(
model_name='fanmembership',
name='member_tier',
field=models.PositiveSmallIntegerField(choices=[(1, 'Early Access'), (2, 'Studio Vault'), (3, 'Collector’s Circle')], default=1, verbose_name='Content tier'),
),
migrations.AlterField(
model_name='memberpost',
name='required_tier',
field=models.PositiveSmallIntegerField(choices=[(1, 'Early Access'), (2, 'Studio Vault'), (3, 'Collector’s Circle')], default=1),
),
]
+149 -8
View File
@@ -5,6 +5,7 @@ from django.core.exceptions import ValidationError
from django.core.validators import MaxValueValidator, URLValidator, MinValueValidator, RegexValidator from django.core.validators import MaxValueValidator, URLValidator, MinValueValidator, RegexValidator
from django.db import models from django.db import models
from django.urls import reverse from django.urls import reverse
from django.utils import timezone
from PIL import Image from PIL import Image
from .backgrounds import validate_background_path from .backgrounds import validate_background_path
@@ -119,9 +120,14 @@ class PageSharePreview(models.Model):
class SiteSettings(models.Model): class SiteSettings(models.Model):
countdown_map_position = models.CharField(max_length=6, default='below',
choices=[('above', 'Above countdown content'), ('below', 'Below countdown content')])
name = models.CharField(max_length=100, default='SLUMP X LAND', editable=False) name = models.CharField(max_length=100, default='SLUMP X LAND', editable=False)
site_palette = models.JSONField(default=dict, blank=True) site_palette = models.JSONField(default=dict, blank=True)
hidden_menu = models.JSONField(default=list, blank=True) hidden_menu = models.JSONField(default=list, blank=True)
membership_popup = models.BooleanField('Offer membership after newsletter signup', default=False)
member_scout_url = models.URLField('Early Access monthly checkout link', blank=True, validators=[https_url])
member_vault_url = models.URLField('Studio Vault monthly checkout link', blank=True, validators=[https_url])
support_url = models.URLField('Subscription or support page', blank=True, validators=[https_url], support_url = models.URLField('Subscription or support page', blank=True, validators=[https_url],
help_text='An HTTPS link to your membership or support checkout. Leave blank if you are not accepting signups.') help_text='An HTTPS link to your membership or support checkout. Leave blank if you are not accepting signups.')
caster_threshold = models.DecimalField('Sol-Caster minimum (USD)', max_digits=9, decimal_places=2, caster_threshold = models.DecimalField('Sol-Caster minimum (USD)', max_digits=9, decimal_places=2,
@@ -224,7 +230,7 @@ class Chapter(models.Model):
title = models.CharField(max_length=180) title = models.CharField(max_length=180)
cover = art_field(blank=True) cover = art_field(blank=True)
price_usd = models.DecimalField('Chapter price (USD)', max_digits=7, decimal_places=2, null=True, blank=True, price_usd = models.DecimalField('Chapter price (USD)', max_digits=7, decimal_places=2, null=True, blank=True,
validators=[MinValueValidator(0)], help_text='Leave blank or set to zero for a free chapter.') validators=[MinValueValidator(0)], help_text='Set at least $0.50 for a Stripe chapter purchase. Leave blank if this chapter is only available to members.')
def clean(self): def clean(self):
super().clean() super().clean()
@@ -476,6 +482,9 @@ class BookListing(models.Model):
cover = art_field(verbose_name='Product image', blank=True) cover = art_field(verbose_name='Product image', blank=True)
paypal_url = models.URLField('PayPal Payment Link', blank=True, validators=[validate_book_checkout], paypal_url = models.URLField('PayPal Payment Link', blank=True, validators=[validate_book_checkout],
help_text='Use for a product with no variants. When variants exist, each uses its own link.') help_text='Use for a product with no variants. When variants exist, each uses its own link.')
price_usd = models.DecimalField('Stripe price (USD)', max_digits=8, decimal_places=2, null=True, blank=True,
validators=[MinValueValidator(Decimal('0.50'))], help_text='Charged by Stripe when this product has no variants.')
ships = models.BooleanField('Ship this product', default=True, help_text='Collect a shipping address at Stripe Checkout.')
visible = models.BooleanField(default=False) visible = models.BooleanField(default=False)
class Meta: class Meta:
@@ -507,10 +516,10 @@ class ProductVariant(models.Model):
option = models.CharField('Edition / size / color', max_length=90, blank=True, option = models.CharField('Edition / size / color', max_length=90, blank=True,
help_text='Optional. For example: XL / Black, Signed copy, or Blue pressing.') help_text='Optional. For example: XL / Black, Signed copy, or Blue pressing.')
art = art_field(verbose_name='Variant image', blank=True, help_text='Leave blank to use the main product image.') art = art_field(verbose_name='Variant image', blank=True, help_text='Leave blank to use the main product image.')
price_usd = models.DecimalField('Display price (USD)', max_digits=8, decimal_places=2, null=True, blank=True, price_usd = models.DecimalField('Price (USD)', max_digits=8, decimal_places=2, null=True, blank=True,
validators=[MinValueValidator(Decimal('0.01'))], validators=[MinValueValidator(Decimal('0.01'))],
help_text='Optional. Enter the same price you set in PayPal; this field does not change the checkout price.') help_text='Charged by Stripe. If using a PayPal link, set the PayPal price separately.')
paypal_url = models.URLField('PayPal Payment Link', validators=[validate_book_checkout]) paypal_url = models.URLField('PayPal Payment Link', blank=True, validators=[validate_book_checkout])
visible = models.BooleanField(default=True) visible = models.BooleanField(default=True)
order = models.PositiveSmallIntegerField('Display order', default=0, help_text='Lower numbers appear first.') order = models.PositiveSmallIntegerField('Display order', default=0, help_text='Lower numbers appear first.')
@@ -522,6 +531,29 @@ class ProductVariant(models.Model):
return f'{label} · {self.option}' if self.option else label return f'{label} · {self.option}' if self.option else label
class ShopOrder(models.Model):
class Status(models.TextChoices):
OPEN = 'open', 'Awaiting payment'
PAID = 'paid', 'Paid'
EXPIRED = 'expired', 'Expired'
FAILED = 'failed', 'Checkout unavailable'
reference = models.UUIDField(default=uuid4, unique=True, editable=False)
item = models.CharField(max_length=320)
amount_cents = models.PositiveIntegerField()
livemode = models.BooleanField()
status = models.CharField(max_length=10, choices=Status, default=Status.OPEN, db_index=True)
stripe_session = models.CharField(max_length=255, unique=True, null=True, blank=True)
payment_intent = models.CharField(max_length=255, blank=True)
email = models.EmailField(blank=True)
created_at = models.DateTimeField(auto_now_add=True)
paid_at = models.DateTimeField(null=True, blank=True)
fulfilled = models.BooleanField(default=False)
class Meta:
ordering = ['-created_at']
class ChapterPurchase(models.Model): class ChapterPurchase(models.Model):
user = models.ForeignKey('auth.User', on_delete=models.PROTECT) user = models.ForeignKey('auth.User', on_delete=models.PROTECT)
chapter = models.ForeignKey(Chapter, on_delete=models.PROTECT, related_name='purchases') chapter = models.ForeignKey(Chapter, on_delete=models.PROTECT, related_name='purchases')
@@ -560,6 +592,7 @@ class StreamComment(models.Model):
class FanMembership(models.Model): class FanMembership(models.Model):
user = models.OneToOneField('auth.User', on_delete=models.CASCADE, related_name='slx_membership') user = models.OneToOneField('auth.User', on_delete=models.CASCADE, related_name='slx_membership')
subscriber_until = models.DateTimeField('Subscription active through', null=True, blank=True) subscriber_until = models.DateTimeField('Subscription active through', null=True, blank=True)
member_tier = models.PositiveSmallIntegerField('Content tier', choices=[(1, 'Early Access'), (2, 'Studio Vault'), (3, 'Collector’s Circle')], default=1)
sol_seat = models.BooleanField('Assign Sol Seat', default=False) sol_seat = models.BooleanField('Assign Sol Seat', default=False)
class Meta: class Meta:
@@ -569,6 +602,30 @@ class FanMembership(models.Model):
return str(self.user) return str(self.user)
class MemberPost(models.Model):
title = models.CharField(max_length=160)
body = models.TextField(blank=True)
kind = models.CharField(max_length=12, choices=[('note','Creator note'),('early','Early chapter'),('draft','Draft pages')], default='note')
required_tier = models.PositiveSmallIntegerField(choices=[(1,'Early Access'),(2,'Studio Vault'),(3,'Collector’s Circle')],default=1)
published = models.BooleanField(default=False)
publish_at = models.DateTimeField(default=timezone.now)
class Meta:
ordering = ['-publish_at', '-pk']
def __str__(self):
return self.title
class MemberArtwork(models.Model):
post = models.ForeignKey(MemberPost, related_name='pages', on_delete=models.CASCADE)
order = models.PositiveSmallIntegerField(default=0)
art = art_field()
class Meta:
ordering = ['order', 'pk']
class SupportCredit(models.Model): class SupportCredit(models.Model):
user = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='slx_support_credits') user = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='slx_support_credits')
reference = models.CharField('Unique receipt or credit reference', max_length=140, unique=True) reference = models.CharField('Unique receipt or credit reference', max_length=140, unique=True)
@@ -590,14 +647,27 @@ class TrafficDaily(models.Model):
target_id = models.PositiveBigIntegerField(default=0) target_id = models.PositiveBigIntegerField(default=0)
route = models.CharField(max_length=64) route = models.CharField(max_length=64)
country = models.CharField(max_length=2, blank=True, default='') country = models.CharField(max_length=2, blank=True, default='')
region = models.CharField(max_length=120, blank=True, default='')
city = models.CharField(max_length=120, blank=True, default='')
source = models.CharField(max_length=255, blank=True, default='') source = models.CharField(max_length=255, blank=True, default='')
views = models.PositiveBigIntegerField(default=1) views = models.PositiveBigIntegerField(default=1)
class Meta: class Meta:
constraints = [models.UniqueConstraint(fields=['day', 'kind', 'target_id', 'route', 'country', 'source'], constraints = [
name='slx_traffic_daily_key')] models.UniqueConstraint(
indexes = [models.Index(fields=['kind', 'target_id'], name='slx_traffic_item_idx')] fields=[
'day', 'kind', 'target_id', 'route',
'country', 'region', 'city', 'source'
],
name='slx_traffic_daily_key'
)
]
indexes = [
models.Index(
fields=['kind', 'target_id'],
name='slx_traffic_item_idx'
)
]
class AIChapterReview(models.Model): class AIChapterReview(models.Model):
chapter = models.OneToOneField(Chapter, on_delete=models.CASCADE, related_name='ai_editorial_review') chapter = models.OneToOneField(Chapter, on_delete=models.CASCADE, related_name='ai_editorial_review')
@@ -675,3 +745,74 @@ class NewsletterDelivery(models.Model):
class Meta: class Meta:
constraints = [models.UniqueConstraint(fields=['campaign', 'subscriber'], name='slx_unique_newsletter_delivery')] constraints = [models.UniqueConstraint(fields=['campaign', 'subscriber'], name='slx_unique_newsletter_delivery')]
class ManagedPage(models.Model):
title = models.CharField(max_length=160)
slug = models.SlugField(unique=True)
body = models.TextField(blank=True)
link = models.CharField(max_length=240, blank=True, help_text='Optional local destination, such as /shop/. Leave blank to publish the page body.')
map_slot = models.CharField(max_length=50, blank=True, editable=False)
menu_key = models.CharField(max_length=32, blank=True, help_text='Optional existing menu key to replace, such as read, blog, or shop.')
published = models.BooleanField(default=False)
show_in_menu = models.BooleanField(default=False)
homepage = models.BooleanField(default=False)
class Meta:
constraints = [models.UniqueConstraint(fields=['homepage'], condition=models.Q(homepage=True), name='slx_single_managed_home')]
def clean(self):
from urllib.parse import urlsplit
super().clean()
if self.link:
try:
parts = urlsplit(self.link)
except ValueError as exc:
raise ValidationError({'link': 'Enter a valid local path.'}) from exc
if not self.link.startswith('/') or self.link.startswith('//') or parts.netloc or (parts.path == '/' or parts.path.startswith('/pages/')) or '\\' in self.link or any(ord(c)<32 for c in self.link):
raise ValidationError({'link': 'Enter a local path other than the homepage, such as /shop/.'})
if self.homepage and not self.published:
raise ValidationError({'homepage': 'Publish this page before setting it as the homepage.'})
def get_absolute_url(self):
from django.urls import reverse
return reverse('managed-page', args=[self.slug])
def __str__(self):
return self.title
class MapLocation(models.Model):
title = models.CharField(max_length=80)
key = models.SlugField(max_length=50, unique=True)
path = models.CharField(max_length=240, blank=True, help_text='Optional override, e.g. /chapters/9/. Leave blank to follow the selected page.')
page = models.ForeignKey(ManagedPage, null=True, blank=True, on_delete=models.SET_NULL)
fallback_path = models.CharField(max_length=240, blank=True, editable=False)
x = models.DecimalField(max_digits=8, decimal_places=5, validators=[MinValueValidator(0), MaxValueValidator(100)])
y = models.DecimalField(max_digits=8, decimal_places=5, validators=[MinValueValidator(0), MaxValueValidator(100)])
visible = models.BooleanField(default=True)
position = models.PositiveIntegerField(default=0)
class Meta:
ordering = ['position', 'pk']
def clean(self):
super().clean()
if self.path and (not self.path.startswith('/') or self.path.startswith('//') or
'\\' in self.path or any(c.isspace() or ord(c) < 32 for c in self.path)):
raise ValidationError({'path': 'Enter an internal path starting with one slash.'})
if self.visible and not (self.path or self.page_id or self.fallback_path):
raise ValidationError({'path': 'Choose a page or enter a path.'})
def destination(self):
return self.path or (self.page.get_absolute_url() if self.page_id and self.page.published else self.fallback_path)
def __str__(self):
return self.title
class CollectorProfile(models.Model):
user = models.OneToOneField('auth.User', on_delete=models.CASCADE)
display_name = models.CharField(max_length=80, blank=True)
photo = art_field(blank=True)
public = models.BooleanField(default=False)
+3 -1
View File
@@ -231,4 +231,6 @@ def books(request):
product.store_variants = [v for v in variants if v.visible] product.store_variants = [v for v in variants if v.visible]
product.legacy_checkout = product.paypal_url if not variants else '' product.legacy_checkout = product.paypal_url if not variants else ''
groups[product.category]['products'].append(product) groups[product.category]['products'].append(product)
return render(request, 'books.html', {'product_groups': [g for g in groups.values() if g['products']]}) from .shop_stripe import ready
return render(request, 'books.html', {'product_groups': [g for g in groups.values() if g['products']],
'stripe_shop_ready': ready()})
+48 -9
View File
@@ -10,25 +10,64 @@ from .models import Chapter, Entry, TrafficDaily
def traffic_report(request): def traffic_report(request):
days = request.GET.get('days', '30') days = request.GET.get('days', '30')
days = int(days) if days in ('7', '30', '90') else 30 days = int(days) if days in ('7', '30', '90') else 30
kind = request.GET.get('kind', 'all') kind = request.GET.get('kind', 'all')
if kind not in ('all', 'chapter', 'blog'): if kind not in ('all', 'chapter', 'blog'):
kind = 'all' kind = 'all'
qs = TrafficDaily.objects.filter(day__gte=timezone.localdate()-timedelta(days=days-1))
qs = TrafficDaily.objects.filter(
day__gte=timezone.localdate() - timedelta(days=days - 1)
)
if kind != 'all': if kind != 'all':
qs = qs.filter(kind=kind) qs = qs.filter(kind=kind)
def grouped(*fields): def grouped(*fields):
return qs.values(*fields).annotate(views=Sum('views')).order_by('-views', *fields) return qs.values(*fields).annotate(
views=Sum('views')
).order_by('-views', *fields)
counts = {row['kind']: row['views'] for row in grouped('kind')} counts = {row['kind']: row['views'] for row in grouped('kind')}
countries = list(grouped('country')) countries = list(grouped('country'))
regions = list(grouped('country', 'region')[:100])
cities = list(grouped('country', 'region', 'city')[:100])
sources = grouped('source')[:30] sources = grouped('source')[:30]
series = list(grouped('day').order_by('day')) series = list(grouped('day').order_by('day'))
top = list(qs.exclude(target_id=0).values('kind','target_id').annotate(views=Sum('views')).order_by('-views','target_id')[:25])
chapters = Chapter.objects.in_bulk(row['target_id'] for row in top if row['kind'] == 'chapter') top = list(
posts = Entry.objects.in_bulk(row['target_id'] for row in top if row['kind'] == 'blog') qs.exclude(target_id=0)
.values('kind', 'target_id')
.annotate(views=Sum('views'))
.order_by('-views', 'target_id')[:25]
)
chapters = Chapter.objects.in_bulk(
row['target_id'] for row in top if row['kind'] == 'chapter'
)
posts = Entry.objects.in_bulk(
row['target_id'] for row in top if row['kind'] == 'blog'
)
for row in top: for row in top:
obj = (chapters if row['kind'] == 'chapter' else posts).get(row['target_id']) obj = (
chapters if row['kind'] == 'chapter' else posts
).get(row['target_id'])
row['title'] = str(obj) if obj else 'Removed content' row['title'] = str(obj) if obj else 'Removed content'
return {'days': days, 'kind': kind, 'total': sum(counts.values()), 'chapters': counts.get('chapter', 0),
'blogs': counts.get('blog', 0), 'countries': countries, 'sources': sources, 'top': top, 'series': series, return {
'analytics_enabled': settings.SLX_ANALYTICS, 'geo_configured': bool(settings.SLX_GEOIP_DB)} 'days': days,
'kind': kind,
'total': sum(counts.values()),
'chapters': counts.get('chapter', 0),
'blogs': counts.get('blog', 0),
'countries': countries,
'regions': regions,
'cities': cities,
'sources': sources,
'top': top,
'series': series,
'analytics_enabled': settings.SLX_ANALYTICS,
'geo_configured': bool(settings.SLX_GEOIP_DB),
}
+191
View File
@@ -0,0 +1,191 @@
"""Hosted Stripe checkout for Studio shop orders."""
import hashlib
import hmac
import json
import re
import time
from decimal import Decimal
from urllib.parse import urlencode, urlsplit
from uuid import UUID
from urllib.request import HTTPRedirectHandler, Request, build_opener
from urllib.error import URLError
from django.conf import settings
from django.db import transaction
from django.http import Http404, HttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.utils import timezone
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST, require_safe
from .models import BookListing, ProductVariant, ShopOrder
class CheckoutError(Exception):
pass
class NoRedirect(HTTPRedirectHandler):
def redirect_request(self, *args, **kwargs):
return None
def origin():
try:
url = urlsplit(settings.SLX_STRIPE_ORIGIN)
if (url.scheme == 'https' and url.hostname in settings.ALLOWED_HOSTS and url.netloc == url.hostname
and url.path in ('', '/') and not url.query and not url.fragment):
return f'https://{url.netloc}'
except ValueError:
pass
return ''
def live_mode():
return settings.SLX_STRIPE_SECRET_KEY.startswith(('sk_live_', 'rk_live_'))
def ready():
return bool(origin() and settings.SLX_STRIPE_WEBHOOK_SECRET.startswith('whsec_') and
settings.SLX_STRIPE_SECRET_KEY.startswith(('sk_test_', 'sk_live_', 'rk_test_', 'rk_live_')))
def valid_price(price):
return price is not None and price >= Decimal('0.50')
def request_session(order, collect_shipping):
params = {
'mode': 'payment', 'payment_method_types[0]': 'card',
'success_url': origin() + reverse('shop-stripe-receipt', args=[order.reference]),
'cancel_url': origin() + reverse('books'),
'client_reference_id': str(order.reference),
'metadata[slx_shop_order]': str(order.reference),
'line_items[0][quantity]': 1,
'line_items[0][price_data][currency]': 'usd',
'line_items[0][price_data][unit_amount]': order.amount_cents,
'line_items[0][price_data][product_data][name]': order.item,
}
if collect_shipping:
countries = [c.strip().upper() for c in settings.SLX_STRIPE_SHIP_COUNTRIES if c.strip()]
if not countries or not all(re.fullmatch(r'[A-Z]{2}', country) for country in countries):
raise CheckoutError
for i, code in enumerate(countries):
params[f'shipping_address_collection[allowed_countries][{i}]'] = code
request = Request('https://api.stripe.com/v1/checkout/sessions', data=urlencode(params).encode(),
headers={'Authorization': 'Bearer ' + settings.SLX_STRIPE_SECRET_KEY,
'Idempotency-Key': str(order.reference),
'Content-Type': 'application/x-www-form-urlencoded'})
try:
with build_opener(NoRedirect()).open(request, timeout=8) as response:
data = json.load(response)
session = data['id']
url = urlsplit(data['url'])
if not re.fullmatch(r'cs_(test|live)_[A-Za-z0-9_]{1,200}', session):
raise CheckoutError
if (data.get('livemode') is not order.livemode or url.scheme != 'https'
or url.netloc != 'checkout.stripe.com' or not url.path.startswith('/c/')):
raise CheckoutError
return session, data['url']
except (URLError, OSError, ValueError, KeyError, TypeError, AttributeError) as exc:
raise CheckoutError from exc
@never_cache
@require_POST
def checkout(request, product_id, variant_id):
if not ready():
return render(request, 'shop-order.html', {'unavailable': True}, status=503)
product = get_object_or_404(BookListing, pk=product_id, visible=True)
if variant_id:
variant = get_object_or_404(ProductVariant, pk=variant_id, product=product, visible=True)
else:
if product.variants.exists():
raise Http404
variant = None
price = variant.price_usd if variant else product.price_usd
if not valid_price(price):
raise Http404
item = f'{product.title} · {variant}' if variant else product.title
order = ShopOrder.objects.create(item=item, amount_cents=int(price * 100), livemode=live_mode())
try:
session, url = request_session(order, product.ships and not (variant and variant.format == ProductVariant.Format.DIGITAL))
except CheckoutError:
ShopOrder.objects.filter(pk=order.pk, status=ShopOrder.Status.OPEN).update(status=ShopOrder.Status.FAILED)
return render(request, 'shop-order.html', {'unavailable': True}, status=502)
ShopOrder.objects.filter(pk=order.pk, stripe_session__isnull=True).update(stripe_session=session)
return redirect(url)
def valid_signature(body, header):
parts = {}
for value in header.split(','):
key, sep, val = value.partition('=')
if sep:
parts.setdefault(key, []).append(val)
try:
ts, = parts['t']
if not ts.isascii() or not ts.isdecimal() or len(ts) > 12 or abs(time.time() - int(ts)) > 300:
return False
except (KeyError, ValueError):
return False
expected = hmac.new(settings.SLX_STRIPE_WEBHOOK_SECRET.encode(),
ts.encode() + b'.' + body, hashlib.sha256).hexdigest()
return any(v.isascii() and hmac.compare_digest(expected, v) for v in parts.get('v1', []))
@csrf_exempt
@require_POST
def webhook(request):
if not settings.SLX_STRIPE_WEBHOOK_SECRET.startswith('whsec_'):
return HttpResponse(status=503)
body = request.body
if len(body) > 1024 * 1024 or not valid_signature(body, request.headers.get('Stripe-Signature', '')):
return HttpResponse(status=400)
try:
event = json.loads(body)
kind = event['type']
if kind not in ('checkout.session.completed', 'checkout.session.expired', 'checkout.session.async_payment_succeeded'):
return HttpResponse(status=200)
session = event['data']['object']
metadata = session.get('metadata') or {}
reference = metadata.get('slx_shop_order')
if not reference:
return HttpResponse(status=200)
sid = session['id']
if (not re.fullmatch(r'cs_(test|live)_[A-Za-z0-9_]{1,200}', sid)
or session.get('client_reference_id') != reference or session.get('mode') != 'payment'):
return HttpResponse(status=400)
reference = UUID(reference)
except (ValueError, KeyError, TypeError, AttributeError):
return HttpResponse(status=400)
with transaction.atomic():
order = ShopOrder.objects.select_for_update().filter(reference=reference).first()
if not order:
return HttpResponse(status=200)
if (event.get('livemode') is not order.livemode or session.get('livemode') is not order.livemode
or not sid.startswith('cs_live_' if order.livemode else 'cs_test_')
or (order.stripe_session and order.stripe_session != sid)
or session.get('currency') != 'usd' or session.get('amount_total') != order.amount_cents):
return HttpResponse(status=400)
if order.status != ShopOrder.Status.PAID:
if kind == 'checkout.session.expired':
order.status = ShopOrder.Status.EXPIRED
elif session.get('payment_status') == 'paid':
order.status = ShopOrder.Status.PAID
order.paid_at = timezone.now()
order.payment_intent = str(session.get('payment_intent') or '')[:255]
details = session.get('customer_details')
order.email = str((details.get('email') if isinstance(details, dict) else '') or '')[:254]
order.stripe_session = sid
order.save(update_fields=['status', 'paid_at', 'payment_intent', 'email', 'stripe_session'])
return HttpResponse(status=200)
@never_cache
@require_safe
def receipt(request, reference):
order = get_object_or_404(ShopOrder, reference=reference)
return render(request, 'shop-order.html', {'paid': order.status == ShopOrder.Status.PAID})
+22
View File
@@ -0,0 +1,22 @@
"""Reusable A–Z spelling in the Djinn-Sol alphabet."""
from string import ascii_lowercase
from django import template
register = template.Library()
@register.inclusion_tag("djinn-sol-glyphs.html")
def djinn_sol(text):
return {
"words": [
[f"djinn-sol/{letter}.png" for letter in word if letter in ascii_lowercase]
for word in str(text).lower().split()
]
}
@register.simple_tag(takes_context=True)
def map_destination(context, slug, default_url):
page = context.get('map_destinations', {}).get(slug)
return page.get_absolute_url() if page else default_url
+47 -9
View File
@@ -45,20 +45,43 @@ def geo_reader(path):
except maxminddb.InvalidDatabaseError as exc: except maxminddb.InvalidDatabaseError as exc:
raise ValueError('Invalid country database') from exc raise ValueError('Invalid country database') from exc
def location_for(request):
empty = {'country': '', 'region': '', 'city': ''}
def country_for(request):
if not settings.SLX_GEOIP_DB: if not settings.SLX_GEOIP_DB:
return '' return empty
header = 'HTTP_X_SLX_CLIENT_IP' if settings.SLX_TRUST_CADDY_IP else 'REMOTE_ADDR'
header = (
'HTTP_X_SLX_CLIENT_IP'
if settings.SLX_TRUST_CADDY_IP
else 'REMOTE_ADDR'
)
try: try:
ip = ipaddress.ip_address(request.META.get(header, '')) ip = ipaddress.ip_address(request.META.get(header, ''))
if not ip.is_global: if not ip.is_global:
return '' return empty
row = geo_reader(settings.SLX_GEOIP_DB).get(str(ip)) or {} row = geo_reader(settings.SLX_GEOIP_DB).get(str(ip)) or {}
code = row.get('country', {}).get('iso_code', '')
return code if re.fullmatch(r'[A-Z]{2}', code) else '' country = row.get('country', {}).get('iso_code', '')
subdivisions = row.get('subdivisions') or []
region = ''
if subdivisions:
region = subdivisions[0].get('names', {}).get('en', '')
city = row.get('city', {}).get('names', {}).get('en', '')
return {
'country': country if re.fullmatch(r'[A-Z]{2}', country) else '',
'region': region[:120],
'city': city[:120],
}
except (ValueError, OSError, ImportError, RuntimeError): except (ValueError, OSError, ImportError, RuntimeError):
return '' return empty
def view_total(kind, ident): def view_total(kind, ident):
@@ -86,12 +109,27 @@ class TrafficMiddleware:
or any('prefetch' in request.META.get(header, '').lower() for header in ('HTTP_SEC_PURPOSE', 'HTTP_PURPOSE')) or any('prefetch' in request.META.get(header, '').lower() for header in ('HTTP_SEC_PURPOSE', 'HTTP_PURPOSE'))
or not request.META.get('HTTP_USER_AGENT') or BOT.search(request.META['HTTP_USER_AGENT'])): or not request.META.get('HTTP_USER_AGENT') or BOT.search(request.META['HTTP_USER_AGENT'])):
return response return response
kind, target = getattr(request, 'slx_view_target', ('site', 0)) kind, target = getattr(request, 'slx_view_target', ('site', 0))
try: try:
row, created = TrafficDaily.objects.get_or_create(day=timezone.localdate(), kind=kind, target_id=target, location = location_for(request)
route=match.url_name, country=country_for(request), source=source_origin(request))
row, created = TrafficDaily.objects.get_or_create(
day=timezone.localdate(),
kind=kind,
target_id=target,
route=match.url_name,
country=location['country'],
region=location['region'],
city=location['city'],
source=source_origin(request),
)
if not created: if not created:
TrafficDaily.objects.filter(pk=row.pk).update(views=F('views') + 1) TrafficDaily.objects.filter(pk=row.pk).update(views=F('views') + 1)
except DatabaseError: except DatabaseError:
logger.warning('SLX traffic could not be recorded.') logger.warning('SLX traffic could not be recorded.')
return response return response
+121 -40
View File
@@ -1,5 +1,6 @@
from math import floor from math import floor
from urllib.parse import urlencode from urllib.parse import urlencode
from django.conf import settings as config
from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator from django.core.paginator import Paginator
from django.db import connection from django.db import connection
@@ -9,9 +10,10 @@ from django.http import FileResponse, Http404, JsonResponse
from django.shortcuts import get_object_or_404, redirect, render from django.shortcuts import get_object_or_404, redirect, render
from django.utils import timezone from django.utils import timezone
from django.views.decorators.cache import never_cache from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_safe from django.views.decorators.http import require_POST, require_safe
from .chapter_access import full_chapters, rolling_chapter_ids
from PIL import Image from PIL import Image
from .models import SiteSettings, Chapter, Page, Entry, BookListing, StreamComment, DiscussionComment, PageBackground, FloatingArtwork, ProductVariant, PageSharePreview from .models import SiteSettings, Chapter, Page, Entry, BookListing, StreamComment, DiscussionComment, PageBackground, FloatingArtwork, ProductVariant, PageSharePreview, MemberArtwork
from .fans import engagement, live from .fans import engagement, live
from .reader import reading_frames from .reader import reading_frames
from .reactions import reaction_group, reaction_groups from .reactions import reaction_group, reaction_groups
@@ -47,7 +49,13 @@ def search(request):
chapter_filter = Q(title__icontains=query) | Q(summary__icontains=query) chapter_filter = Q(title__icontains=query) | Q(summary__icontains=query)
if query.lstrip('#').isascii() and query.lstrip('#').isdigit() and len(query.lstrip('#')) < 10: if query.lstrip('#').isascii() and query.lstrip('#').isdigit() and len(query.lstrip('#')) < 10:
chapter_filter |= Q(number=int(query.lstrip('#'))) chapter_filter |= Q(number=int(query.lstrip('#')))
chapters = live(Chapter).filter(chapter_filter)[:20] chapters = live(Chapter).filter(chapter_filter).annotate(
first_page_art=Subquery(Page.objects.filter(chapter_id=OuterRef('pk')).order_by('number').values('art')[:1]))[:20]
page_storage = Page._meta.get_field("art").storage
for chapter in chapters:
chapter.search_cover = chapter.cover.url if chapter.cover else (
page_storage.url(chapter.first_page_art) if chapter.first_upload_is_cover and chapter.first_page_art
and not chapter.publisher_url else '')
posts = live(Entry).filter(Q(title__icontains=query) | Q(summary__icontains=query) | posts = live(Entry).filter(Q(title__icontains=query) | Q(summary__icontains=query) |
Q(category__icontains=query))[:20] Q(category__icontains=query))[:20]
return render(request, 'search.html', {'query': query, 'chapters': chapters, 'items': posts}) return render(request, 'search.html', {'query': query, 'chapters': chapters, 'items': posts})
@@ -91,7 +99,8 @@ def stream(request):
@require_safe @require_safe
def community(request): def community(request):
return render(request, 'community.html') from .collectors import recognized_collectors
return render(request, 'community.html', {'collectors': recognized_collectors()})
@require_safe @require_safe
@@ -135,50 +144,55 @@ def countdown_progress(site, now):
@require_safe @require_safe
def home(request): def home(request):
settings = settings_row() from .models import ManagedPage
now = timezone.now() page = ManagedPage.objects.filter(published=True, homepage=True).first()
homepage_countdown = ( return render_managed_page(request, page) if page else map_landing(request)
settings.homepage_countdown_enabled
and settings.homepage_countdown_at
and settings.homepage_countdown_at > now @require_safe
) def map_landing(request):
countdown_context = { from .models import MapLocation
'countdown_now': now,
'release_progress': countdown_progress(settings, now) if homepage_countdown else None, locations = []
'countdown_chapters': countdown_chapter_shelf(request.user, now) if homepage_countdown else [], for marker in MapLocation.objects.filter(visible=True).select_related('page'):
'countdown_social_color': settings.homepage_social_color if HEX_COLOR.fullmatch(settings.homepage_social_color) else '#ffdd00', if url := marker.destination():
} locations.append({'title': marker.title, 'key': marker.key, 'url': url,
if homepage_countdown and settings.homepage_countdown_landing and settings.homepage_countdown_cover: 'x': format(marker.x, 'f'), 'y': format(marker.y, 'f')})
tint = settings.homepage_countdown_tint context = countdown_splash_context(request)
return render(request, 'countdown-landing.html', { if context:
**countdown_context, 'settings': settings, return render(request, 'countdown-landing.html', {**context, 'map_locations': locations, 'with_world_map': True})
'countdown_tint': tint if HEX_COLOR.fullmatch(tint) else '#0c1020', return render(request, 'home.html', {'map_locations': locations})
'countdown_tint_strength': min(100, settings.homepage_countdown_tint_strength),
})
return render(request, 'home.html', { def render_managed_page(request, page):
**countdown_context, 'homepage_countdown': homepage_countdown, if page.link and page.link.split('?', 1)[0].split('#', 1)[0] != request.path:
'chapters': with_views(live(Chapter), 'chapter')[:6], return redirect(page.link)
'upcoming': upcoming_chapters()[:3], return render(request, 'managed-page.html', {'page': page})
'recent_reviews': published_reviews()[:5],
'news': with_views(live(Entry).filter(kind=Entry.Kind.NEWS), 'blog')[:6],
'cast': live(Entry).filter(kind=Entry.Kind.CAST)[:3], @require_safe
'world': live(Entry).filter(kind=Entry.Kind.WORLD)[:3], def managed_page(request, slug):
}) from .models import ManagedPage
return render_managed_page(request, get_object_or_404(ManagedPage, slug=slug, published=True))
@require_safe @require_safe
def chapters(request): def chapters(request):
return render(request, 'chapters.html', {'chapters': with_views(live(Chapter), 'chapter')}) return render(request, 'chapters.html', {'chapters': with_views(live(Chapter), 'chapter'), 'rolling_free_ids': set(rolling_chapter_ids().values_list('pk', flat=True)), 'show_archive_status': True})
@require_safe @require_safe
@never_cache @never_cache
def chapter(request, number): def chapter(request, number):
item = get_object_or_404(live(Chapter), number=number) item = get_object_or_404(live(Chapter), number=number)
if not full_chapters(request.user).filter(pk=item.pk).exists():
from shop.payments import stripe_ready
return render(request, 'chapter-locked.html', {
'chapter': item, 'stripe_enabled': stripe_ready() and bool(config.SLX_COMMERCE_STRIPE_WEBHOOK_SECRET),
})
if item.publisher_url: if item.publisher_url:
return redirect(item.publisher_url) return redirect(item.publisher_url)
if item.price_usd and not entitled_chapters(request.user).filter(pk=item.pk).exists():
return render(request, 'chapter-locked.html', {'chapter': item, 'paypal_ready': checkout_ready()})
request.slx_view_target = ('chapter', item.pk) request.slx_view_target = ('chapter', item.pk)
item.public_views = view_total('chapter', item.pk) item.public_views = view_total('chapter', item.pk)
pages = list(item.pages.all()) pages = list(item.pages.all())
@@ -187,7 +201,7 @@ def chapter(request, number):
page.reactions = groups[page.pk] page.reactions = groups[page.pk]
next_chapter = live(Chapter).filter(number__gt=number).order_by('number').first() next_chapter = live(Chapter).filter(number__gt=number).order_by('number').first()
next_readable = bool(next_chapter and ( next_readable = bool(next_chapter and (
not next_chapter.price_usd or entitled_chapters(request.user).filter(pk=next_chapter.pk).exists())) full_chapters(request.user).filter(pk=next_chapter.pk).exists()))
next_cover = None next_cover = None
if next_readable: if next_readable:
next_cover = next_chapter.cover next_cover = next_chapter.cover
@@ -195,7 +209,11 @@ def chapter(request, number):
first_page = next_chapter.pages.first() first_page = next_chapter.pages.first()
next_cover = first_page.art if first_page else None next_cover = first_page.art if first_page else None
previous_chapter = live(Chapter).filter(number__lt=number).first() previous_chapter = live(Chapter).filter(number__lt=number).first()
return render(request, 'chapter.html', {'chapter': item, 'frames': reading_frames(item, pages), from shop.models import Product
from shop.payments import stripe_ready
physical = Product.objects.filter(active=True, kind=Product.Kind.PHYSICAL, sample_chapter=item).first()
return render(request, 'chapter.html', {'chapter': item,
'physical_edition': physical, 'stripe_enabled': stripe_ready() and bool(config.SLX_COMMERCE_STRIPE_WEBHOOK_SECRET), 'frames': reading_frames(item, pages),
'next_chapter': next_chapter, 'next_readable': next_readable, 'next_cover': next_cover, 'next_chapter': next_chapter, 'next_readable': next_readable, 'next_cover': next_cover,
'previous_chapter': previous_chapter, 'previous_chapter': previous_chapter,
**chapter_fan_context(request, item)}) **chapter_fan_context(request, item)})
@@ -227,16 +245,43 @@ def entry(request, kind, slug):
'share_image': request.build_absolute_uri(item.art.url) if item.art else ''}) 'share_image': request.build_absolute_uri(item.art.url) if item.art else ''})
def countdown_splash_context(request):
settings = settings_row()
now = timezone.now()
if (settings.homepage_countdown_enabled and settings.homepage_countdown_landing
and settings.homepage_countdown_cover and settings.homepage_countdown_at
and settings.homepage_countdown_at > now):
tint = settings.homepage_countdown_tint
social = settings.homepage_social_color
return {
'settings': settings,
'countdown_now': now,
'release_progress': countdown_progress(settings, now),
'countdown_chapters': countdown_chapter_shelf(request.user, now),
'countdown_social_color': social if HEX_COLOR.fullmatch(social) else '#ffdd00',
'countdown_tint': tint if HEX_COLOR.fullmatch(tint) else '#0c1020',
'countdown_tint_strength': min(100, settings.homepage_countdown_tint_strength),
}
return None
@require_safe @require_safe
def coming_soon(request): def coming_soon(request):
return render(request, 'soon.html') context = countdown_splash_context(request)
return render(request, 'countdown-landing.html', context) if context else render(request, 'soon.html')
@require_safe @require_safe
def image(request, key): def image(request, key):
# Chapter pages respect visibility and schedule even if a file URL is shared. # Chapter pages respect visibility and schedule even if a file URL is shared.
name = f'images/{key}' name = f'images/{key}'
from .membership import accessible_posts
from .collectors import recognized_collectors
from .models import CollectorProfile
sources = ( sources = (
(recognized_collectors(), 'photo'),
(CollectorProfile.objects.filter(user_id=request.user.pk), 'photo'),
(MemberArtwork.objects.filter(post__in=accessible_posts(request.user)), 'art'),
(PageSharePreview.objects.all(), 'art'), (PageSharePreview.objects.all(), 'art'),
(PageBackground.objects.filter(enabled=True), 'art'), (PageBackground.objects.filter(enabled=True), 'art'),
(FloatingArtwork.objects.filter(enabled=True), 'art'), (FloatingArtwork.objects.filter(enabled=True), 'art'),
@@ -255,7 +300,7 @@ def image(request, key):
(scheduled_chapters() if settings_row().show_chapter_countdowns else Chapter.objects.none(), 'cover'), (scheduled_chapters() if settings_row().show_chapter_countdowns else Chapter.objects.none(), 'cover'),
(live(Chapter), 'cover'), (live(Chapter), 'cover'),
(live(Entry), 'art'), (live(Entry), 'art'),
(Page.objects.filter(chapter__in=entitled_chapters(request.user), chapter__publisher_url=''), 'art'), (Page.objects.filter(chapter__in=full_chapters(request.user), chapter__publisher_url=''), 'art'),
) )
if can_watch_stream(request.user) or (request.user.is_staff and request.user.has_perm('catalog.view_sitesettings')): if can_watch_stream(request.user) or (request.user.is_staff and request.user.has_perm('catalog.view_sitesettings')):
sources += ((SiteSettings.objects.filter(pk=1), 'stream_cover'),) sources += ((SiteSettings.objects.filter(pk=1), 'stream_cover'),)
@@ -264,6 +309,8 @@ def image(request, key):
model = qs.model model = qs.model
if any(request.user.has_perm(f'catalog.{action}_{model._meta.model_name}') for action in ('view', 'change')): if any(request.user.has_perm(f'catalog.{action}_{model._meta.model_name}') for action in ('view', 'change')):
qs = model.objects.all() qs = model.objects.all()
elif model is MemberArtwork and any(request.user.has_perm(f'catalog.{action}_memberpost') for action in ('view', 'change')):
qs = MemberArtwork.objects.all()
elif model is Page and any(request.user.has_perm(f'catalog.{action}_chapter') for action in ('view', 'change')): elif model is Page and any(request.user.has_perm(f'catalog.{action}_chapter') for action in ('view', 'change')):
qs = Page.objects.all() qs = Page.objects.all()
record = qs.filter(**{field: name}).first() record = qs.filter(**{field: name}).first()
@@ -291,3 +338,37 @@ def health(request):
with connection.cursor() as cursor: with connection.cursor() as cursor:
cursor.execute('SELECT 1') cursor.execute('SELECT 1')
return JsonResponse({'status': 'ok', 'service': 'slx-studio'}) return JsonResponse({'status': 'ok', 'service': 'slx-studio'})
@require_POST
@login_required
def buy_chapter(request, number):
from django.conf import settings
from django.contrib import messages
from django.db import transaction
from shop.models import Product, Order, OrderItem
from shop.payments import create_stripe_order_session, stripe_ready
item = get_object_or_404(live(Chapter), number=number, publisher_url='', price_usd__gte='0.50')
if full_chapters(request.user).filter(pk=item.pk).exists():
return redirect('chapter', number=number)
if not request.user.is_active or not request.user.email or not stripe_ready() or not settings.SLX_COMMERCE_STRIPE_WEBHOOK_SECRET:
messages.error(request, 'Chapter checkout needs an account email and an enabled Stripe checkout.')
return redirect('chapter', number=number)
try:
with transaction.atomic():
product, _ = Product.objects.get_or_create(slug=f'digital-chapter-{item.pk}', defaults={
'kind': Product.Kind.DIGITAL, 'title': item.title[:160], 'sample_chapter': item,
'price_usd': item.price_usd, 'active': False, 'track_stock': False,
})
if product.kind != Product.Kind.DIGITAL or product.sample_chapter_id != item.pk:
raise ValueError('Reserved chapter product slug already exists.')
order = Order.objects.create(user=request.user, email=request.user.email, gateway=Order.Gateway.STRIPE,
subtotal_usd=item.price_usd, total_usd=item.price_usd)
OrderItem.objects.create(order=order, product=product, chapter=item, title_snapshot=item.title[:160],
unit_price_usd=item.price_usd)
url = create_stripe_order_session(order)
except Exception:
messages.error(request, 'Checkout could not start. Please try again.')
return redirect('chapter', number=number)
return redirect(url)
+5
View File
@@ -4,6 +4,11 @@ services:
image: postgres:16 image: postgres:16
restart: unless-stopped restart: unless-stopped
environment: environment:
SLX_PAYPAL_MODE: ${SLX_PAYPAL_MODE:-live}
SLX_PAYPAL_ORIGIN: ${SLX_PAYPAL_ORIGIN:-https://slumpxland-official.com}
SLX_PAYPAL_CLIENT_ID: ${SLX_PAYPAL_CLIENT_ID:-}
SLX_PAYPAL_CLIENT_SECRET: ${SLX_PAYPAL_CLIENT_SECRET:-}
SLX_PAYPAL_WEBHOOK_ID: ${SLX_PAYPAL_WEBHOOK_ID:-}
POSTGRES_DB: slump POSTGRES_DB: slump
POSTGRES_USER: slump POSTGRES_USER: slump
POSTGRES_PASSWORD_FILE: /run/secrets/db_password POSTGRES_PASSWORD_FILE: /run/secrets/db_password
View File
Whitespace-only changes.
View File
Whitespace-only changes.
View File
Whitespace-only changes.
View File
Whitespace-only changes.
View File
Whitespace-only changes.
+5 -5
View File
@@ -5,16 +5,16 @@ from .models import Order, OrderItem, Product, Subscription
@admin.register(Product, site=studio) @admin.register(Product, site=studio)
class ProductAdmin(admin.ModelAdmin): class ProductAdmin(admin.ModelAdmin):
list_display = ['title', 'kind', 'price_usd', 'stock', 'active', 'featured', 'position'] list_display = ['title', 'kind', 'price_usd', 'stock', 'active', 'featured', 'verified_by_seller', 'position']
list_filter = ['kind', 'active', 'featured'] list_filter = ['kind', 'active', 'featured', 'verified_by_seller']
list_editable = ['price_usd', 'stock', 'active', 'position'] list_editable = ['price_usd', 'stock', 'active', 'position']
search_fields = ['title', 'summary'] search_fields = ['title', 'summary']
prepopulated_fields = {'slug': ('title',)} prepopulated_fields = {'slug': ('title',)}
fieldsets = [ fieldsets = [
('Product', {'fields': ['title', 'slug', 'kind', 'summary', 'description', 'image', 'price_usd', 'active', 'featured', 'position']}), ('Product', {'fields': ['title', 'slug', 'kind', 'summary', 'description', 'image', 'price_usd', 'active', 'featured', 'verified_by_seller', 'position']}),
('Physical Inventory & Shipping', {'fields': ['track_stock', 'stock', 'shipping_usd']}), ('Physical Inventory & Shipping', {'fields': ['track_stock', 'stock', 'shipping_usd']}),
('Digital Download', {'fields': ['digital_file']}), ('Digital Download', {'fields': ['digital_file', 'sample_chapter']}),
('Subscription Billing', {'fields': ['billing_interval', 'stripe_price_id', 'paypal_plan_id']}), ('Subscription Billing', {'fields': ['billing_interval', 'stripe_price_id', 'paypal_plan_id', 'member_tier', 'comparison']}),
] ]
@@ -0,0 +1,18 @@
# Generated by Django 5.2.19 on 2026-11-26 01:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='product',
name='verified_by_seller',
field=models.BooleanField(default=False, help_text='Show the Verified by Seller badge on this listing.'),
),
]
@@ -0,0 +1,45 @@
# Generated by Django 5.2.19 on 2026-11-26 11:05
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalog', '0027_alter_chapter_price_usd_managedpage'),
('shop', '0002_product_verified_by_seller'),
]
operations = [
migrations.AddField(
model_name='order',
name='stripe_live',
field=models.BooleanField(editable=False, null=True),
),
migrations.AddField(
model_name='orderitem',
name='chapter',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='catalog.chapter'),
),
migrations.AddField(
model_name='product',
name='member_tier',
field=models.PositiveSmallIntegerField(blank=True, choices=[(1, 'Early Access'), (2, 'Studio Vault')], null=True),
),
migrations.AddField(
model_name='product',
name='sample_chapter',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='shop_editions', to='catalog.chapter'),
),
migrations.AddField(
model_name='subscription',
name='entitlement_tier',
field=models.PositiveSmallIntegerField(editable=False, null=True),
),
migrations.AddField(
model_name='subscription',
name='stripe_live',
field=models.BooleanField(editable=False, null=True),
),
]
+20
View File
@@ -0,0 +1,20 @@
from decimal import Decimal
from django.db import migrations
def seed(apps, schema_editor):
Product = apps.get_model('shop', 'Product')
products = Product.objects.using(schema_editor.connection.alias)
for slug, label, tier in [('slx-monthly-early-access', 'Early Access', 1),
('slx-monthly-studio-vault', 'Studio Vault', 2)]:
if not products.filter(kind='subscription', member_tier=tier).exists():
products.get_or_create(slug=slug, defaults={
'title': f'Slump X Land Monthly · {label}', 'kind': 'subscription',
'billing_interval': 'month', 'member_tier': tier, 'price_usd': Decimal('0.50'),
'track_stock': False, 'active': False,
})
class Migration(migrations.Migration):
dependencies = [('shop', '0003_order_stripe_live_orderitem_chapter_and_more')]
operations = [migrations.RunPython(seed, migrations.RunPython.noop)]
@@ -0,0 +1,18 @@
# Generated by Django 5.2.19 on 2026-11-26 12:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0004_fan_club_products'),
]
operations = [
migrations.AddField(
model_name='product',
name='comparison',
field=models.TextField(blank=True, help_text='One benefit per line, using Feature: Details. Used on the membership comparison chart.', max_length=3000),
),
]
+18
View File
@@ -0,0 +1,18 @@
# Generated by Django 5.2.19 on 2026-11-26 13:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0005_product_comparison'),
]
operations = [
migrations.AlterField(
model_name='product',
name='member_tier',
field=models.PositiveSmallIntegerField(blank=True, choices=[(1, 'Early Access'), (2, 'Studio Vault'), (3, 'Collector’s Circle')], null=True),
),
]
+11
View File
@@ -24,7 +24,14 @@ class Product(models.Model):
image = models.ImageField(upload_to='shop/products/', blank=True) image = models.ImageField(upload_to='shop/products/', blank=True)
price_usd = models.DecimalField(max_digits=9, decimal_places=2, validators=[MinValueValidator(Decimal('0.50'))]) price_usd = models.DecimalField(max_digits=9, decimal_places=2, validators=[MinValueValidator(Decimal('0.50'))])
active = models.BooleanField(default=True) active = models.BooleanField(default=True)
comparison = models.TextField(blank=True, max_length=3000,
help_text='One benefit per line, using Feature: Details. Used on the membership comparison chart.')
featured = models.BooleanField(default=False) featured = models.BooleanField(default=False)
sample_chapter = models.ForeignKey('catalog.Chapter', null=True, blank=True, on_delete=models.SET_NULL,
related_name='shop_editions')
member_tier = models.PositiveSmallIntegerField(choices=[(1, 'Early Access'), (2, 'Studio Vault'), (3, 'Collector’s Circle')],
null=True, blank=True)
verified_by_seller = models.BooleanField(default=False, help_text="Show the Verified by Seller badge on this listing.")
position = models.PositiveIntegerField(default=0) position = models.PositiveIntegerField(default=0)
# Physical inventory & shipping # Physical inventory & shipping
@@ -96,6 +103,7 @@ class Order(models.Model):
# Gateway tracking # Gateway tracking
gateway_session_id = models.CharField(max_length=200, blank=True, db_index=True) gateway_session_id = models.CharField(max_length=200, blank=True, db_index=True)
gateway_payment_id = models.CharField(max_length=200, blank=True) gateway_payment_id = models.CharField(max_length=200, blank=True)
stripe_live = models.BooleanField(null=True, editable=False)
paid_at = models.DateTimeField(null=True, blank=True) paid_at = models.DateTimeField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True) created_at = models.DateTimeField(auto_now_add=True)
@@ -113,6 +121,7 @@ class Order(models.Model):
class OrderItem(models.Model): class OrderItem(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items') order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items')
product = models.ForeignKey(Product, on_delete=models.PROTECT) product = models.ForeignKey(Product, on_delete=models.PROTECT)
chapter = models.ForeignKey('catalog.Chapter', null=True, blank=True, on_delete=models.PROTECT)
title_snapshot = models.CharField(max_length=160) title_snapshot = models.CharField(max_length=160)
unit_price_usd = models.DecimalField(max_digits=9, decimal_places=2) unit_price_usd = models.DecimalField(max_digits=9, decimal_places=2)
quantity = models.PositiveIntegerField(default=1) quantity = models.PositiveIntegerField(default=1)
@@ -137,6 +146,8 @@ class Subscription(models.Model):
gateway_sub_id = models.CharField(max_length=200, blank=True, db_index=True) gateway_sub_id = models.CharField(max_length=200, blank=True, db_index=True)
gateway_customer_id = models.CharField(max_length=200, blank=True) gateway_customer_id = models.CharField(max_length=200, blank=True)
status = models.CharField(max_length=20, choices=Status.choices, default=Status.PENDING) status = models.CharField(max_length=20, choices=Status.choices, default=Status.PENDING)
stripe_live = models.BooleanField(null=True, editable=False)
entitlement_tier = models.PositiveSmallIntegerField(null=True, editable=False)
current_period_end = models.DateTimeField(null=True, blank=True) current_period_end = models.DateTimeField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True) created_at = models.DateTimeField(auto_now_add=True)
+7 -5
View File
@@ -9,11 +9,12 @@ from django.utils import timezone
import stripe import stripe
from catalog.paypal import CheckoutError, access_token, checkout_origin, request_json, safe_approval_url from catalog.paypal import CheckoutError, access_token, checkout_origin, request_json, safe_approval_url
from catalog.shop_stripe import origin as stripe_origin
from .models import Order, Product, Subscription from .models import Order, Product, Subscription
def stripe_ready(): def stripe_ready():
return bool(settings.SLX_STRIPE_SECRET_KEY and checkout_origin()) return bool(settings.SLX_STRIPE_SECRET_KEY and (stripe_origin() or checkout_origin()))
def paypal_ready(): def paypal_ready():
@@ -23,7 +24,7 @@ def paypal_ready():
and checkout_origin()) and checkout_origin())
def fulfill_order(order, payment_id=''): def fulfill_order(order, payment_id='', stripe_live=None):
with transaction.atomic(): with transaction.atomic():
order = Order.objects.select_for_update().get(pk=order.pk) order = Order.objects.select_for_update().get(pk=order.pk)
if order.status != Order.Status.PENDING: if order.status != Order.Status.PENDING:
@@ -32,7 +33,8 @@ def fulfill_order(order, payment_id=''):
order.paid_at = timezone.now() order.paid_at = timezone.now()
if payment_id: if payment_id:
order.gateway_payment_id = payment_id[:200] order.gateway_payment_id = payment_id[:200]
order.save(update_fields=['status', 'paid_at', 'gateway_payment_id']) order.stripe_live = stripe_live
order.save(update_fields=['status', 'paid_at', 'gateway_payment_id', 'stripe_live'])
for item in order.items.select_related('product'): for item in order.items.select_related('product'):
prod = item.product prod = item.product
@@ -47,7 +49,7 @@ def fulfill_order(order, payment_id=''):
def create_stripe_order_session(order): def create_stripe_order_session(order):
stripe.api_key = settings.SLX_STRIPE_SECRET_KEY stripe.api_key = settings.SLX_STRIPE_SECRET_KEY
origin = checkout_origin() origin = stripe_origin() or checkout_origin()
line_items = [] line_items = []
for item in order.items.select_related('product'): for item in order.items.select_related('product'):
line_items.append({ line_items.append({
@@ -88,7 +90,7 @@ def create_stripe_order_session(order):
def create_stripe_subscription_session(sub): def create_stripe_subscription_session(sub):
stripe.api_key = settings.SLX_STRIPE_SECRET_KEY stripe.api_key = settings.SLX_STRIPE_SECRET_KEY
origin = checkout_origin() origin = stripe_origin() or checkout_origin()
prod = sub.product prod = sub.product
if prod.stripe_price_id: if prod.stripe_price_id:
line_item = {'price': prod.stripe_price_id, 'quantity': 1} line_item = {'price': prod.stripe_price_id, 'quantity': 1}
+1 -1
View File
@@ -11,7 +11,7 @@ urlpatterns = [
path('paypal/return/<uuid:order_id>/', views.paypal_return, name='shop-paypal-return'), path('paypal/return/<uuid:order_id>/', views.paypal_return, name='shop-paypal-return'),
path('order/<uuid:order_id>/', views.order_detail, name='shop-order-detail'), path('order/<uuid:order_id>/', views.order_detail, name='shop-order-detail'),
path('order/<uuid:order_id>/download/<int:item_id>/', views.download_digital, name='shop-download'), path('order/<uuid:order_id>/download/<int:item_id>/', views.download_digital, name='shop-download'),
path('webhooks/stripe/', views.stripe_webhook, name='shop-stripe-webhook'), path('webhooks/stripe/', views.stripe_webhook, name='commerce-stripe-webhook'),
path('webhooks/paypal/', views.paypal_webhook, name='shop-paypal-webhook'), path('webhooks/paypal/', views.paypal_webhook, name='shop-paypal-webhook'),
path('<slug:slug>/', views.product_detail, name='shop-product'), path('<slug:slug>/', views.product_detail, name='shop-product'),
] ]
+60 -22
View File
@@ -1,7 +1,10 @@
from datetime import datetime, timezone as utc
from decimal import Decimal from decimal import Decimal
import json import json
from django.conf import settings from django.conf import settings
from django.contrib import messages from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.db import transaction
from django.http import FileResponse, Http404, HttpResponse, HttpResponseBadRequest from django.http import FileResponse, Http404, HttpResponse, HttpResponseBadRequest
from django.shortcuts import get_object_or_404, redirect, render from django.shortcuts import get_object_or_404, redirect, render
from django.utils import timezone from django.utils import timezone
@@ -76,10 +79,16 @@ def index(request):
def product_detail(request, slug): def product_detail(request, slug):
product = get_object_or_404(Product, slug=slug, active=True) product = get_object_or_404(Product, slug=slug, active=True)
cart_count = sum(_get_cart(request).values()) cart_count = sum(_get_cart(request).values())
from catalog.fans import live
from catalog.models import Chapter
chapter = live(Chapter).filter(pk=product.sample_chapter_id, publisher_url='').first()
return render(request, 'shop/product.html', { return render(request, 'shop/product.html', {
'sample_chapter': chapter,
'editions': Product.objects.filter(active=True, kind=Product.Kind.PHYSICAL, sample_chapter=chapter).exclude(pk=product.pk) if chapter else (),
'related_products': Product.objects.filter(active=True).exclude(pk=product.pk)[:6],
'product': product, 'product': product,
'cart_count': cart_count, 'cart_count': cart_count,
'stripe_enabled': stripe_ready(), 'stripe_enabled': stripe_ready() and bool(settings.SLX_COMMERCE_STRIPE_WEBHOOK_SECRET),
'paypal_enabled': paypal_ready(), 'paypal_enabled': paypal_ready(),
}) })
@@ -173,9 +182,13 @@ def checkout_start(request):
@require_POST @require_POST
@login_required
def subscribe_start(request, slug): def subscribe_start(request, slug):
product = get_object_or_404(Product, slug=slug, active=True, kind=Product.Kind.SUBSCRIPTION) product = get_object_or_404(Product, slug=slug, active=True, kind=Product.Kind.SUBSCRIPTION)
gateway = request.POST.get('gateway', '').lower() gateway = request.POST.get('gateway', '').lower()
if product.member_tier and (gateway != 'stripe' or not stripe_ready() or not settings.SLX_COMMERCE_STRIPE_WEBHOOK_SECRET):
messages.error(request, 'Fan Club subscriptions require Stripe checkout.')
return redirect('shop-product', slug=slug)
email = (request.user.email if request.user.is_authenticated and request.user.email else request.POST.get('email', '')).strip() email = (request.user.email if request.user.is_authenticated and request.user.email else request.POST.get('email', '')).strip()
if not email or '@' not in email: if not email or '@' not in email:
messages.error(request, 'Please enter a valid email address to subscribe.') messages.error(request, 'Please enter a valid email address to subscribe.')
@@ -184,7 +197,7 @@ def subscribe_start(request, slug):
sub = Subscription.objects.create( sub = Subscription.objects.create(
user=request.user if request.user.is_authenticated else None, user=request.user if request.user.is_authenticated else None,
email=email, email=email,
product=product, product=product, entitlement_tier=product.member_tier,
gateway=gateway if gateway in {'stripe', 'paypal'} else Order.Gateway.STRIPE, gateway=gateway if gateway in {'stripe', 'paypal'} else Order.Gateway.STRIPE,
) )
try: try:
@@ -229,24 +242,27 @@ def download_digital(request, order_id, item_id):
@csrf_exempt @csrf_exempt
@require_POST @require_POST
def stripe_webhook(request): def stripe_webhook(request):
if not settings.SLX_STRIPE_WEBHOOK_SECRET: if not settings.SLX_COMMERCE_STRIPE_WEBHOOK_SECRET:
return HttpResponseBadRequest('Webhook secret not configured') return HttpResponseBadRequest('Webhook secret not configured')
stripe.api_key = settings.SLX_STRIPE_SECRET_KEY stripe.api_key = settings.SLX_STRIPE_SECRET_KEY
sig = request.META.get('HTTP_STRIPE_SIGNATURE', '') sig = request.META.get('HTTP_STRIPE_SIGNATURE', '')
try: try:
event = stripe.Webhook.construct_event(request.body, sig, settings.SLX_STRIPE_WEBHOOK_SECRET) event = stripe.Webhook.construct_event(request.body, sig, settings.SLX_COMMERCE_STRIPE_WEBHOOK_SECRET)
except Exception: except Exception:
return HttpResponseBadRequest('Invalid signature') return HttpResponseBadRequest('Invalid signature')
from catalog.chapter_access import stripe_live_mode
if event.get('livemode') != stripe_live_mode():
return HttpResponseBadRequest('Stripe mode mismatch')
etype = event['type'] etype = event['type']
obj = event['data']['object'] obj = event['data']['object']
if etype in ('checkout.session.completed', 'checkout.session.async_payment_succeeded'):
if etype == 'checkout.session.completed':
meta = obj.get('metadata') or {} meta = obj.get('metadata') or {}
if meta.get('kind') == 'order' and meta.get('order_id'): if meta.get('kind') == 'order' and obj.get('payment_status') == 'paid':
order = Order.objects.filter(order_id=meta['order_id']).first() order = Order.objects.filter(gateway=Order.Gateway.STRIPE, gateway_session_id=obj.get('id', '')).first()
if order: if (order and str(order.order_id) == meta.get('order_id') and obj.get('currency') == 'usd'
shipping = obj.get('shipping_details') or {} and obj.get('amount_total') == int(order.total_usd * 100)):
shipping = obj.get('shipping_details') or (obj.get('collected_information') or {}).get('shipping_details') or {}
addr = shipping.get('address') or {} addr = shipping.get('address') or {}
if addr: if addr:
order.full_name = (shipping.get('name') or order.full_name)[:160] order.full_name = (shipping.get('name') or order.full_name)[:160]
@@ -260,23 +276,45 @@ def stripe_webhook(request):
'full_name', 'shipping_line1', 'shipping_line2', 'full_name', 'shipping_line1', 'shipping_line2',
'shipping_city', 'shipping_state', 'shipping_postal', 'shipping_country' 'shipping_city', 'shipping_state', 'shipping_postal', 'shipping_country'
]) ])
fulfill_order(order, payment_id=obj.get('payment_intent') or obj.get('id', '')) fulfill_order(order, payment_id=obj.get('payment_intent') or obj['id'], stripe_live=event['livemode'])
elif meta.get('kind') == 'subscription' and meta.get('sub_id'): elif meta.get('kind') == 'subscription' and obj.get('subscription'):
Subscription.objects.filter(sub_id=meta['sub_id']).update( sync_stripe_subscription(obj['subscription'], event['livemode'], meta.get('sub_id'))
status=Subscription.Status.ACTIVE,
gateway_sub_id=obj.get('subscription') or '',
gateway_customer_id=obj.get('customer') or '',
)
elif etype in ('customer.subscription.deleted', 'invoice.payment_failed'): elif etype == 'charge.refunded' and obj.get('refunded') and obj.get('payment_intent'):
sub_id = obj.get('id') if etype == 'customer.subscription.deleted' else obj.get('subscription') Order.objects.filter(gateway=Order.Gateway.STRIPE, stripe_live=event['livemode'],
gateway_payment_id=obj['payment_intent']).update(status=Order.Status.REFUNDED)
elif etype in ('customer.subscription.updated', 'customer.subscription.deleted',
'invoice.paid', 'invoice.payment_failed'):
sub_id = obj.get('id') if etype.startswith('customer.subscription.') else (
obj.get('subscription') or ((obj.get('parent') or {}).get('subscription_details') or {}).get('subscription'))
if sub_id: if sub_id:
new_status = Subscription.Status.CANCELED if etype == 'customer.subscription.deleted' else Subscription.Status.PAST_DUE sync_stripe_subscription(sub_id, event['livemode'])
Subscription.objects.filter(gateway_sub_id=sub_id).update(status=new_status)
return HttpResponse('ok') return HttpResponse('ok')
def sync_stripe_subscription(remote_id, live_mode, checkout_ref=None):
with transaction.atomic():
rows = Subscription.objects.select_for_update().filter(gateway=Order.Gateway.STRIPE)
sub = rows.filter(gateway_sub_id=remote_id, stripe_live=live_mode).first()
if sub is None and checkout_ref:
sub = rows.filter(sub_id=checkout_ref, gateway_sub_id='').first()
if not sub:
return
current = stripe.Subscription.retrieve(remote_id)
if current.get('livemode') != live_mode or (current.get('metadata') or {}).get('sub_id') != str(sub.sub_id):
return
state = current.get('status')
periods = [item.get('current_period_end') for item in (current.get('items') or {}).get('data', [])]
period = current.get('current_period_end') or min((v for v in periods if v), default=None)
sub.status = (Subscription.Status.ACTIVE if state == 'active' else Subscription.Status.CANCELED
if state in {'canceled', 'incomplete_expired'} else Subscription.Status.PAST_DUE)
sub.current_period_end = datetime.fromtimestamp(period, tz=utc.utc) if period else None
sub.gateway_sub_id = remote_id
sub.gateway_customer_id = current.get('customer') or ''
sub.stripe_live = live_mode
sub.save(update_fields=['status', 'current_period_end', 'gateway_sub_id', 'gateway_customer_id', 'stripe_live'])
@csrf_exempt @csrf_exempt
@require_POST @require_POST
def paypal_webhook(request): def paypal_webhook(request):
+7 -17
View File
@@ -56,10 +56,17 @@ LOGIN_URL='fan-login'
LOGIN_REDIRECT_URL='library' LOGIN_REDIRECT_URL='library'
# Keep disabled until a PayPal app and canonical HTTPS origin are configured. # Keep disabled until a PayPal app and canonical HTTPS origin are configured.
SLX_STRIPE_SECRET_KEY = (read_secret('SLX_STRIPE_SECRET_KEY') or read_secret('STRIPE_SECRET_KEY')).strip()
SLX_STRIPE_WEBHOOK_SECRET = (read_secret('SLX_STRIPE_WEBHOOK_SECRET') or read_secret('STRIPE_WEBHOOK_SECRET')).strip()
SLX_COMMERCE_STRIPE_WEBHOOK_SECRET = read_secret('SLX_COMMERCE_STRIPE_WEBHOOK_SECRET').strip() or SLX_STRIPE_WEBHOOK_SECRET
SLX_STRIPE_ORIGIN = os.getenv('SLX_STRIPE_ORIGIN', '').strip()
SLX_STRIPE_SHIP_COUNTRIES = os.getenv('SLX_STRIPE_SHIP_COUNTRIES', 'US').split(',')
SLX_PAYPAL_MODE = os.getenv('SLX_PAYPAL_MODE', '').strip().lower() SLX_PAYPAL_MODE = os.getenv('SLX_PAYPAL_MODE', '').strip().lower()
SLX_PAYPAL_CLIENT_ID = os.getenv('SLX_PAYPAL_CLIENT_ID', '').strip() SLX_PAYPAL_CLIENT_ID = os.getenv('SLX_PAYPAL_CLIENT_ID', '').strip()
SLX_PAYPAL_CLIENT_SECRET = os.getenv('SLX_PAYPAL_CLIENT_SECRET', '').strip() SLX_PAYPAL_CLIENT_SECRET = os.getenv('SLX_PAYPAL_CLIENT_SECRET', '').strip()
SLX_PAYPAL_ORIGIN = os.getenv('SLX_PAYPAL_ORIGIN', '').strip() SLX_PAYPAL_ORIGIN = os.getenv('SLX_PAYPAL_ORIGIN', '').strip()
SLX_PAYPAL_WEBHOOK_ID = os.getenv('SLX_PAYPAL_WEBHOOK_ID', '').strip()
SLX_ANALYTICS = os.getenv('SLX_ANALYTICS', '1') == '1' SLX_ANALYTICS = os.getenv('SLX_ANALYTICS', '1') == '1'
SLX_GEOIP_DB = os.getenv('SLX_GEOIP_DB', '').strip() SLX_GEOIP_DB = os.getenv('SLX_GEOIP_DB', '').strip()
@@ -82,20 +89,3 @@ EMAIL_HOST_PASSWORD = read_secret('SLX_SMTP_PASSWORD').strip()
EMAIL_USE_TLS = os.getenv('SLX_SMTP_SECURITY', 'starttls') == 'starttls' EMAIL_USE_TLS = os.getenv('SLX_SMTP_SECURITY', 'starttls') == 'starttls'
EMAIL_USE_SSL = os.getenv('SLX_SMTP_SECURITY', 'starttls') == 'ssl' EMAIL_USE_SSL = os.getenv('SLX_SMTP_SECURITY', 'starttls') == 'ssl'
EMAIL_TIMEOUT = 15 EMAIL_TIMEOUT = 15
def _read_secret(env_var, file_env_var, default=''):
val = os.environ.get(env_var, '').strip()
if val:
return val
fpath = os.environ.get(file_env_var, '').strip()
if fpath and os.path.isfile(fpath):
return Path(fpath).read_text().strip()
return default
SLX_STRIPE_SECRET_KEY = _read_secret('SLX_STRIPE_SECRET_KEY', 'SLX_STRIPE_SECRET_KEY_FILE')
SLX_STRIPE_WEBHOOK_SECRET = _read_secret('SLX_STRIPE_WEBHOOK_SECRET', 'SLX_STRIPE_WEBHOOK_SECRET_FILE')
SLX_PAYPAL_MODE = os.environ.get('SLX_PAYPAL_MODE', 'sandbox').strip()
SLX_PAYPAL_ORIGIN = os.environ.get('SLX_PAYPAL_ORIGIN', 'https://slumpxland-official.com').strip()
SLX_PAYPAL_CLIENT_ID = os.environ.get('SLX_PAYPAL_CLIENT_ID', '').strip()
SLX_PAYPAL_CLIENT_SECRET = os.environ.get('SLX_PAYPAL_CLIENT_SECRET', '').strip()
SLX_PAYPAL_WEBHOOK_ID = os.environ.get('SLX_PAYPAL_WEBHOOK_ID', '').strip()
+15 -3
View File
@@ -1,13 +1,17 @@
from django.conf import settings from django.conf import settings
from django.urls import re_path from django.urls import include, re_path
from django.views.static import serve from django.views.static import serve
from django.urls import include, path from django.views.generic import TemplateView
from django.urls import path
from django.contrib.auth import views as auth_views from django.contrib.auth import views as auth_views
from catalog import views, fans, reactions, reviews, paypal, streams, newsletter from catalog import views, fans, reactions, reviews, paypal, streams, newsletter, shop_stripe, membership, collectors
from catalog.admin import studio from catalog.admin import studio
urlpatterns = [ urlpatterns = [
path('', views.home, name='home'), path('', views.home, name='home'),
path('map/', views.map_landing, name='world-map'),
path('pages/<slug:slug>/', views.managed_page, name='managed-page'),
path('chapters/<int:number>/buy/', views.buy_chapter, name='buy-chapter'),
path('admin/', studio.urls), path('admin/', studio.urls),
path('shop/', include('shop.urls')), path('shop/', include('shop.urls')),
path('chapters/', views.chapters, name='chapters'), path('chapters/', views.chapters, name='chapters'),
@@ -32,11 +36,15 @@ urlpatterns = [
path('fan/login/', auth_views.LoginView.as_view(template_name='registration/fan-login.html'), name='fan-login'), path('fan/login/', auth_views.LoginView.as_view(template_name='registration/fan-login.html'), name='fan-login'),
path('fan/logout/', auth_views.LogoutView.as_view(next_page='home'), name='fan-logout'), path('fan/logout/', auth_views.LogoutView.as_view(next_page='home'), name='fan-logout'),
path('fan/signup/', fans.signup, name='fan-signup'), path('fan/signup/', fans.signup, name='fan-signup'),
path('fan/collector-preferences/', collectors.preferences, name='collector-preferences'),
path('fan/library/', fans.library, name='library'), path('fan/library/', fans.library, name='library'),
path('fan/follow/', fans.follow_title, name='fan-follow'), path('fan/follow/', fans.follow_title, name='fan-follow'),
path('fan/notifications/', fans.notices, name='fan-notices'), path('fan/notifications/', fans.notices, name='fan-notices'),
path('fan/action/<str:kind>/<int:pk>/', fans.act, name='fan-action'), path('fan/action/<str:kind>/<int:pk>/', fans.act, name='fan-action'),
path('books/', paypal.books, name='books'), path('books/', paypal.books, name='books'),
path('books/checkout/<int:product_id>/<int:variant_id>/', shop_stripe.checkout, name='shop-stripe-checkout'),
path('books/payment/<uuid:reference>/', shop_stripe.receipt, name='shop-stripe-receipt'),
path('webhooks/stripe/shop/', shop_stripe.webhook, name='shop-stripe-webhook'),
path('chapters/<int:number>/checkout/', paypal.start, name='paypal-start'), path('chapters/<int:number>/checkout/', paypal.start, name='paypal-start'),
path('checkout/paypal/<uuid:checkout_id>/', paypal.returned, name='paypal-return'), path('checkout/paypal/<uuid:checkout_id>/', paypal.returned, name='paypal-return'),
path('checkout/paypal/<uuid:checkout_id>/finish/', paypal.finish, name='paypal-finish'), path('checkout/paypal/<uuid:checkout_id>/finish/', paypal.finish, name='paypal-finish'),
@@ -44,10 +52,14 @@ urlpatterns = [
path('media/images/<uuid:key>', views.image, name='image'), path('media/images/<uuid:key>', views.image, name='image'),
re_path(r'^media/shop/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT / 'shop'}), re_path(r'^media/shop/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT / 'shop'}),
path('healthz/', views.health, name='health'), path('healthz/', views.health, name='health'),
path('membership/', membership.index, name='membership'),
path('membership/posts/<int:pk>/', membership.detail, name='member-post'),
path('newsletter/', newsletter.signup, name='newsletter-signup'), path('newsletter/', newsletter.signup, name='newsletter-signup'),
path('newsletter/confirm/<uuid:token>/', newsletter.confirm, name='newsletter-confirm'), path('newsletter/confirm/<uuid:token>/', newsletter.confirm, name='newsletter-confirm'),
path('newsletter/unsubscribe/<uuid:token>/', newsletter.unsubscribe, name='newsletter-unsubscribe'), path('newsletter/unsubscribe/<uuid:token>/', newsletter.unsubscribe, name='newsletter-unsubscribe'),
path('newsletter/one-click/<uuid:token>/', newsletter.one_click, name='newsletter-one-click'), path('newsletter/one-click/<uuid:token>/', newsletter.one_click, name='newsletter-one-click'),
path('about/', TemplateView.as_view(template_name='series-intro.html'), name='series-intro'),
path('djinnii/', TemplateView.as_view(template_name='djinnii.html'), name='djinnii'),
path('<slug:kind>/', views.entries, name='entries'), path('<slug:kind>/', views.entries, name='entries'),
path('<slug:kind>/<slug:slug>/', views.entry, name='entry'), path('<slug:kind>/<slug:slug>/', views.entry, name='entry'),
] ]
Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

+9
View File
@@ -0,0 +1,9 @@
(() => {
const reminder = document.querySelector('[data-archive-reminder]');
if (!reminder || typeof reminder.showModal !== 'function') return;
try {
if (sessionStorage.getItem('slx-archive-reminder')) return;
sessionStorage.setItem('slx-archive-reminder', 'seen');
} catch { /* The reminder still works when session storage is unavailable. */ }
if (!document.querySelector('dialog[open]')) reminder.showModal();
})();
+25
View File
@@ -0,0 +1,25 @@
.release-landing.countdown-showcase{padding:clamp(.75rem,2.5vw,2.25rem)}
.countdown-showcase .compact-release{width:min(100%,72rem);display:grid;grid-template-columns:minmax(0,.84fr) minmax(0,1.16fr);align-items:start;gap:clamp(.75rem,2vw,1.35rem)}
.compact-release .release-stage{grid-column:1/-1;padding:0 .25rem clamp(1rem,3.5vw,2rem)}
.compact-release .release-hover{width:min(100%,61rem);display:grid;justify-items:center}
.compact-release .release-cover{display:block;width:auto;height:auto;max-width:100%;max-height:min(59svh,42rem);object-fit:contain}
.compact-release .release-reflection{display:none}
.compact-release .release-copy,.compact-release .release-message{min-width:0;text-align:left}
.compact-release .release-timer-panel{padding:clamp(.85rem,2vw,1.35rem)}
.compact-release .release-timer-panel h1{font-size:clamp(1.5rem,3.3vw,2.85rem);line-height:1.1;margin:.45rem 0 .7rem}
.compact-release .release-clock .ticker{font-size:clamp(1.1rem,2.6vw,1.65rem)}
.compact-release .release-progress{margin-top:.7rem}
.compact-release .slx-author-note{margin:0;padding:clamp(.85rem,2vw,1.4rem)}
.compact-release .slx-author-note-copy{font-size:clamp(.95rem,1.5vw,1.08rem);line-height:1.5}
.compact-release .slx-author-note-copy p{margin:0 0 .65em}
.compact-release .slx-author-note-signoff{margin-top:.55rem}
.compact-release .slx-author-avatar{width:clamp(44px,6vw,76px);height:auto}
.compact-release .slx-author-signature{max-width:min(38%,9rem)}
@media(max-width:670px){
.countdown-showcase .compact-release{grid-template-columns:minmax(0,1fr);gap:.65rem}
.compact-release .release-stage{padding-bottom:.6rem}
.compact-release .release-cover{max-height:min(47svh,24rem)}
}
.compact-release .release-reflection{display:grid;justify-items:center;top:100%;height:20%;opacity:.16}
.compact-release .release-reflection img{display:block;width:auto;height:auto;max-width:100%;max-height:min(59svh,42rem);object-fit:contain}
@media(max-width:670px){.compact-release .release-reflection{display:none}}
Binary file not shown.

After

Width:  |  Height:  |  Size: 224 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 300 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 387 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 211 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 124 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 368 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 251 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 446 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 254 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 327 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 367 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 200 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 346 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 370 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 264 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 265 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 295 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 236 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 427 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 302 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 184 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 305 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 252 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 411 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 505 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 346 B

+4
View File
@@ -0,0 +1,4 @@
header.site-header{position:relative;isolation:isolate}
header.site-header::before{content:"";position:absolute;inset:0;z-index:-1;pointer-events:none;background:url("solterra-map.jpg") center 44%/cover no-repeat;opacity:.16}
.djinnii-page{max-width:68rem;margin-inline:auto;padding-inline:1rem}
.djinnii-chart{display:block;width:100%;height:auto}
+38
View File
@@ -37,3 +37,41 @@ body.reader-lock{overflow:hidden}
.chapter-finish-card p{margin:.2rem 0}.chapter-finish-card .actions{margin-top:.75rem;align-items:center} .chapter-finish-card p{margin:.2rem 0}.chapter-finish-card .actions{margin-top:.75rem;align-items:center}
.chapter-finish-close{position:absolute;right:.55rem;top:.55rem;font-size:1.1rem;line-height:1} .chapter-finish-close{position:absolute;right:.55rem;top:.55rem;font-size:1.1rem;line-height:1}
.reader .chapter-finish-cover{width:clamp(66px,22vw,120px);max-height:min(180px,42dvh);object-fit:contain;border-radius:7px;margin:0;flex:none} .reader .chapter-finish-cover{width:clamp(66px,22vw,120px);max-height:min(180px,42dvh);object-fit:contain;border-radius:7px;margin:0;flex:none}
/* Compact reader: title/actions at the top, page position below the art. */
.section.manaa-reader{padding-block:clamp(.6rem,2vw,1.4rem);max-width:1320px}
.reading-deck .reading-heading{position:relative;z-index:4;display:grid;grid-template-columns:auto minmax(0,1fr) auto auto;gap:.2rem;padding:.22rem .45rem}
.reading-deck .reading-heading h1{overflow:hidden;white-space:nowrap;text-overflow:ellipsis;font-size:clamp(.9rem,2.8vw,1.18rem)}
.reading-icon{display:grid;place-items:center;width:44px;min-height:44px;font-size:1.22rem;color:inherit;text-decoration:none;border-radius:.45rem;cursor:pointer}
.reading-heading .reading-icon{font-size:1.22rem}
.reading-icon:hover{background:#ffffff15}
.reading-settings>summary{list-style:none}
.reading-settings>summary::-webkit-details-marker{display:none}
.reading-settings-panel{position:absolute;right:.45rem;top:calc(100% - 1px);z-index:5;display:grid;gap:.75rem;min-width:min(14rem,calc(100vw - 2rem));padding:.85rem;border:1px solid var(--rule);border-radius:.55rem;background:var(--slx-reader-bar,#161f30);color:var(--slx-reader-ink,#eff4ff);box-shadow:0 .5rem 1.3rem #0008;font-size:.85rem}
.reading-settings .reading-view{display:grid}
.reading-deck .reading-tools{position:relative;top:auto;z-index:2;display:block;padding:.18rem .45rem;border-top:1px solid var(--rule);border-bottom:0}
.reading-deck .reading-move{display:grid;grid-template-columns:44px minmax(0,1fr) 44px;gap:clamp(.35rem,2vw,.9rem);max-width:52rem;margin:auto}
.reading-deck .reading-move button{min-height:40px}
.reading-position{display:grid;gap:0;min-width:0;text-align:center}
.reading-move .reading-position span{min-width:0;font-size:.75rem}
.reading-position input{width:100%;margin:0;height:1.3rem;accent-color:var(--brand-red,#ff5a59);cursor:pointer}
.reading-deck[data-mode=scroll] .reading-move button,
.reading-deck[data-mode=scroll] .reading-position input{display:none}
.reading-deck[data-mode=scroll] .reading-move{grid-template-columns:1fr}
.reading-deck[data-mode]:not(.show-reader-reactions) .reading-frame figcaption{display:none}
.reading-deck:is([data-mode=double],[data-mode=single]) .reading-window:not(.is-zoomed){
--reader-fit-height:min(78svh,860px);height:var(--reader-fit-height);display:grid;align-items:center;
}
.reading-deck:is([data-mode=double],[data-mode=single]).show-reader-reactions .reading-window:not(.is-zoomed){height:auto;min-height:var(--reader-fit-height)}
.reading-deck:is([data-mode=double],[data-mode=single]) .reading-frame{align-items:center}
.reading-deck:is(.reading-native,.reading-immersive) .reading-heading{display:grid}
.reading-deck:is(.reading-native,.reading-immersive) .reading-window:not(.is-zoomed){height:auto;min-height:0;--reader-fit-height:var(--fullscreen-art-height,max(55px,calc(100dvh - 105px)))}
@media(max-width:600px){
body:has(.reading-deck[data-mode]) .site-header{display:none}
.section.manaa-reader{padding:0 0 1rem}
.reading-deck{border-inline:0;border-radius:0}
.manaa-reader> :not(.reading-deck){margin-inline:.75rem}
.reading-deck:is([data-mode=double],[data-mode=single]):not(.reading-native,.reading-immersive) .reading-window:not(.is-zoomed){
--reader-fit-height:max(190px,calc(100svh - 107px));
}
}
+53 -16
View File
@@ -9,6 +9,8 @@
const viewport = reader.querySelector('[data-reader-window]'); const viewport = reader.querySelector('[data-reader-window]');
const mode = reader.querySelector('[data-reader-mode]'); const mode = reader.querySelector('[data-reader-mode]');
const output = reader.querySelector('[data-page-output]'); const output = reader.querySelector('[data-page-output]');
const scrubber = reader.querySelector('[data-reader-scrubber]');
const settings = reader.querySelector('[data-reader-settings]');
const steps = [...reader.querySelectorAll('[data-step]')]; const steps = [...reader.querySelectorAll('[data-step]')];
const zoomButtons = [...reader.querySelectorAll('[data-zoom]')]; const zoomButtons = [...reader.querySelectorAll('[data-zoom]')];
const rtl = reader.dataset.direction === 'rtl'; const rtl = reader.dataset.direction === 'rtl';
@@ -17,7 +19,21 @@
let turns = []; let turns = [];
let index = 0; let index = 0;
let zoomResetScroll = false; let zoomResetScroll = false;
let pageMotion; let displayed;
let lastMode;
const warmed = new WeakSet();
function warmNearby() {
for (const turn of turns.slice(Math.max(0, index - 1), index + 3)) {
for (const page of turn.pages.length ? turn.pages : [turn.frame.el]) {
const image = page.querySelector('img');
if (!image || warmed.has(image)) continue;
warmed.add(image);
image.loading = 'eager';
image.decode?.().catch(() => {});
}
}
}
const finish = reader.querySelector('[data-chapter-finish]'); const finish = reader.querySelector('[data-chapter-finish]');
const marker = reader.querySelector('[data-reader-end]'); const marker = reader.querySelector('[data-reader-end]');
let finishTimer, shown = false, atEnd = false, lastVisible = false; let finishTimer, shown = false, atEnd = false, lastVisible = false;
@@ -43,7 +59,6 @@
}, {threshold: .25}).observe(frames[frames.length - 1].el); }, {threshold: .25}).observe(frames[frames.length - 1].el);
} }
document.addEventListener('visibilitychange', scheduleFinish); document.addEventListener('visibilitychange', scheduleFinish);
const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)');
const turnable = () => !zoom && mode.value !== 'scroll'; const turnable = () => !zoom && mode.value !== 'scroll';
const nextSwipeSign = rtl ? 1 : -1; const nextSwipeSign = rtl ? 1 : -1;
@@ -71,17 +86,27 @@
reader.dataset.mode = mode.value; reader.dataset.mode = mode.value;
viewport.classList.toggle('is-zoomed', zoom > 0); viewport.classList.toggle('is-zoomed', zoom > 0);
strip.style.setProperty('--reader-scale', levels[zoom] / 100); strip.style.setProperty('--reader-scale', levels[zoom] / 100);
for (const frame of frames) { const changed = lastMode !== mode.value || !displayed ? frames :
displayed === current.frame ? [current.frame] : [displayed, current.frame];
for (const frame of changed) {
const visible = scrolling || frame === current.frame; const visible = scrolling || frame === current.frame;
frame.el.hidden = !visible; frame.el.hidden = !visible;
for (const page of frame.pages) page.hidden = visible && !scrolling && !current.pages.includes(page); for (const page of frame.pages) page.hidden = visible && !scrolling && !current.pages.includes(page);
frame.el.classList.toggle('show-pair', frame.pages.length === 2 && (scrolling ? false : current.pages.length === 2)); frame.el.classList.toggle('show-pair', frame.pages.length === 2 && (scrolling ? false : current.pages.length === 2));
} }
displayed = current.frame;
lastMode = mode.value;
if (!scrolling) warmNearby();
const labels = current.pages.map((page) => page.dataset.number); const labels = current.pages.map((page) => page.dataset.number);
const label = current.frame.kind === 'cover' ? 'Cover' : const label = current.frame.kind === 'cover' ? 'Cover' :
current.frame.kind === 'spread' ? 'Spread · ' + labels[0] : current.frame.kind === 'spread' ? 'Spread · ' + labels[0] :
(labels.length === 2 ? 'Pages ' : 'Page ') + labels.join('–'); (labels.length === 2 ? 'Pages ' : 'Page ') + labels.join('–');
output.textContent = scrolling ? 'Scroll view' : label + ' · ' + (index + 1) + '/' + turns.length; output.textContent = scrolling ? 'Scroll view' : label + ' · ' + (index + 1) + '/' + turns.length;
scrubber.disabled = scrolling || turns.length < 2;
scrubber.max = turns.length;
scrubber.value = index + 1;
scrubber.dir = rtl ? 'rtl' : 'ltr';
scrubber.setAttribute('aria-valuetext', scrolling ? 'Scroll view' : label);
for (const step of steps) { for (const step of steps) {
const target = index + Number(step.dataset.step); const target = index + Number(step.dataset.step);
step.disabled = scrolling || target < 0 || target >= turns.length; step.disabled = scrolling || target < 0 || target >= turns.length;
@@ -102,19 +127,19 @@
function stepBy(delta) { function stepBy(delta) {
const next = index + delta; const next = index + delta;
if (mode.value === 'scroll' || next < 0 || next >= turns.length) return; if (mode.value === 'scroll' || next < 0 || next >= turns.length) return;
pageMotion?.cancel();
index = next; index = next;
zoomResetScroll = true; zoomResetScroll = true;
render(); render();
if (turnable() && !reduceMotion.matches && typeof strip.animate === 'function') {
const direction = -nextSwipeSign * Math.sign(delta);
pageMotion = strip.animate([
{ transform: 'translateX(' + (direction * 26) + 'px)', opacity: .72 },
{ transform: 'translateX(0)', opacity: 1 },
], {duration: 175, easing: 'cubic-bezier(.2,.7,.28,1)'});
}
} }
scrubber.addEventListener('input', () => stepBy(Number(scrubber.value) - 1 - index));
reader.querySelector('[data-reader-reactions]').addEventListener('change', event => {
reader.classList.toggle('show-reader-reactions', event.target.checked);
});
document.addEventListener('pointerdown', event => {
if (settings.open && !settings.contains(event.target)) settings.open = false;
});
let gesture = null; let gesture = null;
let lastTurn = -Infinity; let lastTurn = -Infinity;
const interactive = target => target.closest('a,button,input,select,textarea,summary,[contenteditable]'); const interactive = target => target.closest('a,button,input,select,textarea,summary,[contenteditable]');
@@ -145,7 +170,13 @@
if (performance.now() - lastTurn < 220) { if (performance.now() - lastTurn < 220) {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
return;
} }
if (!turnable() || interactive(event.target) || event.detail === 0) return;
const bounds = viewport.getBoundingClientRect();
const ratio = (event.clientX - bounds.left) / bounds.width;
if (ratio < .24) stepBy(rtl ? 1 : -1);
else if (ratio > .76) stepBy(rtl ? -1 : 1);
}, true); }, true);
function revealHash(scroll) { function revealHash(scroll) {
@@ -158,12 +189,11 @@
} }
mode.addEventListener('change', () => { mode.addEventListener('change', () => {
pageMotion?.cancel();
const current = turns[index]; const current = turns[index];
// When leaving scroll, keep the artwork nearest the top of the viewport. // When leaving scroll, keep the artwork nearest the top of the viewport.
const currentPage = [...frames].flatMap((f) => f.pages)
.find((page) => page.getBoundingClientRect().bottom > viewport.getBoundingClientRect().top + 16);
const wasScroll = reader.dataset.mode === 'scroll'; const wasScroll = reader.dataset.mode === 'scroll';
const currentPage = wasScroll && frames.flatMap((f) => f.pages)
.find((page) => page.getBoundingClientRect().bottom > Math.max(0, viewport.getBoundingClientRect().top) + 16);
turns = makeTurns(); turns = makeTurns();
const id = (wasScroll ? currentPage : current.pages[0])?.id || const id = (wasScroll ? currentPage : current.pages[0])?.id ||
(current.frame.kind === 'cover' ? 'chapter-cover' : ''); (current.frame.kind === 'cover' ? 'chapter-cover' : '');
@@ -211,7 +241,7 @@
document.body.classList.remove('reader-lock'); document.body.classList.remove('reader-lock');
for (const element of inerted.splice(0)) element.inert = false; for (const element of inerted.splice(0)) element.inert = false;
fullscreenLabel(); fullscreenLabel();
fullscreenButton.focus({preventScroll: true}); settings.querySelector('summary').focus({preventScroll: true});
} }
async function closeFullscreen() { async function closeFullscreen() {
if (reader.classList.contains('reading-immersive')) closeImmersive(); if (reader.classList.contains('reading-immersive')) closeImmersive();
@@ -220,6 +250,7 @@
} }
} }
fullscreenButton.addEventListener('click', async () => { fullscreenButton.addEventListener('click', async () => {
settings.open = false;
if (active()) { if (active()) {
await closeFullscreen(); await closeFullscreen();
return; return;
@@ -253,7 +284,11 @@
document.addEventListener('fullscreenchange', fullscreenLabel); document.addEventListener('fullscreenchange', fullscreenLabel);
document.addEventListener('webkitfullscreenchange', fullscreenLabel); document.addEventListener('webkitfullscreenchange', fullscreenLabel);
document.addEventListener('keydown', (event) => { document.addEventListener('keydown', (event) => {
if (event.key === 'Escape' && !finish?.open) closeImmersive(); if (event.key !== 'Escape' || finish?.open) return;
if (settings.open) {
settings.open = false;
settings.querySelector('summary').focus();
} else closeImmersive();
}); });
reader.querySelector('a[href="#discussion"]').addEventListener('click', async (event) => { reader.querySelector('a[href="#discussion"]').addEventListener('click', async (event) => {
if (!active()) return; if (!active()) return;
@@ -267,5 +302,7 @@
revealHash(false); revealHash(false);
render(); render();
reader.querySelector('[data-reader-tools]').hidden = false; reader.querySelector('[data-reader-tools]').hidden = false;
settings.hidden = false;
requestAnimationFrame(fitFullscreen);
if (findTurn(hashId()) >= 0) requestAnimationFrame(() => revealHash(true)); if (findTurn(hashId()) >= 0) requestAnimationFrame(() => revealHash(true));
})(); })();
+33
View File
@@ -0,0 +1,33 @@
.shop-grid .member-plan-with-art {
position: relative;
isolation: isolate;
overflow: hidden;
background: #121928;
color: #fff;
}
.shop-grid .member-plan-with-art > .member-plan-art,
.shop-grid .member-plan-with-art::before {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
pointer-events: none;
}
.shop-grid .member-plan-with-art > .member-plan-art {
display: block;
object-fit: cover;
opacity: .65;
z-index: -2;
}
.shop-grid .member-plan-with-art::before {
content: "";
background: linear-gradient(90deg, rgb(9 14 25 / .78), rgb(9 14 25 / .44));
z-index: -1;
}
.shop-grid .member-plan-with-art .member-plan-copy h2,
.shop-grid .member-plan-with-art .member-plan-copy p {
color: #fff;
}
.plan-comparison{width:100%;border-collapse:collapse;text-align:left}
.plan-comparison caption{text-align:left;padding:.5rem}
.plan-comparison :is(th,td){border-bottom:1px solid currentColor;padding:.65rem;text-align:left}
+11 -1
View File
@@ -19,7 +19,17 @@
open(link); open(link);
}); });
} }
dialog.addEventListener('close', () => { trigger?.focus(); trigger = undefined; }); dialog.addEventListener('close', () => {
trigger?.focus();
trigger = undefined;
const membership = document.querySelector('[data-membership-popup]');
if (!membership || document.querySelector('dialog[open]')) return;
try {
if (sessionStorage.getItem('slx-membership-popup-seen')) return;
sessionStorage.setItem('slx-membership-popup-seen', '1');
membership.showModal();
} catch {}
});
if (dialog.hasAttribute('data-auto-open')) { if (dialog.hasAttribute('data-auto-open')) {
setTimeout(() => { setTimeout(() => {
try { try {
+2 -1
View File
@@ -64,7 +64,7 @@ footer{background:var(--slx-footer,var(--brand-navy));color:var(--slx-footer-ink
.reading-heading,.reading-tools{background:var(--slx-reader-bar,#161f30);color:var(--slx-reader-ink,#eff4ff);border-color:var(--rule)} .reading-heading,.reading-tools{background:var(--slx-reader-bar,#161f30);color:var(--slx-reader-ink,#eff4ff);border-color:var(--rule)}
.reading-frame figure figcaption{color:var(--slx-reader-ink,#eff4ff);background:transparent} .reading-frame figure figcaption{color:var(--slx-reader-ink,#eff4ff);background:transparent}
.reading-tools button,.reading-view select{background:var(--control);border-color:var(--control-rule);color:var(--slx-reader-ink,#eff4ff)} .reading-tools button,.reading-view select{background:var(--control);border-color:var(--control-rule);color:var(--slx-reader-ink,#eff4ff)}
.reading-tools .reading-fullscreen[aria-pressed=true]{border-color:var(--brand-yellow);color:var(--brand-yellow)} .reading-settings .reading-fullscreen[aria-pressed=true]{border-color:var(--brand-yellow);color:var(--brand-yellow)}
/* Compact rank tags and manga speech balloons. */ /* Compact rank tags and manga speech balloons. */
.rank-badge{display:inline-block;border-radius:4px;padding:.13em .5em;font-size:.72rem;line-height:1.48;font-weight:900; .rank-badge{display:inline-block;border-radius:4px;padding:.13em .5em;font-size:.72rem;line-height:1.48;font-weight:900;
@@ -242,3 +242,4 @@ body.has-page-background .live-hero{background:var(--slx-live,transparent)}
.newsletter-popup .newsletter-consent .slx-word-land{color:#ae152c} .newsletter-popup .newsletter-consent .slx-word-land{color:#ae152c}
.newsletter-popup [data-newsletter-status]{padding:.7rem .9rem;border-radius:.4rem;background:#eff3f8;color:#202c43} .newsletter-popup [data-newsletter-status]{padding:.7rem .9rem;border-radius:.4rem;background:#eff3f8;color:#202c43}
.newsletter-popup-actions{display:flex;align-items:center;gap:.55rem 1rem;flex-wrap:wrap;margin-top:1rem;padding-top:1rem;border-top:1px solid #dfe0e6} .newsletter-popup-actions{display:flex;align-items:center;gap:.55rem 1rem;flex-wrap:wrap;margin-top:1rem;padding-top:1rem;border-top:1px solid #dfe0e6}
.shop-stripe-form{margin:0 0 .45rem}
Binary file not shown.

After

Width:  |  Height:  |  Size: 347 KiB

+10
View File
@@ -0,0 +1,10 @@
.slx-store{--store-ink:#122442;--store-paper:#fff;--store-card:#f1f3f7;color:var(--store-ink);background:var(--store-paper);max-width:76rem;margin:1.5rem auto;padding:clamp(.75rem,3vw,2rem)}
.slx-store a{color:inherit}.store-bar{display:flex;justify-content:space-between;gap:1rem;padding:.4rem 0}
.store-banner{text-align:center;background:var(--store-card);padding:1rem;margin:.5rem 0}
.store-banner h1,.store-detail h1{margin:.3rem 0}.store-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:.5rem}
.store-card{background:var(--store-card);text-align:center;padding:.65rem;display:flex;flex-direction:column;align-items:center;gap:.35rem;min-width:0}
.store-card h2{font-size:1rem;margin:0;line-height:1.25}.store-stock{font-size:.85rem;margin:auto 0 0;padding-top:.35rem}.store-cover{width:100%;display:grid;place-items:center;aspect-ratio:3/4;overflow:hidden;background:#e5e9f2}.store-cover img{width:100%;height:100%;object-fit:contain}
.store-card form{width:100%;margin:0}.slx-store .store-button{display:inline-block;color:#fff;background:#092951;border:0;border-radius:.2rem;padding:.4rem .75rem;cursor:pointer;font:inherit;text-decoration:none}.store-card .store-button{width:100%}
.store-detail{display:grid;grid-template-columns:minmax(9rem,1fr) minmax(13rem,1.8fr) minmax(8rem,1fr);gap:1.5rem;align-items:start;margin:1rem 0 2rem}
.store-product-info form{display:flex;flex-wrap:wrap;gap:.5rem;align-items:center}.store-product-info input[type=number]{width:4rem}.store-price{font-size:1.35rem;font-weight:800}.store-format{padding:1rem;background:var(--store-card)}.store-format h2{font-size:1rem;margin:0}.store-section>h2{border-bottom:1px solid #092951;padding-bottom:.3rem}.store-sample details{margin:.5rem 0}.store-sample summary{cursor:pointer;font-weight:700}.store-sample img{display:block;max-width:min(100%,42rem);height:auto;margin:.5rem auto}
@media(max-width:720px){.store-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.store-detail{grid-template-columns:minmax(7rem,1fr) minmax(0,1.5fr);gap:.75rem}.store-format{grid-column:1/-1}}
+24
View File
@@ -0,0 +1,24 @@
document.addEventListener('DOMContentLoaded', () => {
const map = document.querySelector('[data-studio-map-picker]');
const pin = document.querySelector('[data-studio-map-pin]');
const x = document.getElementById('id_x');
const y = document.getElementById('id_y');
if (!map || !pin || !x || !y) return;
const refresh = () => {
pin.hidden = ![x, y].every(field => field.value !== '' && Number(field.value) >= 0 && Number(field.value) <= 100);
if (!pin.hidden) {
pin.style.left = x.value + '%';
pin.style.top = y.value + '%';
}
};
map.addEventListener('click', event => {
const box = map.getBoundingClientRect();
const percent = (value, size) => Math.max(0, Math.min(100, 100 * value / size)).toFixed(5);
x.value = percent(event.clientX - box.left, box.width);
y.value = percent(event.clientY - box.top, box.height);
refresh();
});
x.addEventListener('input', refresh);
y.addEventListener('input', refresh);
refresh();
});
+61
View File
@@ -0,0 +1,61 @@
.slx-world-map,.slx-world-resources{position:relative;max-width:72rem;margin:2rem auto;padding:1rem;box-sizing:border-box}
.slx-world-map h2{margin:.25rem 0}
.slx-world-stage{position:relative;isolation:isolate}
.slx-world-stage img{display:block;width:100%;height:auto;border:0;filter:none;opacity:1}
.slx-world-marker{position:absolute;left:var(--x);top:var(--y);transform:translate(-50%,-50%);width:clamp(25px,4vw,44px);aspect-ratio:1;display:grid;place-items:center;border-radius:50%;color:#ffe141}
.slx-world-marker::before,.slx-world-marker::after{content:"";grid-area:1/1;border:2px solid currentColor;border-radius:50%;width:48%;aspect-ratio:1;box-shadow:0 0 4px #161009;pointer-events:none}
.slx-world-marker::after{animation:slx-map-scan 2.4s ease-out infinite}
.slx-world-marker:nth-of-type(even)::after{animation-delay:-1.2s}
.slx-world-marker:is(:hover,:focus-visible,[aria-current])::before{width:75%;border-width:3px}
.slx-world-marker:focus-visible{outline:2px solid currentColor;outline-offset:1px}
.slx-world-directory{display:flex;flex-wrap:wrap;gap:.4rem .85rem;list-style:none;margin:1rem 0 0;padding:0}
.slx-world-directory a{display:inline-block;padding:.3rem 0;text-decoration:underline}
.slx-world-resources{display:grid;gap:.65rem;grid-template-columns:repeat(auto-fit,minmax(min(100%,12rem),1fr))}
[id^="map-"]{scroll-margin-top:6rem}
[id^="map-"]:target{outline:2px solid #dfb900;outline-offset:3px}
@keyframes slx-map-scan{from{transform:scale(1);opacity:.9}to{transform:scale(1.8);opacity:0}}
@media(prefers-reduced-motion:reduce){.slx-world-marker::after{animation:none;display:none}}
.slx-world-stage{container-type:inline-size}
.slx-world-marker .slx-map-label{position:absolute;top:calc(50% + clamp(7px,1.1cqw,13px));left:50%;transform:translateX(-50%);display:grid;justify-items:center;gap:.2rem;width:max-content;max-width:21cqw;font-size:clamp(4px,1.05cqw,12px);padding:.2rem .3rem;background:#101522ed;border-radius:.3em;line-height:1}
.slx-world-marker[data-map-destination="cart"] .slx-map-label{left:calc(50% + 2.8cqw);transform:translateX(-100%)}
.slx-world-marker[data-map-destination="start"] .slx-map-label{left:calc(50% - 8.2cqw);transform:none}
.djinn-sol-word{display:inline-flex;align-items:center;gap:.11em}
.slx-world-stage img.djinn-sol-glyph{width:.62em;height:.81em;object-fit:contain;image-rendering:pixelated}
.slx-world-marker .djinn-sol-spelling{display:flex;gap:.28em;justify-content:center;flex-wrap:wrap}
.slx-map-english{color:#fff;font-size:clamp(9px,1.25cqw,14px);font-weight:700;text-align:center;line-height:1.1;text-wrap:balance}
.slx-world-marker:is(:hover,:focus-visible){z-index:2}
.slx-world-marker[data-map-destination="start"] .slx-map-label{left:calc(50% - 8.2cqw)}
@container (max-width: 540px){
.slx-world-marker[data-map-destination="newsletter"] .slx-map-label{left:calc(50% - 10cqw);transform:none}
.slx-world-marker[data-map-destination="library"] .slx-map-label{left:calc(50% + 6cqw);transform:none}
}
body.map-landing{margin:0;min-height:100svh;display:flex;flex-direction:column;background:#090e1a}
.map-landing .slx-page-backdrop{display:none}
.map-landing .site-header{flex:none}
.map-landing-main{flex:1;display:flex;flex-direction:column;min-width:0}
.map-landing .slx-world-map{flex:1;display:flex;flex-direction:column;width:100%;max-width:none;margin:0;padding:0;color:#f5f7ff}
.slx-map-controls{display:flex;align-items:center;justify-content:space-between;gap:.6rem;padding:.45rem 1rem}
.slx-map-controls h1{font-size:clamp(1rem,3vw,1.6rem);margin:0;color:inherit}
.slx-map-controls button,.slx-map-list summary{color:#f5f7ff;background:#192339;border:1px solid #61708b;border-radius:.35rem;padding:.3rem .6rem;cursor:pointer}
.slx-map-controls button[aria-pressed="false"]{opacity:.72}
.slx-map-viewport{flex:1;display:grid;place-items:center;min-width:0;container-type:inline-size}
.map-landing .slx-world-stage{width:min(100cqw,140svh);margin:auto}
.slx-map-list{padding:.35rem 1rem}
.slx-map-list summary{width:max-content}
.slx-map-list a{color:#fff}
@media(min-aspect-ratio: 4/3){.map-landing .slx-world-stage{width:min(100cqw,calc((100svh - 9rem) * 1.7504))}}
body.map-landing{height:100svh}
.map-landing .slx-map-viewport{container-type:size;min-height:10rem}
.map-landing .slx-world-stage{width:min(100cqw,175.04cqh)}
.map-landing .slx-map-list[open] .slx-world-directory{max-height:26svh;overflow:auto}
.slx-world-stage .slx-map-avatar{width:auto;height:clamp(39px,7cqw,77px);position:absolute;z-index:5;transform:translate(-50%,-94%);pointer-events:none;filter:drop-shadow(0 0 5px #b3eaff) drop-shadow(0 0 10px #3387ff);image-rendering:pixelated}
.slx-world-stage .slx-map-avatar[hidden]{display:none}
.slx-world-stage.has-avatar-pointer,.slx-world-stage.has-avatar-pointer .slx-world-marker{cursor:none}
.slx-world-marker{background:radial-gradient(circle at center,#e22118 0 3px,transparent 4px)}
.countdown-showcase .slx-world-map{position:relative;isolation:isolate;color:#f5f7ff;background:#090e1a;border-radius:1rem}
/* The embedded map takes its size from its image, not a fixed viewport. */
.countdown-showcase .slx-map-viewport{display:block;width:100%;container-type:normal}
.countdown-showcase .slx-world-stage{width:100%;aspect-ratio:2048 / 1170}
.countdown-showcase .slx-world-stage > img:first-child{width:100%;height:auto}
+78
View File
@@ -0,0 +1,78 @@
(() => {
const map = document.querySelector('.slx-world-map');
const Audio = window.AudioContext || window.webkitAudioContext;
if (!map) return;
const stage = map.querySelector('.slx-world-stage');
const standing = stage.querySelector('.slx-map-avatar:not(.slx-map-avatar-selected)');
const selected = stage.querySelector('.slx-map-avatar-selected');
if (!standing || !selected) return;
let landed = false;
const move = (x,y) => {
const avatar = landed ? selected : standing;
avatar.style.left = x;
avatar.style.top = y;
avatar.hidden = false;
};
stage.addEventListener('pointermove', event => {
if (landed || event.pointerType === 'touch') return;
const bounds = stage.getBoundingClientRect();
move(`${event.clientX-bounds.left}px`, `${event.clientY-bounds.top}px`);
stage.classList.add('has-avatar-pointer');
});
stage.addEventListener('pointerleave', () => {
standing.hidden = true;
stage.classList.remove('has-avatar-pointer');
});
addEventListener('pageshow', () => { landed = false; standing.hidden = selected.hidden = true; stage.classList.remove('has-avatar-pointer'); });
const toggle = map.querySelector('[data-map-sound]');
let enabled = true;
try { enabled = localStorage.getItem('slx-map-sound') !== 'off'; } catch {}
const reflect = () => toggle.setAttribute('aria-pressed', String(enabled));
reflect();
toggle.hidden = !Audio;
toggle.addEventListener('click', () => {
enabled = !enabled;
reflect();
try { localStorage.setItem('slx-map-sound', enabled ? 'on' : 'off'); } catch {}
});
let audio, navigating = false;
map.addEventListener('click', event => {
const link = event.target.closest('.slx-world-marker');
if (!link || event.defaultPrevented || event.button !== 0 ||
event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
event.preventDefault();
if (navigating) return;
navigating = true;
landed = true;
standing.hidden = true;
move(link.style.getPropertyValue('--x'), link.style.getPropertyValue('--y'));
let timeout;
const go = () => {
if (!navigating) return;
clearTimeout(timeout);
navigating = false;
location.assign(link.href);
};
timeout = setTimeout(go, enabled && Audio ? 420 : 280);
if (!enabled || !Audio) return;
try {
audio ||= new Audio();
audio.resume().then(() => {
if (!navigating) return;
const now = audio.currentTime;
const tone = audio.createOscillator();
const gain = audio.createGain();
tone.frequency.setValueAtTime(1090, now);
tone.frequency.exponentialRampToValueAtTime(510, now + .12);
gain.gain.setValueAtTime(.001, now);
gain.gain.exponentialRampToValueAtTime(.17, now + .014);
gain.gain.exponentialRampToValueAtTime(.001, now + .14);
tone.connect(gain).connect(audio.destination);
tone.onended = () => setTimeout(go, 130);
tone.start(now);
tone.stop(now + .15);
}).catch(() => {});
} catch { /* The navigation timer still runs without audio. */ }
});
})();
@@ -0,0 +1,10 @@
{% extends "admin/change_form.html" %}
{% load static %}
{% block after_field_sets %}
<h2>Place the marker</h2>
<p>Click or tap the map to set the position, or enter X and Y above as percentages.</p>
<div style="position:relative;max-width:900px">
<img data-studio-map-picker src="{% static 'solterra-map.jpg' %}" width="2048" height="1170" alt="Sol’Terra map" style="display:block;width:100%;height:auto;cursor:crosshair">
<span data-studio-map-pin aria-hidden="true" hidden style="position:absolute;width:16px;height:16px;border:3px solid #ffde31;border-radius:50%;background:#ad1414;transform:translate(-50%,-50%);pointer-events:none"></span>
</div>
{% endblock %}
+1 -1
View File
@@ -3,7 +3,7 @@
{% block breadcrumbs %}<div class="breadcrumbs"><a href="{% url 'admin:index' %}">Studio</a> &rsaquo; Homepage Countdown</div>{% endblock %} {% block breadcrumbs %}<div class="breadcrumbs"><a href="{% url 'admin:index' %}">Studio</a> &rsaquo; Homepage Countdown</div>{% endblock %}
{% block content %} {% block content %}
<section class="studio-content-panel studio-timer"> <section class="studio-content-panel studio-timer">
<p>Show the timer beneath your hero or switch to a dedicated cover landing page. Both display your released chapters first. This does not change the separate Coming Soon page or schedule any chapters.</p> <p>Enable the countdown cover landing and upload a cover to combine it with the Sol’Terra map. Choose whether the map appears above or below the countdown content.</p>
<form method="post" enctype="multipart/form-data">{% csrf_token %} <form method="post" enctype="multipart/form-data">{% csrf_token %}
{{ form.non_field_errors }} {{ form.non_field_errors }}
{% for hidden in form.hidden_fields %}{{ hidden }}{% endfor %} {% for hidden in form.hidden_fields %}{{ hidden }}{% endfor %}
+29 -1
View File
@@ -15,7 +15,7 @@
</div> </div>
<section class="traffic-panel" aria-labelledby="traffic-map-heading"> <section class="traffic-panel" aria-labelledby="traffic-map-heading">
<h2 id="traffic-map-heading">Where readers are</h2> <h2 id="traffic-map-heading">Where readers are</h2>
{% if not geo_configured %}<p>Connect a GeoLite Country database to locate new visits by country. Earlier and unresolved visits appear as Unknown.</p>{% endif %} {% if not geo_configured %}<p>Connect a GeoLite2 City database to locate new visits by country. Earlier and unresolved visits appear as Unknown.</p>{% endif %}
<div data-world-map data-map-url="{% static 'world-countries.json' %}"></div> <div data-world-map data-map-url="{% static 'world-countries.json' %}"></div>
<p data-map-status aria-live="polite">Select a highlighted country to see its pageviews.</p> <p data-map-status aria-live="polite">Select a highlighted country to see its pageviews.</p>
{{ countries|json_script:"country-traffic" }} {{ countries|json_script:"country-traffic" }}
@@ -24,6 +24,34 @@
</tbody></table><small>Map boundaries: Natural Earth. Location is approximate.</small> </tbody></table><small>Map boundaries: Natural Earth. Location is approximate.</small>
</section> </section>
<div class="traffic-grid"> <div class="traffic-grid">
<section class="traffic-panel">
<h2>Regions and states</h2>
<table class="traffic-table">
<thead><tr><th scope="col">Country</th><th scope="col">Region / State</th><th scope="col">Views</th></tr></thead>
<tbody>
{% for row in regions %}
<tr><td>{{ row.country|default:'Unknown' }}</td><td>{{ row.region|default:'Unknown' }}</td><td>{{ row.views }}</td></tr>
{% empty %}
<tr><td colspan="3">No region data available yet.</td></tr>
{% endfor %}
</tbody>
</table>
</section>
<section class="traffic-panel">
<h2>Cities</h2>
<table class="traffic-table">
<thead><tr><th scope="col">City</th><th scope="col">Region</th><th scope="col">Country</th><th scope="col">Views</th></tr></thead>
<tbody>
{% for row in cities %}
<tr><td>{{ row.city|default:'Unknown' }}</td><td>{{ row.region|default:'Unknown' }}</td><td>{{ row.country|default:'Unknown' }}</td><td>{{ row.views }}</td></tr>
{% empty %}
<tr><td colspan="4">No city data available yet.</td></tr>
{% endfor %}
</tbody>
</table>
</section>
</div>
<div class="traffic-grid">
<section class="traffic-panel"><h2>Traffic sources</h2><p>Referring origins only. Direct visits and missing referrers are grouped together.</p> <section class="traffic-panel"><h2>Traffic sources</h2><p>Referring origins only. Direct visits and missing referrers are grouped together.</p>
<table class="traffic-table"><thead><tr><th scope="col">Source</th><th scope="col">Views</th></tr></thead><tbody> <table class="traffic-table"><thead><tr><th scope="col">Source</th><th scope="col">Views</th></tr></thead><tbody>
{% for row in sources %}<tr><td>{% if row.source == 'internal' %}SLX site{% elif row.source %}<a href="{{ row.source }}" rel="noreferrer noopener" target="_blank">{{ row.source }}</a>{% else %}Direct / unavailable{% endif %}</td><td>{{ row.views }}</td></tr>{% empty %}<tr><td colspan="2">No sources in this range yet.</td></tr>{% endfor %} {% for row in sources %}<tr><td>{% if row.source == 'internal' %}SLX site{% elif row.source %}<a href="{{ row.source }}" rel="noreferrer noopener" target="_blank">{{ row.source }}</a>{% else %}Direct / unavailable{% endif %}</td><td>{{ row.views }}</td></tr>{% empty %}<tr><td colspan="2">No sources in this range yet.</td></tr>{% endfor %}
+15
View File
@@ -0,0 +1,15 @@
{% load static %}
<link rel="stylesheet" href="{% static 'manaa-reader.css' %}">
<dialog class="chapter-finish" data-archive-reminder aria-labelledby="archive-reminder-title">
<div class="chapter-finish-card"><div>
<p class="kicker">Slump X Land Monthly</p>
<h2 id="archive-reminder-title">Read the entire archive</h2>
<p>The newest three chapters are free to read in full. Create an account and join Slump X Land Monthly to unlock every chapter, new and old, as they’re published.</p>
<div class="actions">
<a class="cta" href="{% url 'fan-signup' %}">Create an account</a>
<a class="cta secondary" href="{% url 'membership' %}">See monthly plans</a>
<a href="{% url 'fan-login' %}">Sign in</a>
<form method="dialog"><button class="fan-button" autofocus>Keep browsing</button></form>
</div></div></div>
</dialog>
<script defer src="{% static 'archive-reminder.js' %}"></script>
+16 -3
View File
@@ -1,4 +1,4 @@
{% load static slx_brand share_meta %}<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"><title>{% block title %}SLUMP X LAND · Official{% endblock %}</title>{% share_metadata %}{% block meta %}{% endblock %}<link rel="stylesheet" href="{% static 'brand.css' %}"><link rel="stylesheet" href="{% static 'site.css' %}"><script defer src="{% static 'countdown.js' %}"></script>{% block scripts %}{% endblock %}<link rel="stylesheet" href="{% static 'site-theme.css' %}">{% if floating_top_art or floating_bottom_art %}<script defer src="{% static 'floating-artwork.js' %}"></script>{% endif %}{% if newsletter_popup_form %}<script defer src="{% static 'newsletter-popup.js' %}"></script>{% endif %}</head><body{% if page_backdrop %} class="has-page-background"{% endif %}{% if site_theme_vars or page_backdrop %} style="{{ site_theme_vars }}{% if page_backdrop %};--slx-page-color:{{ page_backdrop.color }};--slx-page-tint:{{ page_tint }}%{% endif %}"{% endif %}> {% load static slx_brand share_meta %}<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"><title>{% block title %}SLUMP X LAND · Official{% endblock %}</title>{% share_metadata %}{% block meta %}{% endblock %}<link rel="stylesheet" href="{% static 'brand.css' %}"><link rel="stylesheet" href="{% static 'site.css' %}"><script defer src="{% static 'countdown.js' %}"></script><link rel="stylesheet" href="{% static 'djinnii.css' %}">{% block scripts %}{% endblock %}<link rel="stylesheet" href="{% static 'site-theme.css' %}">{% if floating_top_art or floating_bottom_art %}<script defer src="{% static 'floating-artwork.js' %}"></script>{% endif %}{% if newsletter_popup_form %}<script defer src="{% static 'newsletter-popup.js' %}"></script>{% endif %}</head><body class="{% if page_backdrop %}has-page-background{% endif %}{% block body_class %}{% endblock %}"{% if site_theme_vars or page_backdrop %} style="{{ site_theme_vars }}{% if page_backdrop %};--slx-page-color:{{ page_backdrop.color }};--slx-page-tint:{{ page_tint }}%{% endif %}"{% endif %}>
{% if page_backdrop %} {% if page_backdrop %}
<div class="slx-page-backdrop" aria-hidden="true"> <div class="slx-page-backdrop" aria-hidden="true">
{% if page_backdrop.art %}<img src="{{ page_backdrop.art.url }}" alt="" decoding="async"><span></span>{% endif %} {% if page_backdrop.art %}<img src="{{ page_backdrop.art.url }}" alt="" decoding="async"><span></span>{% endif %}
@@ -11,12 +11,25 @@
{% for tab in public_menu %} {% for tab in public_menu %}
<a href="{{ tab.url }}"{% if tab.active %} aria-current="page"{% endif %}{% if tab.key == 'notices' %} aria-label="{{ tab.label }}{% if fan_unread %} ({{ fan_unread }} unread){% endif %}"{% endif %}>{% if tab.key == 'notices' %}♢{% if fan_unread %} <span class="notice-count">{{ fan_unread }}</span>{% endif %}{% else %}{{ tab.label }}{% endif %}</a> <a href="{{ tab.url }}"{% if tab.active %} aria-current="page"{% endif %}{% if tab.key == 'notices' %} aria-label="{{ tab.label }}{% if fan_unread %} ({{ fan_unread }} unread){% endif %}"{% endif %}>{% if tab.key == 'notices' %}♢{% if fan_unread %} <span class="notice-count">{{ fan_unread }}</span>{% endif %}{% else %}{{ tab.label }}{% endif %}</a>
{% endfor %} {% endfor %}
<a href="{% url 'djinnii' %}"{% if request.resolver_match.url_name == 'djinnii' %} aria-current="page"{% endif %}>Djinnii</a>
</nav> </nav>
</header> </header>
{% endblock %} {% endblock %}
{% block floating_top %}{% include 'floating-artwork.html' with band=floating_top_art position='top' only %}{% endblock %} {% block floating_top %}{% include 'floating-artwork.html' with band=floating_top_art position='top' only %}{% endblock %}
{% block content %}{% endblock %} {% block content %}{% endblock %}
{% include 'floating-artwork.html' with band=floating_bottom_art position='bottom' only %} {% block floating_bottom %}{% include 'floating-artwork.html' with band=floating_bottom_art position='bottom' only %}{% endblock %}
{% block footer %}<footer>{{ "SLUMP X LAND"|slx_brand }} <span class="footer-separator">·</span> The official ManaA site{% if newsletter_signup_open %} <span class="footer-separator">·</span> <a href="{% url 'newsletter-signup' %}" data-newsletter-open>Newsletter</a>{% endif %}</footer>{% endblock %} {% block footer %}<footer>{{ "SLUMP X LAND"|slx_brand }} <span class="footer-separator">·</span> The official ManaA site{% if newsletter_signup_open %} <span class="footer-separator">·</span> <a href="{% url 'newsletter-signup' %}" data-newsletter-open>Newsletter</a>{% endif %}</footer>{% endblock %}
{% if newsletter_popup_form %}{% include 'newsletter/popup.html' %}{% endif %} {% block popups %}{% if newsletter_popup_form %}{% include 'newsletter/popup.html' %}
{% if settings.membership_popup and request.resolver_match.url_name == 'home' %}
<dialog class="newsletter-popup" data-membership-popup aria-labelledby="membership-popup-title">
<div class="newsletter-popup-hero"><form method="dialog"><button class="newsletter-popup-close" autofocus aria-label="Close membership">×</button></form>
<p class="kicker">MEMBER EDITION</p><h2 id="membership-popup-title">Slump X Land Monthly</h2>
<p>Read early chapters and see select draft pages from the studio.</p>
</div>
<div class="newsletter-popup-body"><a class="read-manaa" href="{% url 'membership' %}">Explore membership →</a></div>
</dialog>
{% endif %}{% endif %}{% endblock %}
{% if not user.is_authenticated and request.resolver_match.url_name == 'chapters' or not user.is_authenticated and request.resolver_match.url_name == 'chapter' %}
{% include 'archive-reminder.html' %}
{% endif %}
</body></html> </body></html>
+11 -3
View File
@@ -30,14 +30,22 @@
<section class="shop-option" data-variant-panel="{{ variant.pk }}"> <section class="shop-option" data-variant-panel="{{ variant.pk }}">
{% include 'shop-image.html' with primary=variant.art fallback=product.cover title=product.title only %} {% include 'shop-image.html' with primary=variant.art fallback=product.cover title=product.title only %}
<p class="shop-format">{{ variant }}{% if variant.price_usd != None %} <span>· ${{ variant.price_usd|floatformat:"2" }}</span>{% endif %}</p> <p class="shop-format">{{ variant }}{% if variant.price_usd != None %} <span>· ${{ variant.price_usd|floatformat:"2" }}</span>{% endif %}</p>
<a class="cta" href="{{ variant.paypal_url }}">Buy {{ variant.get_format_display }} on PayPal →</a> {% if stripe_shop_ready and variant.price_usd >= 0.50 %}
{% include 'shop-stripe-button.html' with product_id=product.pk variant_id=variant.pk %}
{% endif %}
{% if variant.paypal_url %}<a class="cta secondary" href="{{ variant.paypal_url }}">Buy {{ variant.get_format_display }} on PayPal →</a>
{% elif not stripe_shop_ready or not variant.price_usd or variant.price_usd < 0.50 %}<p class="shop-format">Currently unavailable</p>{% endif %}
</section> </section>
{% endfor %} {% endfor %}
{% else %} {% else %}
<section class="shop-option"> <section class="shop-option">
{% include 'shop-image.html' with primary=product.cover title=product.title only %} {% include 'shop-image.html' with primary=product.cover title=product.title only %}
{% if product.legacy_checkout %}<a class="cta" href="{{ product.legacy_checkout }}">Buy on PayPal →</a> {% if not product.variants.exists and stripe_shop_ready and product.price_usd >= 0.50 %}
{% else %}<p class="shop-format">Currently unavailable</p>{% endif %} <p class="shop-format">${{ product.price_usd|floatformat:"2" }}</p>
{% include 'shop-stripe-button.html' with product_id=product.pk variant_id=0 %}
{% endif %}
{% if product.legacy_checkout %}<a class="cta secondary" href="{{ product.legacy_checkout }}">Buy on PayPal →</a>
{% elif product.variants.exists or not stripe_shop_ready or not product.price_usd or product.price_usd < 0.50 %}<p class="shop-format">Currently unavailable</p>{% endif %}
</section> </section>
{% endif %} {% endif %}
</article> </article>
+6
View File
@@ -0,0 +1,6 @@
{% if chapter.price_usd >= 0.50 and stripe_enabled %}
{% if user.is_authenticated %}<form method="post" action="{% url 'buy-chapter' chapter.number %}">{% csrf_token %}<button type="submit" class="cta">Buy digital chapter · ${{ chapter.price_usd|floatformat:2 }}</button></form>
{% else %}<a class="cta" href="{% url 'fan-login' %}?next={% url 'chapter' chapter.number %}">Sign in to buy · ${{ chapter.price_usd|floatformat:2 }}</a>{% endif %}
{% endif %}
{% if physical_edition %}<a class="cta secondary" href="{% url 'shop-product' physical_edition.slug %}">Buy the physical book</a>{% endif %}
<a class="cta secondary" href="{% url 'membership' %}">Join Slump X Land’s Monthly Fan Club</a>
+1 -1
View File
@@ -1,2 +1,2 @@
{% load slx_brand %} {% load slx_brand %}
<div class="cards">{% for chapter in chapters %}<article class="card chapter-card"><a class="card-main" href="{% url 'chapter' chapter.number %}">{% if chapter.cover %}<img src="{{ chapter.cover.url }}" alt="" loading="lazy">{% endif %}<div><span class="kicker">#{{ chapter.number|stringformat:"03d" }}</span><h3>{{ chapter.title|slx_brand }}</h3><time datetime="{{ chapter.publish_at|date:'c' }}">{{ chapter.publish_at|date:"M j, Y" }}</time> {% if chapter.public_views != None %}{% include "view-eye.html" with views=chapter.public_views %}{% endif %}</div></a><div class="card-foot"><a href="{% url 'chapter-discussion' chapter.number %}#discussion">Fan discussion →</a></div></article>{% empty %}<p>{{ empty_text|default:"Chapters will appear here when they’re published." }}</p>{% endfor %}</div> <div class="cards">{% for chapter in chapters %}<article class="card chapter-card"><a class="card-main" href="{% url 'chapter' chapter.number %}">{% if chapter.search_cover %}<img src="{{ chapter.search_cover }}" alt="" loading="lazy">{% elif chapter.cover %}<img src="{{ chapter.cover.url }}" alt="" loading="lazy">{% endif %}<div><span class="kicker">#{{ chapter.number|stringformat:"03d" }}</span><h3>{{ chapter.title|slx_brand }}</h3>{% if show_archive_status %}<span class="badge">{% if chapter.pk in rolling_free_ids %}Free to read{% else %}Archive{% endif %}</span>{% endif %}<time datetime="{{ chapter.publish_at|date:'c' }}">{{ chapter.publish_at|date:"M j, Y" }}</time> {% if chapter.public_views != None %}{% include "view-eye.html" with views=chapter.public_views %}{% endif %}</div></a><div class="card-foot"><a href="{% url 'chapter-discussion' chapter.number %}#discussion">Fan discussion →</a></div></article>{% empty %}<p>{{ empty_text|default:"Chapters will appear here when they’re published." }}</p>{% endfor %}</div>
+1 -1
View File
@@ -1 +1 @@
{% if chapter.cover %}<figure id="chapter-cover" class="reactable-cover chapter-art"><img src="{{ chapter.cover.url }}" alt=""><figcaption>React to the chapter cover{% include 'reaction-strip.html' with group=cover_reactions reaction_for='React to chapter cover art' %}</figcaption></figure>{% endif %} {% if chapter.cover %}<figure id="chapter-cover" class="reactable-cover chapter-art"><img src="{{ chapter.cover.url }}" alt="Chapter cover" fetchpriority="high" decoding="async"><figcaption>React to the chapter cover{% include 'reaction-strip.html' with group=cover_reactions reaction_for='React to chapter cover art' %}</figcaption></figure>{% endif %}
+1
View File
@@ -21,6 +21,7 @@
{% else %}<a class="cta secondary" href="{% url 'chapters' %}">Chapter archive</a>{% endif %} {% else %}<a class="cta secondary" href="{% url 'chapters' %}">Chapter archive</a>{% endif %}
<form method="dialog"><button class="fan-button" type="submit">Back to page</button></form> <form method="dialog"><button class="fan-button" type="submit">Back to page</button></form>
</div> </div>
</div> </div>
</div> </div>
</dialog> </dialog>
+5 -11
View File
@@ -2,18 +2,12 @@
{% block title %}{{ chapter.title }} · SLUMP X LAND{% endblock %} {% block title %}{{ chapter.title }} · SLUMP X LAND{% endblock %}
{% block content %} {% block content %}
<main class="section article theme-shop"> <main class="section article theme-shop">
<p class="kicker">Chapter {{ chapter.number }} · Paid chapter</p><h1>{{ chapter.title|slx_brand }}</h1> <p class="kicker">#{{ chapter.number|stringformat:"03d" }} · Rolling archive</p>
<h1>{{ chapter.title|slx_brand }}</h1>
{% if chapter.cover %}<img class="book-cover" src="{{ chapter.cover.url }}" alt="">{% endif %} {% if chapter.cover %}<img class="book-cover" src="{{ chapter.cover.url }}" alt="">{% endif %}
{% if chapter.summary %}<p>{{ chapter.summary|slx_brand }}</p>{% endif %} {% if chapter.summary %}<p>{{ chapter.summary|slx_brand }}</p>{% endif %}
<p><strong>${{ chapter.price_usd|floatformat:2 }} USD</strong> · One-time purchase</p> <p>The newest three chapters are free. Sign in with an active Slump X Land Monthly membership to read the full archive.</p>
{% if paypal_ready %} <div class="actions">{% include 'chapter-access-actions.html' %}{% if not user.is_authenticated %}<a class="cta secondary" href="{% url 'fan-signup' %}">Create an account</a><a href="{% url 'fan-login' %}?next={% url 'chapter' chapter.number %}">Sign in</a>{% endif %}</div>
{% if user.is_authenticated %} <p><a href="{% url 'chapters' %}">See the latest free chapters →</a></p>
<form method="post" action="{% url 'paypal-start' chapter.number %}">{% csrf_token %}
<button class="cta" type="submit">Continue to PayPal →</button></form>
<p>PayPal will show the payment methods available to you.</p>
{% else %}<a class="cta" href="{% url 'fan-login' %}?next={% url 'chapter' chapter.number %}">Sign in to buy</a>
<p>New to SLX? <a href="{% url 'fan-signup' %}">Create a reader account</a>.</p>{% endif %}
{% else %}<p>Online checkout is currently unavailable.</p>{% endif %}
<p><a href="{% url 'chapter-discussion' chapter.number %}">Fan discussion</a> · <a href="{% url 'chapters' %}">All chapters</a></p>
</main> </main>
{% endblock %} {% endblock %}
+27 -12
View File
@@ -3,30 +3,34 @@
{% block content %}<main class="section reader manaa-reader"> {% block content %}<main class="section reader manaa-reader">
{% if frames %} {% if frames %}
<section class="reading-deck" data-reader data-direction="{{ chapter.reader_direction }}" aria-label="ManaA reader"> <section class="reading-deck" data-reader data-direction="{{ chapter.reader_direction }}" aria-label="ManaA reader">
<div class="reading-heading"><h1><span class="kicker">#{{ chapter.number|stringformat:"03d" }}</span> {{ chapter.title|slx_brand }}</h1>{% include "view-eye.html" with views=chapter.public_views %}<a href="#discussion">Discussion ↓</a></div> <div class="reading-heading">
<div class="reading-tools" data-reader-tools hidden> <a class="reading-icon" href="{% url 'chapters' %}" aria-label="Chapter archive">‹</a>
<button type="button" class="fan-button reading-fullscreen" data-fullscreen aria-pressed="false">⛶ Fullscreen</button> <h1><span class="kicker">#{{ chapter.number|stringformat:"03d" }}</span> {{ chapter.title|slx_brand }}</h1>
<div class="reading-move" aria-label="Page navigation"> <a class="reading-icon" href="#discussion" aria-label="Discussion" title="Discussion"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" aria-hidden="true"><path d="M4 4h16v12H9l-5 4z"/></svg></a>
<button type="button" class="fan-button" data-step="{% if chapter.reader_direction == 'rtl' %}1{% else %}-1{% endif %}" aria-label="{% if chapter.reader_direction == 'rtl' %}Next pages{% else %}Previous pages{% endif %}">←</button> <details class="reading-settings" data-reader-settings hidden>
<span data-page-output aria-live="polite"></span> <summary class="reading-icon" aria-label="Reading settings" title="Reading settings">⚙</summary>
<button type="button" class="fan-button" data-step="{% if chapter.reader_direction == 'rtl' %}-1{% else %}1{% endif %}" aria-label="{% if chapter.reader_direction == 'rtl' %}Previous pages{% else %}Next pages{% endif %}">→</button> <div class="reading-settings-panel">
</div> <label class="reading-view">Reading mode <select data-reader-mode>
<label class="reading-view">View <select data-reader-mode>
<option value="double" selected>Double page</option><option value="single">Single page</option><option value="scroll">Scroll</option> <option value="double" selected>Double page</option><option value="single">Single page</option><option value="scroll">Scroll</option>
</select></label> </select></label>
<small>{{ chapter.get_reader_direction_display }}</small>
<div class="reading-zoom" aria-label="Zoom controls"> <div class="reading-zoom" aria-label="Zoom controls">
<button type="button" class="fan-button" data-zoom="-1" aria-label="Zoom out">−</button> <button type="button" class="fan-button" data-zoom="-1" aria-label="Zoom out">−</button>
<button type="button" class="fan-button" data-zoom="0" aria-label="Reset zoom to fit">Fit</button> <button type="button" class="fan-button" data-zoom="0" aria-label="Reset zoom to fit">Fit</button>
<button type="button" class="fan-button" data-zoom="1" aria-label="Zoom in">+</button> <button type="button" class="fan-button" data-zoom="1" aria-label="Zoom in">+</button>
</div> </div>
<label><input type="checkbox" data-reader-reactions> Show page reactions</label>
<button type="button" class="fan-button reading-fullscreen" data-fullscreen aria-pressed="false">⛶ Fullscreen</button>
</div> </div>
<div class="reading-window" data-reader-window tabindex="0" aria-label="Chapter art. Swipe, drag horizontally, or use the arrow keys to turn fitted pages. Scroll or swipe to explore zoomed artwork."> </details>
</div>
<div class="reading-window" data-reader-window tabindex="0" aria-label="Chapter art. Tap an edge, swipe, or use the arrow keys to turn fitted pages. Scroll or swipe to explore zoomed artwork.">
<div class="reading-strip"> <div class="reading-strip">
{% for frame in frames %} {% for frame in frames %}
<div class="reading-frame frame-{{ frame.kind }}" data-frame="{{ frame.kind }}"> <div class="reading-frame frame-{{ frame.kind }}" data-frame="{{ frame.kind }}">
{% for page in frame.pages %} {% for page in frame.pages %}
<figure data-page data-number="{{ page.number }}" id="page-{{ page.number }}" class="reactable-page"> <figure data-page data-number="{{ page.number }}" id="page-{{ page.number }}" class="reactable-page">
<img src="{{ page.art.url }}" alt="{% if frame.kind == 'cover' %}Chapter cover{% elif frame.kind == 'spread' %}Double spread, page {{ page.number }}{% else %}Page {{ page.number }}{% endif %}" {% if not forloop.first or not forloop.parentloop.first %}loading="lazy"{% endif %} decoding="async"> <img src="{{ page.art.url }}" alt="{% if frame.kind == 'cover' %}Chapter cover{% elif frame.kind == 'spread' %}Double spread, page {{ page.number }}{% else %}Page {{ page.number }}{% endif %}" {% if not forloop.first or not forloop.parentloop.first %}loading="lazy"{% else %}fetchpriority="high"{% endif %} decoding="async">
<figcaption>{% if frame.kind == 'cover' %}Cover{% elif frame.kind == 'spread' %}Double spread · Page {{ page.number }}{% else %}Page {{ page.number }}{% endif %} <figcaption>{% if frame.kind == 'cover' %}Cover{% elif frame.kind == 'spread' %}Double spread · Page {{ page.number }}{% else %}Page {{ page.number }}{% endif %}
{% include 'reaction-strip.html' with group=page.reactions reaction_for='React to chapter page art' %}</figcaption> {% include 'reaction-strip.html' with group=page.reactions reaction_for='React to chapter page art' %}</figcaption>
</figure> </figure>
@@ -37,9 +41,20 @@
{% endfor %} {% endfor %}
<div data-reader-end aria-hidden="true"></div> <div data-reader-end aria-hidden="true"></div>
</div></div> </div></div>
<div class="reading-tools" data-reader-tools hidden>
<div class="reading-move" aria-label="Page navigation">
<button type="button" class="fan-button" data-step="{% if chapter.reader_direction == 'rtl' %}1{% else %}-1{% endif %}" aria-label="{% if chapter.reader_direction == 'rtl' %}Next pages{% else %}Previous pages{% endif %}">←</button>
<div class="reading-position">
<input type="range" min="1" max="1" value="1" data-reader-scrubber aria-label="Jump to a page or spread">
<span data-page-output aria-live="polite"></span>
</div>
<button type="button" class="fan-button" data-step="{% if chapter.reader_direction == 'rtl' %}-1{% else %}1{% endif %}" aria-label="{% if chapter.reader_direction == 'rtl' %}Previous pages{% else %}Next pages{% endif %}">→</button>
</div>
</div>
{% include 'chapter-finish.html' %} {% include 'chapter-finish.html' %}
</section> </section>
{% else %}<h1>{{ chapter.title|slx_brand }}</h1>{% include "view-eye.html" with views=chapter.public_views %}<p>No pages have been posted for this chapter yet.</p>{% endif %} {% else %}<h1>{{ chapter.title|slx_brand }}</h1><p>No pages have been posted for this chapter yet.</p>{% endif %}
<div class="reading-chapter-stats">{% include "view-eye.html" with views=chapter.public_views %}</div>
{% if chapter.summary %}<p>{{ chapter.summary|slx_brand }}</p>{% endif %} {% if chapter.summary %}<p>{{ chapter.summary|slx_brand }}</p>{% endif %}
<nav class="actions" aria-label="Chapter navigation"> <nav class="actions" aria-label="Chapter navigation">
{% if previous_chapter %}<a class="cta secondary" href="{% url 'chapter' previous_chapter.number %}">Previous chapter</a>{% endif %} {% if previous_chapter %}<a class="cta secondary" href="{% url 'chapter' previous_chapter.number %}">Previous chapter</a>{% endif %}
Loaded 100 of 125 files, more files were not shown because too many files have changed in this diff. Show more