-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathgenerate.py
executable file
·1881 lines (1567 loc) · 70.6 KB
/
generate.py
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
#!/usr/bin/env python3
import sys
import re
import os
import shutil
import pprint
import subprocess
import json
import html
import subprocess
import http.server
import socketserver
import hashlib
import urllib.parse
import pytz
import argparse
import gzip
import lunr
from dataclasses import dataclass, field
from collections import defaultdict, OrderedDict
from bs4 import BeautifulSoup, NavigableString
from urllib.parse import quote
from datetime import datetime, timedelta, timezone
from dateutil.relativedelta import relativedelta
from PyPDF2 import PdfReader, PdfWriter
#
# Parse arguments
#
### CONFIG Class
@dataclass
class BuildConfig():
source_dir: str = "issues" # where to look for files
build_dir: str = "out" # where to put the output
cache_dir: str = "cache"
server: str = "www.64er-magazin.de" # where to put the files so others can see
base_dir: str = "" # base directory: updated from command line arguments and branch name
# cli arguments
deploy: bool = False # set via cli argument "upload": upload to server
build_future: bool = False # set via cli flag "--future": helper for disabling unfinished categories
start_local_server: bool = True # set via cli flag "--join": helper for not starting a local server every time
lang: str = "de" # set via cli flag "--lang": change language between english and german
# git status
git_has_changes: bool = True # set in setup
git_branch_name: str = "main" # set in setup
def parse_cli_into_config():
# supported command line arguments
parser = argparse.ArgumentParser(description=f"Generate the magazine")
parser.add_argument("deploy_mode", choices=["upload", "local"], nargs='?', default="local", help="the deploy mode (default: %(default)s)")
parser.add_argument("--future", action='store_true', help="also build issues with release dates in the future")
parser.add_argument("--lang", choices=['de', 'en'], nargs='?', const='de', default='de', help="[WIP] build a different language version (default: %(default)s)")
parser.add_argument("--join", action='store_true', help="open page locally without starting a server ")
# parsing command line arguments
args = parser.parse_args()
config = BuildConfig()
config.deploy = args.deploy_mode == "upload"
config.build_future = args.future
config.lang = args.lang
config.start_local_server = not args.join
# get git status
f = os.popen(f'git ls-files -m | wc -l')
if int(f.read()) <= 0:
config.git_has_changes = False
git_branch_name = subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"]).decode("utf-8").strip()
config.git_branch_name = git_branch_name
##
## SETUP
##
print("*** Setup")
is_on_main = git_branch_name == 'main'
# adjust base dir for the current build destination and branches
if is_on_main:
if not config.build_future:
config.base_dir = ''
else:
config.base_dir = 'test/'
else:
config.base_dir = 'test/' + config.git_branch_name + '/'
if config.lang != 'de':
config.base_dir += '/' + config.lang
git_status = ''
if config.git_has_changes:
git_status = '+'
print(f" > branch '{config.git_branch_name}'{git_status} -> '{config.base_dir}'")
# if the current build should be uploaded: do some sanity checking
if config.deploy:
# if config.git_has_changes:
# print("Generating and upload failed:")
# print("There are uncommited changes in the working copy.")
# exit()
if is_on_main and not config.build_future:
response = input("Deploy to production? [Y/N]: ").strip()
if response.lower() != 'y':
print("Exiting.")
exit()
return config
CONFIG = parse_cli_into_config()
git_status = '\n <!!!> Has uncommited changes!' if CONFIG.git_has_changes else ''
print(f"""
> base_dir: {CONFIG.base_dir}
> deploy: {CONFIG.deploy}
> build_future: {CONFIG.build_future}
> start_local_server: {CONFIG.start_local_server}
{git_status}
""")
#
# Settings
#
OUT_DIRECTORY = CONFIG.build_dir
CACHE_DIRECTORY = CONFIG.cache_dir
SERVER = CONFIG.server
BASE_DIR = CONFIG.base_dir
LANG = CONFIG.lang
NEW_DOWNLOADS = 20
RSS_BASE_URL = "https://www.64er-magazin.de/"
MASTODON_HASHTAGS = "#c64 #retrocomputing #64er"
TITLE_IMAGE_NAME = "title.jpg"
#
# Localization
#
if LANG == "de":
IN_DIRECTORY = 'issues'
MAGAZINE_NAME = "64'er Magazin"
MAGAZINE_NAME_FULL = "64'er – Das Magazin für Computer-Fans"
LABEL_ISSUES = "Ausgaben"
LABEL_ARTICLES = "Artikel"
LABEL_LISTINGS = "Listings"
LABEL_SEARCH = "Suchen"
LABEL_NEWS = "Aktuell"
LABEL_HARDWARE = "Hardware"
LABEL_TESTS = "Test"
LABEL_SOFTWARE = "Software"
LABEL_GAMES = "Spiele"
LABEL_PROGRAMS = "Programme"
LABEL_TUTORIALS = "Kurse"
LABEL_IN_PRACTICE = "Praxis"
LABEL_CONTACT = "Kontakt"
LABEL_IMPRINT = "Impressum"
LABEL_PRIVACY = "Datenschutzerklärung"
LABEL_404 = "404 - Seite nicht gefunden"
LABEL_ISSUE = "Ausgabe"
LABEL_PAGE = "S."
LABEL_DOWNLOAD_ISSUE_PDF = "PDF Downloaden"
LABEL_DOWNLOAD_ARTICLE_PDF = "Diesen Artikel als PDF herunterladen"
LABEL_SHARE_ON_MASTODON = "Diesen Artikel auf Mastodon teilen"
LABEL_DOWNLOAD = "Download"
LABEL_NEWER = "← Neuer"
LABEL_OLDER = "Älter →"
LABEL_PREVIOUS_ARTICLE = "← Vorheriger Artikel"
LABEL_NEXT_ARTICLE = "Nächster Artikel →"
LABEL_ALL_ISSUES = "Alle Ausgaben"
LABEL_ALL_ARTICLES = "Alle Artikel"
LABEL_ALL_LISTINGS = "Alle Listings"
LABEL_CURRENT_REGULAR_ISSUE = "Das aktuelle Magazin"
LABEL_CURRENT_SPECIAL_ISSUE = "Das aktuelle Sonderheft"
LABEL_REGULAR_MAGAZINES = "Stammagazin"
LABEL_SPECIAL_MAGAZINES = "Sonderhefte"
LABEL_LATEST_LISTINGS = "Neueste Listings"
LABEL_TOC_ISSUE = "Inhalt Ausgabe"
LABEL_CATEGORY = "Kategorie"
LABEL_ARTICLE = "Artikel"
LABEL_DOWNLOADS = "Downloads"
FILENAME_ISSUES = "ausgaben"
FILENAME_ARTICLES = "artikel"
FILENAME_LISTINGS = "listings"
FILENAME_NEWS = "aktuell"
FILENAME_HARDWARE = "hardware"
FILENAME_TESTS = "test"
FILENAME_SOFTWARE = "software"
FILENAME_GAMES = "spiele"
FILENAME_PROGRAMS = "programme"
FILENAME_TUTORIALS = "kurse"
FILENAME_IN_PRACTICE = "praxis"
FILENAME_PRIVACY = "datenschutz"
FILENAME_404 = "404"
FILENAME_IMPRINT = "impressum"
CATEGORY_TYPE_IN_1 = "Programme zum Abtippen"
CATEGORY_TYPE_IN_2 = "Listings zum Abtippen"
TOPICS = [ # Title + used prefix # these are the values used with "64er.index_category" for sorting the topics by prefix
(LABEL_NEWS, ["Aktuell|"]),
(LABEL_HARDWARE, ["Hardware|"]),
(LABEL_TESTS, [ "Hardware-Test|",
"Software-Test|",
"Spiele-Test|"]),
(LABEL_SOFTWARE, ["Software|"]),
(LABEL_GAMES, ["Listings zum Abtippen|Spiel|"]),
(LABEL_PROGRAMS, ["Listings zum Abtippen|Anwendung|",
"Listings zum Abtippen|Grafik|",
"Listings zum Abtippen|Tips & Tricks|"]),
(LABEL_TUTORIALS, ["Kurse|"]),
(LABEL_IN_PRACTICE, ["So machen's andere|"]),
]
HTML_PRIVACY = """
<main>
<h1>Datenschutzerklärung</h1>
<ul>
<li>Beim Lesen dieser Website werden keine personenbezogenen Daten erhoben.</li>
<li>Die Suche läuft lokal im Browser. Die Sucheingabe wird nicht an den Server übertragen.</li>
<li>Beim Absenden eines Kommentars werden die eingegebenen Daten auf einem Server in der EU gespeichert.</li>
</ul>
</main>
"""
HTML_IMG_FEHLERTEUFELCHEN= f"""
<img src="/{BASE_DIR}fehlerteufelchen.svg" alt="Fehlerteufelchen">
"""
HTML_IMG_FUTURETEUFELCHEN= f"""
<img src="/{BASE_DIR}futureteufelchen.svg" alt="Futureteufelchen">
"""
HTML_404 = f"""
<main class="fehlerteufelchen">
<h1>Seite nicht gefunden</h1>
{HTML_IMG_FEHLERTEUFELCHEN}
</main>
"""
elif LANG == "en":
IN_DIRECTORY = 'en'
MAGAZINE_NAME = "64'er Magazine"
MAGAZINE_NAME_FULL = "64'er – The Magazine for Computer Fans"
LABEL_ISSUES = "Issues"
LABEL_ARTICLES = "Articles"
LABEL_LISTINGS = "Listings"
LABEL_SEARCH = "Search"
LABEL_NEWS = "News"
LABEL_HARDWARE = "Hardware"
LABEL_TESTS = "Tests"
LABEL_SOFTWARE = "Software"
LABEL_GAMES = "Games"
LABEL_PROGRAMS = "Programs"
LABEL_TUTORIALS = "Tutorials"
LABEL_IN_PRACTICE = "Practice"
LABEL_CONTACT = "Contact"
LABEL_IMPRINT = "Imprint"
LABEL_PRIVACY = "Privacy"
LABEL_404 = "404 - Page Not Found"
LABEL_CATEGORY = "Category"
LABEL_ISSUE = "Issue"
LABEL_PAGE = "p."
LABEL_DOWNLOAD_ISSUE_PDF = "Download PDF"
LABEL_DOWNLOAD_ARTICLE_PDF = "Download this article in PDF format"
LABEL_SHARE_ON_MASTODON = "Share this article on Mastodon"
LABEL_DOWNLOAD = "Download"
LABEL_NEWER = "← Newer"
LABEL_OLDER = "Older →"
LABEL_PREVIOUS_ARTICLE = "← Previous Article"
LABEL_NEXT_ARTICLE = "Next Article →"
LABEL_ALL_ISSUES = "All Issues"
LABEL_ALL_ARTICLES = "All Articles"
LABEL_ALL_LISTINGS = "All Listings"
LABEL_CURRENT_REGULAR_ISSUE = "Current Issue"
LABEL_CURRENT_SPECIAL_ISSUE = "Current Special Issue"
LABEL_REGULAR_MAGAZINES = "Main Magazine"
LABEL_SPECIAL_MAGAZINES = "Special Issues"
LABEL_LATEST_LISTINGS = "Latest Listings"
LABEL_TOC_ISSUE = "Table of Contents, Issue"
LABEL_ARTICLE = "Article"
LABEL_DOWNLOADS = "Downloads"
FILENAME_ISSUES = "issues"
FILENAME_ARTICLES = "articles"
FILENAME_LISTINGS = "listings"
FILENAME_NEWS = "news"
FILENAME_HARDWARE = "hardware"
FILENAME_TESTS = "tests"
FILENAME_SOFTWARE = "software"
FILENAME_GAMES = "games"
FILENAME_PROGRAMS = "programs"
FILENAME_TUTORIALS = "tutorials"
FILENAME_IN_PRACTICE = "practice"
FILENAME_PRIVACY = "privacy"
FILENAME_404 = "404"
FILENAME_IMPRINT = "imprint"
CATEGORY_TYPE_IN_1 = "Type-in Programs"
CATEGORY_TYPE_IN_2 = "Type-in Listings"
# TODO XXX translate
TOPICS = [ # Title + used prefix # these are the values used with "64er.index_category" for sorting the topics by prefix
(LABEL_NEWS, ["Aktuell|"]),
(LABEL_HARDWARE, ["Hardware|"]),
(LABEL_TESTS, [ "Hardware-Test|",
"Software-Test|",
"Spiele-Test|"]),
(LABEL_SOFTWARE, ["Software|"]),
(LABEL_GAMES, ["Listings zum Abtippen|Spiel|"]),
(LABEL_PROGRAMS, ["Listings zum Abtippen|Anwendung|",
"Listings zum Abtippen|Grafik|",
"Listings zum Abtippen|Tips & Tricks|"]),
(LABEL_TUTORIALS, ["Kurse|"]),
(LABEL_IN_PRACTICE, ["So machen's andere|"]),
]
HTML_PRIVACY = """
<main>
<h1>Privacy Policy</h1>
<ul>
<li>No personal data is collected when reading this website.</li>
<li>The search runs locally in the browser. The search input is not transmitted to the server.</li>
<li>When submitting a comment, the entered data is stored on a server in the EU.</li>
</ul>
</main>
"""
HTML_IMG_FEHLERTEUFELCHEN=f"""
<img src="/{BASE_DIR}fehlerteufelchen.svg" alt="Error Devil">
"""
HTML_IMG_FUTURETEUFELCHEN= f"""
<img src="/{BASE_DIR}futureteufelchen.svg" alt="Future Devil">
"""
HTML_404 = f"""
<main class="fehlerteufelchen">
<h1>Page Not Found</h1>
{HTML_IMG_FEHLERTEUFELCHEN}
</main>
"""
LOGO = f'<img src="/{BASE_DIR}logo.svg" alt="{MAGAZINE_NAME}">'
###
### DATABASE
###
# converts an img tag into a picture tag with AVIF and a JPEG fallback
def avif_picture_tag(soup, img_src, attrs=None):
def image_tag(tag_src=img_src):
img_tag = soup.new_tag('img')
# Copy all attributes from the original <img> tag to the new one
if attrs:
for attr, value in attrs.items():
img_tag[attr] = value
# add an empty alt for now if there is none
if 'alt' not in img_tag.attrs:
img_tag['alt'] = ""
img_tag['src'] = tag_src
return img_tag
# svg is unchanged
if img_src[-4:] == '.svg':
svg_tag = image_tag()
return svg_tag
# Create the <picture> tag
picture_tag = soup.new_tag('picture')
# Create the <source> tag for AVIF and add it to <picture>
source_tag = soup.new_tag('source', srcset=img_src[:-4] + '.avif', type='image/avif')
picture_tag.insert(0, source_tag)
# Create a new <img> tag for the JPEG version
# Update the src attribute to the JPEG version
jpg_src = img_src[:-4] + '.jpg'
new_img_tag = image_tag(jpg_src)
# Append the new <img> tag to the <picture> tag
picture_tag.append(new_img_tag)
return picture_tag
def calculate_sha1(filepath):
sha1 = hashlib.sha1()
with open(filepath, 'rb') as f:
while chunk := f.read(8192):
sha1.update(chunk)
return sha1.hexdigest()
class Article:
def __init__(self, metadata):
self.title = metadata['title']
# self.issue = metadata['issue'] # XXX should we reference the issue directly?
self.pages = metadata['pages']
self.id = metadata['id']
self.issue_key = metadata['issue_key']
self.head1 = metadata['head1']
self.head2 = metadata['head2']
self.toc_title = metadata['toc_title']
self.toc_category = metadata['toc_category']
self.index_title = metadata['index_title']
self.index_category = metadata['index_category']
self.target_filename = metadata['target_filename']
self.downloads = metadata['downloads']
self.description = metadata['description']
self.src_img_urls = metadata['src_img_urls']
self.html = metadata['html']
self.txt = metadata['txt']
self.img_urls = metadata['img_urls']
self.path = metadata['path'] # nice for debugging
self.sort_index = None # set later, after sorting all articles
def first_page_number(self):
try:
return int(self.pages.split(',')[0].split('-')[0])
except ValueError:
raise SystemExit(f'\n---\nMetaDataError: pages tag is "{self.pages}"\n File: "{self.path}"')
def out_filename(self):
return self.id + '.html'
def article_pubdate(self):
issue = db.issues[self.issue_key]
if self.issue_key.endswith("/84") and self.issue_key != "12/84":
# until 8411: every 16 hours
# (we can remove this code path once 11/84 is through)
hours_per_article = 16
else:
# starting with 8412: spread over 30 days
hours_per_article = int(30*24 / len(issue.articles))
pubdate = issue.pubdate + timedelta(hours=hours_per_article * self.sort_index)
return pubdate
def is_category_listings(self):
if not self.index_category:
return False
if not self.index_category.startswith(CATEGORY_TYPE_IN_1 + '|') and not self.index_category.startswith(CATEGORY_TYPE_IN_2 + '|'):
return False
if not self.downloads:
return False
return True
class Issue:
def __init__(self, issue_directory_path):
"""Extracts all relevant data from an issue directory, including HTML file paths."""
toc_order = []
pdf_filename = None
issue_dir_name = os.path.basename(issue_directory_path)
issue_key = None
pubdate = None
articles = []
pdf_filename = None
# todo: XXX get listings and binaries from the articles instead of the prg folder
# read all listings in petcat format (and other binaries)
listings = {}
binaries = []
prg_path = os.path.join(issue_directory_path, 'prg')
for root, _, files in os.walk(prg_path):
for file in files:
if file.endswith('.txt'):
file_path = os.path.join(root, file)
with open(file_path, 'r') as file_obj:
listings[os.path.splitext(file)[0]] = file_obj.read()
elif file.endswith('.seq') or file.endswith('.prg'):
file_path = os.path.join('prg', file)
binaries.append(file_path)
for root, dirs, files in os.walk(issue_directory_path):
for file in files:
if file.endswith('.html'):
article_path = os.path.join(root, file)
article_metadata = Issue.__read_html(article_path, listings)
articles.append(Article(article_metadata))
elif file == 'toc.txt':
toc_order = Issue.__read_toc_order(os.path.join(root, file))
elif file == 'pubdate.txt':
pubdate = Issue.__read_pubdate(os.path.join(root, file))
elif file.endswith('.pdf'):
pdf_path = os.path.join(root, file)
pdf_filename = os.path.basename(pdf_path)
# sort articles by page number
def sort_by_page_number_and_toc_category(article):
if article.toc_category == '': # editorial
category_index = -1
elif article.toc_category:
if article.toc_category in toc_order:
category_index = toc_order.index(article.toc_category)
else:
category_index = len(toc_order)
raise Exception(f"- [{issue_directory_path}] ERROR: category not in toc.txt: '{article.toc_category}' ({article.title})")
else: # no toc_category
category_index = len(toc_order)
return (article.first_page_number(), category_index, article.title)
sorted_articles = sorted(articles, key=lambda x: sort_by_page_number_and_toc_category(x))
for index, article in enumerate(sorted_articles):
#print((index, article.first_page_number(), article.toc_category, article.title))
article.sort_index = index
articles = sorted_articles
# get the issue key from the articles and check that all of them match
for article in articles:
if not issue_key:
issue_key = article.issue_key
else:
if issue_key != article.issue_key:
print("BAD", issue_key, article.issue_key)
assert(issue_key == article.issue_key)
if not pubdate:
# no system exit as this also triggers for empty folders (eg. after branch change)
raise AssertionError(f"- [{issue_directory_path}] Skipping: no pubdate")
elif not CONFIG.build_future:
# Define the current datetime with UTC timezone for comparison
current_datetime = datetime.now(pytz.utc)
# Remove the item if its publication date is in the future
if pubdate > current_datetime:
# no system exit
raise AssertionError(f"- [{issue_directory_path}] Skipping: pubdate in the future")
if not pdf_filename:
print(f"- [{issue_directory_path}] Warning: Missing PDF")
# XXX used directly after init and then never again
self.articles = articles
self.issue_key = issue_key
self.toc_order = toc_order
self.pubdate = pubdate
self.pdf_filename = pdf_filename
self.issue_dir_name = issue_dir_name
self.listings = listings
self.binaries = binaries
@staticmethod
def __read_html(html_file_path, listings):
"""Parses an HTML file for article metadata and includes the filename."""
with open(html_file_path, 'r', encoding='utf-8') as file:
contents = file.read()
soup = BeautifulSoup(contents, 'html.parser')
def find_meta(name, is_optional=True): # panic if non optional
meta_tag = soup.find('meta', attrs={'name': name})
if meta_tag:
return meta_tag['content']
elif is_optional:
return None
else:
raise SystemExit(f'\n---\nMetaDataError: "{name}" meta tag is missing\n File: "{html_file_path}"')
def find_title(): # panic if no title
title_tag = soup.find('title')
if title_tag:
return title_tag.text
else:
raise SystemExit(f'\n---\nMetaDataError: title tag is missing\n File: "{html_file_path}"')
metadata = {
'filename': os.path.basename(html_file_path), # XXX old
'title': find_title(),
'issue_key': find_meta('64er.issue', False),
'pages': find_meta('64er.pages', False),
'id': find_meta('64er.id', False),
'head1': find_meta('64er.head1'),
'head2': find_meta('64er.head2'),
'toc_title': find_meta('64er.toc_title'),
'toc_category': find_meta('64er.toc_category'),
'index_title': find_meta('64er.index_title'),
'index_category': find_meta('64er.index_category'),
'path' : html_file_path, # Include full path in metadata
}
metadata['target_filename'] = os.path.basename(metadata['id']) + '.html'
# Put listings into <pre> tags and collect downloads
downloads = []
a_tags = []
pre_tags = soup.find_all("pre")
for tag in pre_tags:
data_filename = tag.get("data-filename")
data_name = tag.get("data-name")
data_range = tag.get("data-range")
data_availability = tag.get("data-availability")
if data_filename:
# remove ';', empty lines and leading spaces
listing = listings[data_filename]
listing = [line.lstrip() for line in listing.splitlines() if line.strip() and not line.lstrip().startswith(';')]
if data_range:
ranges = [(int(part.split('-')[0]), int(part.split('-')[-1])) for part in data_range.split(',')]
filtered_lines = []
blank_line_added = True
for line in listing:
leading_number = int(line.split(' ')[0])
if any(start <= leading_number <= end for start, end in ranges):
filtered_lines.append(line)
blank_line_added = False
else:
if not blank_line_added:
filtered_lines.append('')
blank_line_added = True
listing = filtered_lines
listing = "\n".join(listing)
tag.string = listing
if not any(item[0] == data_name for item in downloads): # duplicates
if data_availability != "local":
data_filename_escaped = urllib.parse.quote(data_filename)
downloads.append((data_name, f"prg/{data_filename_escaped}.prg"))
## additional binary downloads from the Programmservicediskette
div_downloads = soup.find_all("div", { "class" : "binary_download" } )
for tag in div_downloads:
data_filename = tag.get("data-filename")
data_name = tag.get("data-name")
data_filename_escaped = urllib.parse.quote(data_filename)
downloads.append((data_name, f"prg/{data_filename_escaped}"))
tag.decompose()
metadata['downloads'] = downloads
# and make a "downloads" aside
if downloads:
aside_tag = soup.new_tag("aside", attrs={"class": "downloads"})
for (label, url) in downloads:
a_tag = soup.new_tag("a", href=url)
a_tag.string = label
a_tags.append(a_tag)
aside_tag.append(a_tag)
article_tag = soup.find("article")
article_tag.append(aside_tag)
# Extract article description
intro_div = soup.find('p', {"class": "intro"})
if intro_div:
metadata['description'] = intro_div.text.strip()
else:
first_p = soup.find('p')
if first_p:
# Extract text, split into words, take the first 64, and join them back into a string
words = first_p.text.split()
metadata['description'] = ' '.join(words[:64]) + '...'
else:
metadata['description'] = ''
# Extract all image URLs with their *source* names
src_img_urls = [img['src'] for img in soup.find_all('img') if img.get('src')]
metadata['src_img_urls'] = src_img_urls
# In the HTML, change all img src paths from PNG to AVIF, with a JPEG fallback
for img_tag in soup.find_all('img'):
img_src = img_tag['src']
if img_src.lower().endswith('.png'):
img_tag.replace_with(avif_picture_tag(soup, img_tag['src'], img_tag.attrs))
metadata['html'] = soup
metadata['txt'] = html_to_text_preserve_paragraphs(soup.body);
# Extract all image URLs with their *destination* names
img_urls = [img['src'] for img in soup.find_all('img') if img.get('src')]
metadata['img_urls'] = img_urls
return metadata
@staticmethod
def __read_toc_order(toc_file_path):
"""Reads the TOC order from toc.txt file."""
with open(toc_file_path, 'r', encoding='utf-8') as file:
toc_order = [line.strip() for line in file.readlines() if line.strip()]
return toc_order
def __read_pubdate(file_path):
with open(file_path, 'r') as file:
date_str = file.readline().strip()
return datetime.strptime(date_str, "%Y-%m-%d").replace(tzinfo=timezone.utc)
class ArticleDatabase:
def __init__(self, in_directory):
self.issues = {} # Change to dictionary
self.authors = set(())
self.articles = []
for issue_dir_name in sorted(os.listdir(in_directory)):
issue_dir_path = os.path.join(in_directory, issue_dir_name)
if os.path.isdir(issue_dir_path) and (re.match(r'^\d{4}$', issue_dir_name) or re.match(r'^SH\d{4}$', issue_dir_name)):
try:
issue = Issue(issue_dir_path)
except AssertionError as error:
print(error)
continue
# Map issue key to issue data
issue_key = issue.issue_key
self.issues[issue_key] = issue
self.articles.extend(issue.articles)
def latest_regular_issue_key(self):
return max(
(k for k in self.issues.keys() if k[0].isdigit()),
key=lambda k: self.issues[k].pubdate,
default=None
)
def latest_special_issue_key(self):
return max(
(k for k in self.issues.keys() if not k[0].isdigit()),
key=lambda k: self.issues[k].pubdate,
default=None
)
def articles_by_index_categories(self, index_categories, issue_key=None):
# toc_category hacks for Rubriken and Aktuell
if index_categories == ["Aktuell|"]:
filtered_articles = [ article for article in self.articles if ((not article.index_category and article.toc_category and article.toc_category == "Aktuell") or (article.index_category and article.index_category.startswith("Aktuell"))) and (issue_key is None or article.issue_key == issue_key)]
elif index_categories == ["Rubriken|"]:
filtered_articles = [ article for article in self.articles if article.toc_category and article.toc_category == "Rubriken" and (issue_key is None or article.issue_key == issue_key)]
else:
index_categories = tuple(index_categories)
filtered_articles = [ article for article in self.articles if article.index_category and article.index_category.startswith(index_categories) and (issue_key is None or article.issue_key == issue_key)]
return sorted(filtered_articles, key=lambda x: x.first_page_number())
def articles_by_toc_categories(self, toc_categories, issue_key=None):
filtered_articles = [article for article in self.articles if article.toc_category in toc_categories and (issue_key is None or article.issue_key == issue_key)]
return sorted(filtered_articles, key=lambda x: x.first_page_number())
def toc_with_articles(self, issue_key):
issue = self.issues[issue_key]
toc_entries = []
toc_order = [""] + issue.toc_order # prepend empty category
for toc in toc_order:
articles = self.articles_by_toc_categories([toc], issue_key)
articles_sorted = sorted(articles, key=lambda x: x.first_page_number())
toc_entries.append({
'category': toc,
'articles': articles_sorted
})
return toc_entries
def articles_with_downloads(self):
return [article for article in self.articles if article.is_category_listings()]
def all_type_in_articles_grouped_by_index_category(self):
# Initialize a dictionary to hold articles by category
articles_by_category = defaultdict(list)
# Filter articles with downloads and organize them
for article in self.articles:
index_category = article.index_category
if article.is_category_listings():
index_category = index_category[index_category.find('|') + 1:]
articles_by_category[index_category].append(article)
# Sort articles in each category by issue and then by first page number
for category, articles_list in articles_by_category.items():
articles_by_category[category] = sorted(articles_list, key=lambda x: (x.issue_key, x.first_page_number()))
sorted_categories = sorted(articles_by_category.items(), key=lambda x: x[0])
return OrderedDict(sorted_categories)
### Helpers
def full_url(path):
return RSS_BASE_URL + quote(BASE_DIR + path)
def article_path(issue, article, prepend_issue_dir=False):
article_path = optional_issue_prefix(article.out_filename(), issue, prepend_issue_dir)
return article_path
def article_link(db, article, title, prepend_issue_dir=False):
issue = db.issues[article.issue_key]
path = article_path(issue, article, prepend_issue_dir)
return f"<a href='{path}'>{title}</a>"
def prg_link(issue, download):
label, url = download
url = os.path.join(issue.issue_dir_name, url)
return f"<a href='{url}'>{label}</a>"
def index_title(article):
index_title = article.index_title
toc_title = article.toc_title
title = article.title
ret = index_title if index_title else toc_title if toc_title else title
return ret
def toc_title(article):
toc_title = article.toc_title
title = article.title
return toc_title if toc_title else title
def share_on_mastodon_link(title, url):
mastodon_message = quote(f"{title}\n{url}\n{MASTODON_HASHTAGS}")
return f"/{BASE_DIR}tootpick.html#text={mastodon_message}"
def optional_issue_prefix(path, issue, prepend_issue_dir=False):
if prepend_issue_dir:
path = os.path.join(issue.issue_dir_name, path)
return path
### Reusable HTML generation
def html_generate_latest_issue(db, special):
if special:
latest_issue_key = db.latest_special_issue_key()
label_current_issue = LABEL_CURRENT_SPECIAL_ISSUE
else:
latest_issue_key = db.latest_regular_issue_key()
label_current_issue = LABEL_CURRENT_REGULAR_ISSUE
latest_issue = db.issues[latest_issue_key]
issue_dir_name = os.path.basename(latest_issue.issue_dir_name)
latest_title_image = os.path.join(issue_dir_name, "title.jpg")
latest_html = f'''
<h2>{label_current_issue}</h2>\n
<hr>
<a href="{issue_dir_name}">
<img src="{latest_title_image}" alt="">
</a>
<p class="current_issue_download">Ausgabe {latest_issue_key}</p>\n
<p><a href="{issue_dir_name}" class="download_button">{LABEL_DOWNLOAD}</a></p>'''
return latest_html
def html_generate_latest_downloads(db):
articles_with_downloads = db.articles_with_downloads()
sorted_articles = sorted(articles_with_downloads, key=lambda x: x.article_pubdate(), reverse=True)[:NEW_DOWNLOADS]
html_parts = [f"<h2>{LABEL_LATEST_LISTINGS}</h2><hr><ul>"]
for article in sorted_articles:
link = article_link(db, article, index_title(article), True)
html_parts.append(f"<li>{link}</li>")
html_parts.append("</ul>")
return ''.join(html_parts)
def html_generate_title_image(db, issue, width, prepend_issue_dir=False):
title_jpg_path = optional_issue_prefix("title.jpg", issue, prepend_issue_dir)
return f"<img src=\"{title_jpg_path}\" width=\"{width}\" alt=\"{MAGAZINE_NAME} {issue.issue_key}\">\n"
def html_generate_toc(db, issue_key, heading_level=1, prepend_issue_dir=False):
html_parts = []
if heading_level == 1:
html_parts.append(f"<main>\n")
html_parts.append(f"<h{heading_level}>{LABEL_ISSUE} {issue_key}</h{heading_level}>\n")
issue = db.issues[issue_key]
pdf_filename = optional_issue_prefix(issue.pdf_filename, issue, prepend_issue_dir)
title_image = html_generate_title_image(db, issue, 300, prepend_issue_dir)
title_image = f"""
<div class="download_full_pdf">
<a href="{pdf_filename}">
{title_image}
<br>
<div class=\"download_full_pdf_button\">
<div class="download_icon"><img src="/{BASE_DIR}pdf.svg" alt="PDF"></div>
<div class="download_label">{LABEL_DOWNLOAD_ISSUE_PDF}</div>
</div>
</a>
</div>\n
"""
html_parts.append('<div class="toc_container">')
html_parts.append(title_image)
toc_entries = db.toc_with_articles(issue_key)
last_category = None
html_parts.append('<div class="toc">')
for entry in toc_entries:
if len(entry['articles']):
category, subcategory = (entry['category'].split('|', 1) + [None])[:2] if '|' in entry['category'] else (entry['category'], None)
if category != last_category:
if category != "":
html_parts.append(f"<h3>{category}</h3>\n")
last_category = category
if subcategory:
html_parts.append(f"<h4>{subcategory}</h4>\n")
html_parts.append('<ul>\n')
for article in entry['articles']:
# link = article_link(db, article, toc_title(article), prepend_issue_dir) # XXX remove
issue = db.issues[article.issue_key]
path = article_path(issue, article, prepend_issue_dir)
title = toc_title(article)
first_page = article.first_page_number()
link = f"""
<a href='{path}'>
<span class="title">{title}<span class="leaders" aria-hidden="true"></span></span> <span class="page"><span class="visually-hidden">Page </span>{first_page}</span>
</a>
"""
html_parts.append(f"<li>{link}</li>\n")
html_parts.append("</ul>\n")
html_parts.append("</div>\n")
html_parts.append("</div>\n")
if heading_level == 1:
html_parts.append(f"</main>\n")
return ''.join(html_parts)
### HTML file content creation
def html_generate_images_all_issues(db, special):
html_parts = []
if special:
issue_keys = (k for k in db.issues.keys() if not k[0].isdigit())
else:
issue_keys = (k for k in db.issues.keys() if k[0].isdigit())
for issue_key in sorted(issue_keys, key=lambda x: db.issues[x].pubdate, reverse=True):
issue = db.issues[issue_key]
title_image = html_generate_title_image(db, issue, 200, True)
html_parts.append(f"<a href=\"{issue.issue_dir_name}\">{title_image}</a>\n")
return ''.join(html_parts)
def html_generate_tocs_all_issues(db):
# Once we have many "Sonderheft" issues, we may consider splitting
# them into a separate main tab, i.e.
# Ausgaben – Sonderhefte – Artikel – Listings
html_parts = []
html_parts.append(f"<main>\n")
html_parts.append(f"<h1>{LABEL_ALL_ISSUES}</h1>\n")
# top: all issue title images (first regular, then special)
if db.latest_special_issue_key():
html_parts.append(f"<h2>{LABEL_REGULAR_MAGAZINES}</h2>\n")
html_parts.append(html_generate_images_all_issues(db, False))
html_parts.append("<hr>\n")
if db.latest_special_issue_key():
html_parts.append(f"<h2>{LABEL_SPECIAL_MAGAZINES}</h2>\n")
html_parts.append(html_generate_images_all_issues(db, True))
html_parts.append("<hr>\n")
# below: all TOCs
for issue_key in sorted(db.issues.keys(), key=lambda x: db.issues[x].pubdate, reverse=True):
html_parts.append(html_generate_toc(db, issue_key, 2, True))
html_parts.append("<hr>\n")
html_parts.append(f"</main>\n")
return ''.join(html_parts)
def html_generate_articles_for_categories(db, index_categories, alphabetical, issue_key=None, append_issue_number=False):
articles = db.articles_by_index_categories(index_categories, issue_key)
if not articles:
return None
if alphabetical:
articles = sorted(articles, key=lambda x: index_title(x).lower())
html_parts = []
html_parts.append(f"<ul>\n")
for article in articles:
if append_issue_number:
issue_number = f" [{article.issue_key}]"
else:
issue_number = ""
link = article_link(db, article, index_title(article), True)