-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgenerate.py
More file actions
5896 lines (4874 loc) · 267 KB
/
Copy pathgenerate.py
File metadata and controls
5896 lines (4874 loc) · 267 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import shutil
from jinja2 import Environment, FileSystemLoader
import markdown
import yaml
import re
import glob
from pathlib import Path
import hashlib
import base64
import json
import datetime
import argparse
from urllib.parse import urljoin, urlparse
from urllib.request import urlopen
from urllib.error import URLError, HTTPError
from bs4 import BeautifulSoup
# Lazy import for optional dependencies
EBOOKLIB_AVAILABLE = False
MINIFICATION_AVAILABLE = False
# Global flags for chapter inclusion
INCLUDE_DRAFTS = False
INCLUDE_SCHEDULED = False
def _check_ebooklib():
global EBOOKLIB_AVAILABLE
try:
import ebooklib
from ebooklib import epub
EBOOKLIB_AVAILABLE = True
return True
except ImportError:
EBOOKLIB_AVAILABLE = False
return False
def _check_minification():
global MINIFICATION_AVAILABLE
try:
import htmlmin
import rcssmin
import rjsmin
MINIFICATION_AVAILABLE = True
return True
except ImportError:
MINIFICATION_AVAILABLE = False
return False
BUILD_DIR = os.path.abspath("./build")
CONTENT_DIR = "./content"
PAGES_DIR = "./pages"
TEMPLATES_DIR = "./templates"
STATIC_DIR = "./static"
# Global template environment (will be enhanced with novel-specific support)
env = Environment(loader=FileSystemLoader(TEMPLATES_DIR))
# Global asset map for cache busting
ASSET_MAP = {}
def asset_url(filename):
"""Convert asset filename to cache-busted version if available"""
return ASSET_MAP.get(filename, filename)
# Register the asset_url filter
env.filters['asset_url'] = asset_url
# Cache for novel-specific template environments
_novel_template_envs = {}
def get_novel_template_directories(novel_slug):
"""Get list of template directories for a novel (novel-specific first, then defaults)"""
directories = []
# Novel-specific templates directory
novel_templates_dir = os.path.join(CONTENT_DIR, novel_slug, "templates")
if os.path.exists(novel_templates_dir):
directories.append(novel_templates_dir)
# Default templates directory (fallback)
directories.append(TEMPLATES_DIR)
return directories
def get_novel_template_env(novel_slug):
"""Get or create a Jinja2 environment for a specific novel with template override support"""
if novel_slug not in _novel_template_envs:
template_dirs = get_novel_template_directories(novel_slug)
loader = FileSystemLoader(template_dirs)
novel_env = Environment(loader=loader)
# Add the same filters as the global environment
novel_env.filters['slugify_tag'] = slugify_tag
novel_env.filters['format_date_for_display'] = format_date_for_display
novel_env.filters['find_author_username'] = find_author_username_filter
novel_env.filters['asset_url'] = asset_url
# Note: is_chapter_new filter will be set per render with proper config
_novel_template_envs[novel_slug] = novel_env
return _novel_template_envs[novel_slug]
def check_novel_has_custom_templates(novel_slug):
"""Check if a novel has any custom templates"""
novel_templates_dir = os.path.join(CONTENT_DIR, novel_slug, "templates")
return os.path.exists(novel_templates_dir) and bool(os.listdir(novel_templates_dir))
def list_novel_custom_templates(novel_slug):
"""List all custom templates for a novel"""
novel_templates_dir = os.path.join(CONTENT_DIR, novel_slug, "templates")
if not os.path.exists(novel_templates_dir):
return []
custom_templates = []
for file in os.listdir(novel_templates_dir):
if file.endswith('.html'):
custom_templates.append(file)
return sorted(custom_templates)
def encrypt_content_with_password(content, password):
"""Encrypt content using XOR with SHA256 hash of password"""
# Create SHA256 hash of password for consistent key
key = hashlib.sha256(password.encode('utf-8')).digest()
# Convert content to bytes
content_bytes = content.encode('utf-8')
# XOR encrypt
encrypted = bytearray()
for i, byte in enumerate(content_bytes):
encrypted.append(byte ^ key[i % len(key)])
# Return base64 encoded encrypted content
return base64.b64encode(encrypted).decode('utf-8')
def create_password_verification_hash(password):
"""Create a verification hash that can be checked client-side"""
# Use a simple hash that can be reproduced in JavaScript
return hashlib.sha256(password.encode('utf-8')).hexdigest()[:16]
def build_footer_content(site_config, novel_config=None, page_type='site'):
"""Build footer content based on site and story configurations"""
footer_data = {}
# Determine copyright text
if novel_config and novel_config.get('footer', {}).get('custom_text'):
footer_data['copyright'] = novel_config['footer']['custom_text']
elif novel_config and novel_config.get('copyright'):
footer_data['copyright'] = novel_config['copyright']
else:
site_name = site_config.get('site_name', 'Web Novel Collection')
footer_data['copyright'] = f"© 2025 {site_name}"
# Build footer links
footer_links = []
# Add story-specific links if available
if novel_config and novel_config.get('footer', {}).get('links'):
footer_links.extend(novel_config['footer']['links'])
# Add site-wide footer links if available
if site_config.get('footer', {}).get('links'):
footer_links.extend(site_config['footer']['links'])
footer_data['links'] = footer_links
# Add additional footer text
if site_config.get('footer', {}).get('additional_text'):
footer_data['additional_text'] = site_config['footer']['additional_text']
return footer_data
def generate_rss_feed(site_config, novels_data, novel_config=None, novel_slug=None):
"""Generate RSS feed for site or specific story"""
from datetime import datetime, timezone
site_url = site_config.get('site_url', '').rstrip('/')
site_name = site_config.get('site_name', 'Web Novel Collection')
if novel_config and novel_slug:
# Story-specific RSS feed
feed_title = novel_config.get('title', 'Web Novel')
feed_description = novel_config.get('description', 'Web Novel RSS Feed')
feed_link = f"{site_url}/{novel_slug}/"
feed_items = []
# Get chapters for this novel
available_languages = get_available_languages(novel_slug)
primary_lang = novel_config.get('primary_language', 'en')
all_chapters = []
for arc in novel_config.get("arcs", []):
all_chapters.extend(arc.get("chapters", []))
# Sort chapters by published date (most recent first)
chapter_items = []
for chapter in all_chapters:
chapter_id = chapter["id"]
try:
chapter_content_md, chapter_metadata = load_chapter_content(novel_slug, chapter_id, primary_lang)
if chapter_metadata is None:
continue
# Skip draft chapters unless include_drafts is True
if should_skip_chapter(chapter_metadata, INCLUDE_DRAFTS, INCLUDE_SCHEDULED):
continue
# Skip hidden chapters, password-protected, or non-indexed chapters
seo_config = chapter_metadata.get('seo') or {}
seo_allow_indexing = seo_config.get('allow_indexing') if isinstance(seo_config, dict) else None
if (is_chapter_hidden(chapter_metadata) or
('password' in chapter_metadata and chapter_metadata['password']) or
seo_allow_indexing is False):
continue
published_date = chapter_metadata.get('published')
if published_date:
try:
# Use the parse_publish_date function for better date format support
pub_datetime = parse_publish_date(published_date)
if not pub_datetime:
continue # Skip if date parsing failed
# Normalize to timezone-naive datetime for consistent RSS sorting
if pub_datetime.tzinfo is not None:
pub_datetime = pub_datetime.replace(tzinfo=None)
# Handle social_embeds safely
social_embeds = chapter_metadata.get('social_embeds') or {}
description = social_embeds.get('description', '') if isinstance(social_embeds, dict) else ''
chapter_items.append({
'id': chapter_id,
'title': chapter_metadata.get('title', chapter['title']),
'link': f"{site_url}/{novel_slug}/{primary_lang}/{chapter_id}/",
'description': description,
'pub_date': pub_datetime,
'content': convert_markdown_to_html(chapter_content_md[:500] + '...' if len(chapter_content_md) > 500 else chapter_content_md)
})
except Exception as e:
pass # Skip chapters with invalid dates
except:
continue
# Sort by date (newest first) and take latest 20
chapter_items.sort(key=lambda x: x['pub_date'], reverse=True)
feed_items = chapter_items[:20]
else:
# Site-wide RSS feed
feed_title = site_name
feed_description = site_config.get('site_description', 'Web Novel Collection RSS Feed')
feed_link = site_url
feed_items = []
# Collect recent chapters from all novels
all_chapter_items = []
for novel in novels_data:
novel_slug = novel['slug']
novel_config = load_novel_config(novel_slug)
# Skip novels that don't allow indexing
if novel_config.get('seo', {}).get('allow_indexing') is False:
continue
primary_lang = novel_config.get('primary_language', 'en')
all_chapters = []
for arc in novel.get("arcs", []):
all_chapters.extend(arc.get("chapters", []))
for chapter in all_chapters:
chapter_id = chapter["id"]
try:
chapter_content_md, chapter_metadata = load_chapter_content(novel_slug, chapter_id, primary_lang)
# Skip draft chapters unless include_drafts is True
if should_skip_chapter(chapter_metadata, INCLUDE_DRAFTS, INCLUDE_SCHEDULED):
continue
# Skip hidden, password-protected, or non-indexed chapters
seo_config = chapter_metadata.get('seo') or {}
seo_allow_indexing = seo_config.get('allow_indexing') if isinstance(seo_config, dict) else None
if (is_chapter_hidden(chapter_metadata) or
('password' in chapter_metadata and chapter_metadata['password']) or
seo_allow_indexing is False):
continue
published_date = chapter_metadata.get('published')
if published_date:
try:
# Use the parse_publish_date function for better date format support
pub_datetime = parse_publish_date(published_date)
if not pub_datetime:
continue # Skip if date parsing failed
# Normalize to timezone-naive datetime for consistent RSS sorting
if pub_datetime.tzinfo is not None:
pub_datetime = pub_datetime.replace(tzinfo=None)
# Handle social_embeds safely for site-wide RSS
social_embeds = chapter_metadata.get('social_embeds') or {}
description = social_embeds.get('description', '') if isinstance(social_embeds, dict) else ''
all_chapter_items.append({
'id': chapter_id,
'title': f"{novel.get('title', '')}: {chapter_metadata.get('title', chapter['title'])}",
'link': f"{site_url}/{novel_slug}/{primary_lang}/{chapter_id}/",
'description': description,
'pub_date': pub_datetime,
'content': convert_markdown_to_html(chapter_content_md[:300] + '...' if len(chapter_content_md) > 300 else chapter_content_md)
})
except:
pass
except:
continue
# Sort by date (newest first) and take latest 50
all_chapter_items.sort(key=lambda x: x['pub_date'], reverse=True)
feed_items = all_chapter_items[:50]
# Build RSS XML using timezone-aware dates to satisfy RSS spec
current_time = datetime.now(timezone.utc)
rss_content = f"""<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>{feed_title}</title>
<link>{feed_link}</link>
<description>{feed_description}</description>
<language>en-us</language>
<lastBuildDate>{current_time.strftime('%a, %d %b %Y %H:%M:%S %z')}</lastBuildDate>
<generator>Web Novel Static Generator</generator>
"""
for item in feed_items:
pub_date_str = (
item['pub_date'].replace(tzinfo=timezone.utc).strftime('%a, %d %b %Y %H:%M:%S %z')
if item['pub_date'] else ''
)
rss_content += f""" <item>
<title>{item['title']}</title>
<link>{item['link']}</link>
<description><![CDATA[{item['description']}]]></description>
<content:encoded><![CDATA[{item['content']}]]></content:encoded>
<pubDate>{pub_date_str}</pubDate>
<guid>{item['link']}</guid>
</item>
"""
rss_content += """</channel>
</rss>"""
return rss_content
def generate_sitemap_xml(site_config, novels_data):
"""Generate sitemap.xml file for SEO"""
from datetime import datetime
sitemap_entries = []
site_url = site_config.get('site_url', '').rstrip('/')
if not site_url:
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n</urlset>"
# Add front page
sitemap_entries.append(f""" <url>
<loc>{site_url}/</loc>
<changefreq>weekly</changefreq>
<priority>1.0</priority>
</url>""")
# Add page index
available_languages = site_config.get('languages', {}).get('available', ['en'])
for lang in available_languages:
index_filename = f"pages-{lang}.html" if lang != 'en' else "pages.html"
sitemap_entries.append(f""" <url>
<loc>{site_url}/{index_filename}</loc>
<changefreq>weekly</changefreq>
<priority>0.7</priority>
</url>""")
# Add static pages
all_pages = get_all_pages()
available_languages = site_config.get('languages', {}).get('available', ['en'])
for page_data in all_pages:
page_slug = page_data['slug']
# Load page metadata to check if it should be included
for lang in available_languages:
try:
_, page_metadata = load_page_content(page_slug, lang)
# Skip pages that don't allow indexing, are drafts, or are password-protected
if should_skip_page(page_metadata, INCLUDE_DRAFTS):
continue
page_allow_indexing = page_metadata.get('seo', {}).get('allow_indexing')
is_password_protected = 'password' in page_metadata and page_metadata['password']
if page_allow_indexing is False or is_password_protected:
continue
# Build the page URL
if '/' in page_slug:
# Nested page (e.g., "resources/translation-guide")
page_url = f"{site_url}/{page_slug}/{lang}/"
else:
# Top-level page (e.g., "about")
page_url = f"{site_url}/{page_slug}/{lang}/"
# Get updated date if available
lastmod = ""
if page_metadata.get('updated'):
try:
from datetime import datetime
update_date = datetime.strptime(page_metadata['updated'], '%Y-%m-%d')
lastmod = f"\n <lastmod>{update_date.strftime('%Y-%m-%d')}</lastmod>"
except:
pass
sitemap_entries.append(f""" <url>
<loc>{page_url}</loc>
<changefreq>monthly</changefreq>
<priority>0.6</priority>{lastmod}
</url>""")
except:
# Skip pages that don't exist for this language
continue
# Add novel pages
for novel in novels_data:
novel_slug = novel['slug']
novel_config = load_novel_config(novel_slug)
# Skip novels that don't allow indexing
if novel_config.get('seo', {}).get('allow_indexing') is False:
continue
available_languages = get_available_languages(novel_slug)
for lang in available_languages:
# Add TOC pages
sitemap_entries.append(f""" <url>
<loc>{site_url}/{novel_slug}/{lang}/toc/</loc>
<changefreq>weekly</changefreq>
<priority>0.8</priority>
</url>""")
# Add tag index pages
sitemap_entries.append(f""" <url>
<loc>{site_url}/{novel_slug}/{lang}/tags/</loc>
<changefreq>monthly</changefreq>
<priority>0.6</priority>
</url>""")
# Add individual chapters
all_chapters = []
for arc in novel.get("arcs", []):
all_chapters.extend(arc.get("chapters", []))
for chapter in all_chapters:
chapter_id = chapter["id"]
try:
chapter_content_md, chapter_metadata = load_chapter_content(novel_slug, chapter_id, lang)
# Skip draft chapters unless include_drafts is True
if should_skip_chapter(chapter_metadata, INCLUDE_DRAFTS, INCLUDE_SCHEDULED):
continue
# Skip chapters that don't allow indexing, are password-protected, or are hidden
chapter_allow_indexing = chapter_metadata.get('seo', {}).get('allow_indexing')
is_password_protected = 'password' in chapter_metadata and chapter_metadata['password']
is_hidden = is_chapter_hidden(chapter_metadata)
if chapter_allow_indexing is False or is_password_protected or is_hidden:
continue
# Get published date if available
lastmod = ""
if chapter_metadata.get('published'):
try:
# Use parse_publish_date for better date format support
pub_date = parse_publish_date(chapter_metadata['published'])
if pub_date:
lastmod = f"\n <lastmod>{pub_date.strftime('%Y-%m-%d')}</lastmod>"
except:
pass
sitemap_entries.append(f""" <url>
<loc>{site_url}/{novel_slug}/{lang}/{chapter_id}/</loc>
<changefreq>monthly</changefreq>
<priority>0.7</priority>{lastmod}
</url>""")
except:
# Skip chapters that don't exist for this language
continue
# Add tag pages
tags_data = collect_tags_for_novel(novel_slug, lang)
for tag in tags_data.keys():
tag_slug = slugify_tag(tag)
sitemap_entries.append(f""" <url>
<loc>{site_url}/{novel_slug}/{lang}/tags/{tag_slug}/</loc>
<changefreq>monthly</changefreq>
<priority>0.5</priority>
</url>""")
sitemap_content = f"""<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
{chr(10).join(sitemap_entries)}
</urlset>"""
return sitemap_content
def generate_robots_txt(site_config, novels_data):
"""Generate robots.txt file based on site and story configurations"""
robots_content = ["# Robots.txt for Web Novel Static Generator"]
# Add sitemap reference
site_url = site_config.get('site_url', '').rstrip('/')
if site_url:
robots_content.append(f"Sitemap: {site_url}/sitemap.xml")
robots_content.append("")
# Check site-wide indexing settings
site_allow_indexing = site_config.get('seo', {}).get('allow_indexing', True)
if not site_allow_indexing:
# If site doesn't allow indexing, disallow all
robots_content.extend([
"User-agent: *",
"Disallow: /",
""
])
else:
robots_content.extend([
"User-agent: *",
"Allow: /",
""
])
# Add disallow rules for specific novels or chapters that don't allow indexing
disallowed_paths = []
for novel in novels_data:
novel_slug = novel['slug']
novel_config = load_novel_config(novel_slug)
# Check novel-level indexing settings
novel_allow_indexing = novel_config.get('seo', {}).get('allow_indexing')
if novel_allow_indexing is False:
disallowed_paths.append(f"Disallow: /{novel_slug}/")
continue
# Check individual chapters for indexing settings
available_languages = get_available_languages(novel_slug)
for lang in available_languages:
all_chapters = []
for arc in novel.get("arcs", []):
all_chapters.extend(arc.get("chapters", []))
for chapter in all_chapters:
chapter_id = chapter["id"]
try:
chapter_content_md, chapter_metadata = load_chapter_content(novel_slug, chapter_id, lang)
# Skip draft chapters unless include_drafts is True
if should_skip_chapter(chapter_metadata, INCLUDE_DRAFTS, INCLUDE_SCHEDULED):
continue
# Check chapter-level indexing
seo_config = chapter_metadata.get('seo') or {}
chapter_allow_indexing = seo_config.get('allow_indexing') if isinstance(seo_config, dict) else None
if chapter_allow_indexing is False:
disallowed_paths.append(f"Disallow: /{novel_slug}/{lang}/{chapter_id}/")
# Also disallow password-protected and hidden content
if 'password' in chapter_metadata and chapter_metadata['password']:
disallowed_paths.append(f"Disallow: /{novel_slug}/{lang}/{chapter_id}/")
# Disallow hidden chapters
if is_chapter_hidden(chapter_metadata):
disallowed_paths.append(f"Disallow: /{novel_slug}/{lang}/{chapter_id}/")
except:
# Skip chapters that don't exist for this language
continue
# Add all disallow rules
if disallowed_paths:
robots_content.extend(disallowed_paths)
robots_content.append("")
robots_content.append("# Generated by Web Novel Static Generator")
return "\n".join(robots_content)
def load_site_config():
"""Load global site configuration"""
config_file = "site_config.yaml"
if os.path.exists(config_file):
with open(config_file, 'r', encoding='utf-8') as f:
return yaml.safe_load(f)
return {}
def build_social_meta(site_config, novel_config, chapter_metadata, page_type, title, url):
"""Build social media metadata for a page"""
social_meta = {}
# Handle None chapter_metadata
if chapter_metadata is None:
chapter_metadata = {}
# Determine social title
if chapter_metadata and 'social_embeds' in chapter_metadata and chapter_metadata['social_embeds'] and 'title' in chapter_metadata['social_embeds']:
social_meta['title'] = chapter_metadata['social_embeds']['title']
elif page_type == 'chapter':
# Include story name in chapter social titles like website titles do
novel_title = novel_config.get('title', '') if novel_config else ''
if novel_title:
social_meta['title'] = f"{title} - {novel_title}"
else:
social_meta['title'] = title
elif page_type == 'toc':
social_meta['title'] = f"{novel_config.get('title', '')} - Table of Contents"
else:
social_meta['title'] = title
# Apply title format if specified
title_format = site_config.get('social_embeds', {}).get('title_format', '{title}')
social_meta['title'] = title_format.format(title=social_meta['title'])
# Determine social description
if chapter_metadata and 'social_embeds' in chapter_metadata and chapter_metadata['social_embeds'] and 'description' in chapter_metadata['social_embeds']:
social_meta['description'] = chapter_metadata['social_embeds']['description']
elif novel_config.get('social_embeds', {}).get('description'):
social_meta['description'] = novel_config['social_embeds']['description']
else:
social_meta['description'] = site_config.get('social_embeds', {}).get('default_description', site_config.get('site_description', ''))
# Determine social image (absolute URL)
site_url = site_config.get('site_url', '').rstrip('/')
if chapter_metadata and 'social_embeds' in chapter_metadata and chapter_metadata['social_embeds'] and 'image' in chapter_metadata['social_embeds']:
image_path = chapter_metadata['social_embeds']['image']
elif novel_config.get('social_embeds', {}).get('image'):
image_path = novel_config['social_embeds']['image']
else:
image_path = site_config.get('social_embeds', {}).get('default_image', '/static/images/default-social.jpg')
# Convert to absolute URL if relative
if image_path.startswith('/'):
social_meta['image'] = site_url + image_path
else:
social_meta['image'] = image_path
# Set URL
social_meta['url'] = url
# Build keywords
keywords = []
if chapter_metadata and 'social_embeds' in chapter_metadata and chapter_metadata['social_embeds'] and 'keywords' in chapter_metadata['social_embeds']:
keywords.extend(chapter_metadata['social_embeds']['keywords'])
elif novel_config.get('social_embeds', {}).get('keywords'):
keywords.extend(novel_config['social_embeds']['keywords'])
social_meta['keywords'] = ', '.join(keywords) if keywords else None
return social_meta
def generate_image_hash(file_path, length=8):
"""Generate a partial hash of an image file for consistent naming"""
hasher = hashlib.sha256()
with open(file_path, 'rb') as f:
# Read in chunks to handle large files efficiently
for chunk in iter(lambda: f.read(4096), b""):
hasher.update(chunk)
return hasher.hexdigest()[:length]
def build_seo_meta(site_config, novel_config, chapter_metadata, page_type):
"""Build SEO metadata for a page"""
seo_meta = {}
# Handle None chapter_metadata
if chapter_metadata is None:
chapter_metadata = {}
# Determine if indexing is allowed (chapter > story > site)
if 'seo' in chapter_metadata and 'allow_indexing' in chapter_metadata['seo']:
seo_meta['allow_indexing'] = chapter_metadata['seo']['allow_indexing']
elif novel_config.get('seo', {}).get('allow_indexing') is not None:
seo_meta['allow_indexing'] = novel_config['seo']['allow_indexing']
else:
seo_meta['allow_indexing'] = site_config.get('seo', {}).get('allow_indexing', True)
# Determine meta description
if 'seo' in chapter_metadata and 'meta_description' in chapter_metadata['seo']:
seo_meta['meta_description'] = chapter_metadata['seo']['meta_description']
elif novel_config.get('seo', {}).get('meta_description'):
seo_meta['meta_description'] = novel_config['seo']['meta_description']
else:
seo_meta['meta_description'] = site_config.get('site_description', '')
return seo_meta
def should_minify(serve_mode=False, no_minify=False):
"""Determine if minification should be applied"""
# Don't minify in serve mode (development) unless explicitly enabled
if serve_mode:
return False
# Respect explicit --no-minify flag
if no_minify:
return False
# Check if minification libraries are available
if not _check_minification():
return False
return True
def minify_html_content(html_content):
"""Minify HTML content while preserving important formatting"""
if not MINIFICATION_AVAILABLE:
return html_content
try:
import htmlmin
return htmlmin.minify(
html_content,
remove_comments=True,
remove_empty_space=True,
reduce_boolean_attributes=True,
# Preserve formatting in specific elements
keep_pre=True # Preserve <pre> content
)
except Exception as e:
print(f" Warning: HTML minification failed: {e}")
return html_content
def minify_css_content(css_content):
"""Minify CSS content"""
if not MINIFICATION_AVAILABLE:
return css_content
try:
import rcssmin
return rcssmin.cssmin(css_content)
except Exception as e:
print(f" Warning: CSS minification failed: {e}")
return css_content
def minify_js_content(js_content):
"""Minify JavaScript content"""
if not MINIFICATION_AVAILABLE:
return js_content
try:
import rjsmin
return rjsmin.jsmin(js_content)
except Exception as e:
print(f" Warning: JavaScript minification failed: {e}")
return js_content
def write_html_file(file_path, html_content, minify=False):
"""Write HTML content to file with optional minification"""
if minify:
html_content = minify_html_content(html_content)
with open(file_path, "w", encoding='utf-8') as f:
f.write(html_content)
def process_cover_art(novel_slug, novel_config):
"""Process cover art images by copying them to static/images with hash-based filenames"""
processed_images = {}
# Ensure static/images directory exists
images_dir = os.path.normpath(os.path.join(BUILD_DIR, "static", "images"))
os.makedirs(images_dir, exist_ok=True)
# Process story cover art
if novel_config.get('front_page', {}).get('cover_art'):
source_path = os.path.join(CONTENT_DIR, novel_slug, novel_config['front_page']['cover_art'])
if os.path.exists(source_path):
# Generate hash-based filename with original name
original_filename = os.path.basename(source_path)
file_name, file_extension = os.path.splitext(original_filename)
file_hash = generate_image_hash(source_path)
unique_filename = f"{file_hash}-{file_name}{file_extension}"
dest_path = os.path.join(images_dir, unique_filename)
# Copy the image
shutil.copy2(source_path, dest_path)
# Store the processed path
processed_images['story_cover'] = f"static/images/{unique_filename}"
# Process arc cover art
if novel_config.get('arcs'):
for i, arc in enumerate(novel_config['arcs']):
if arc.get('cover_art'):
source_path = os.path.join(CONTENT_DIR, novel_slug, arc['cover_art'])
if os.path.exists(source_path):
# Generate hash-based filename with original name
original_filename = os.path.basename(source_path)
file_name, file_extension = os.path.splitext(original_filename)
file_hash = generate_image_hash(source_path)
unique_filename = f"{file_hash}-{file_name}{file_extension}"
dest_path = os.path.join(images_dir, unique_filename)
# Copy the image
shutil.copy2(source_path, dest_path)
# Store the processed path
processed_images[f'arc_{i}_cover'] = f"static/images/{unique_filename}"
return processed_images
def load_authors_config():
"""Load authors configuration from authors.yaml"""
authors_file = "authors.yaml"
if os.path.exists(authors_file):
with open(authors_file, 'r', encoding='utf-8') as f:
config = yaml.safe_load(f)
return config.get('authors', {})
return {}
def find_author_username(author_name, authors_config):
"""Find the username for an author by their display name"""
for username, author_info in authors_config.items():
if author_info.get('name') == author_name:
return username
return None
def collect_author_contributions(all_novels_data):
"""Collect all stories and chapters that each author contributed to"""
author_contributions = {}
for novel in all_novels_data:
novel_slug = novel['slug']
novel_title = novel.get('title', novel_slug)
novel_config = load_novel_config(novel_slug)
# Check story-level author
story_author = novel_config.get('author', {}).get('name')
if story_author:
if story_author not in author_contributions:
author_contributions[story_author] = {'stories': [], 'chapters': []}
author_contributions[story_author]['stories'].append({
'slug': novel_slug,
'title': novel_title,
'description': novel.get('description'),
'role': 'Author'
})
# Check each chapter for author/translator contributions (use primary language only to avoid duplicates)
primary_lang = novel_config.get('primary_language', 'en')
for arc in novel.get('arcs', []):
for chapter in arc.get('chapters', []):
chapter_id = chapter['id']
chapter_title = chapter['title']
# Load chapter content to get front matter (use primary language only)
try:
chapter_content, chapter_metadata = load_chapter_content(novel_slug, chapter_id, primary_lang)
# Check chapter author
if chapter_metadata.get('author'):
author_name = chapter_metadata['author']
if author_name not in author_contributions:
author_contributions[author_name] = {'stories': [], 'chapters': []}
author_contributions[author_name]['chapters'].append({
'novel_slug': novel_slug,
'novel_title': novel_title,
'chapter_id': chapter_id,
'title': chapter_title,
'role': 'Author',
'published': chapter_metadata.get('published')
})
# Check chapter translator
if chapter_metadata.get('translator'):
translator_name = chapter_metadata['translator']
if translator_name not in author_contributions:
author_contributions[translator_name] = {'stories': [], 'chapters': []}
author_contributions[translator_name]['chapters'].append({
'novel_slug': novel_slug,
'novel_title': novel_title,
'chapter_id': chapter_id,
'title': chapter_title,
'role': 'Translator',
'published': chapter_metadata.get('published')
})
except:
# Skip chapters that can't be loaded
continue
return author_contributions
def get_non_hidden_chapters(novel_config, novel_slug, language='en', include_drafts=False, include_scheduled=False):
"""Get list of chapters that are not hidden or drafts"""
visible_chapters = []
for arc in novel_config.get('arcs', []):
arc_chapters = []
for chapter in arc.get('chapters', []):
chapter_id = chapter['id']
# Load chapter content to check if it's hidden, password protected, or draft
try:
chapter_content, chapter_metadata = load_chapter_content(novel_slug, chapter_id, language)
# Skip if chapter should be skipped
if should_skip_chapter(chapter_metadata, include_drafts, include_scheduled):
continue
arc_chapters.append({
'id': chapter_id,
'title': chapter['title'],
'content': chapter_content,
'metadata': chapter_metadata
})
except:
# Skip chapters that can't be loaded
continue
if arc_chapters: # Only include arcs with visible chapters
visible_chapters.append({
'title': arc['title'],
'cover_art': arc.get('cover_art'),
'chapters': arc_chapters
})
return visible_chapters
def get_chapters_for_epub(novel_config, novel_slug, language='en', include_drafts=False, include_scheduled=False):
"""Get list of chapters for EPUB generation (excludes hidden, draft, and password-protected)"""
visible_chapters = []
for arc in novel_config.get('arcs', []):
arc_chapters = []
for chapter in arc.get('chapters', []):
chapter_id = chapter['id']
# Load chapter content to check if it should be included in EPUB
try:
chapter_content, chapter_metadata = load_chapter_content(novel_slug, chapter_id, language)
# Skip if chapter should be skipped in EPUB
if should_skip_chapter_in_epub(chapter_metadata, include_drafts):
continue
arc_chapters.append({
'id': chapter_id,
'title': chapter['title'],
'content': chapter_content,
'metadata': chapter_metadata
})
except:
# Skip chapters that can't be loaded
continue
if arc_chapters: # Only include arcs with visible chapters
visible_chapters.append({
'title': arc['title'],
'cover_art': arc.get('cover_art'),
'chapters': arc_chapters
})
return visible_chapters
def load_page_content(page_slug, language='en'):
"""Load page content from markdown file with language support and front matter parsing"""
# Try language-specific file first
if language != 'en':
page_file = os.path.join(PAGES_DIR, language, f"{page_slug}.md")
if os.path.exists(page_file):
with open(page_file, 'r', encoding='utf-8') as f:
content = f.read()
front_matter, markdown_content = parse_front_matter(content)
return markdown_content, front_matter
# Fallback to default language file
page_file = os.path.join(PAGES_DIR, f"{page_slug}.md")
if os.path.exists(page_file):
with open(page_file, 'r', encoding='utf-8') as f:
content = f.read()
front_matter, markdown_content = parse_front_matter(content)
return markdown_content, front_matter
return None, {}
def load_nested_page_content(page_path, language='en'):
"""Load nested page content (e.g., resources/translation-guide)"""
page_slug = page_path.replace('/', os.sep)