-
Notifications
You must be signed in to change notification settings - Fork 3
/
litstash.py
1525 lines (1191 loc) · 56.8 KB
/
litstash.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
# LICENSE INFORMATION: GNU GPLv3.0-or-later
# litstash is a downloader of submissions from Literotica and xnxx stories
# Copyright (C) 2023 NocturnalNebula <nocturnalnebula@proton.me>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# < --- PROGRAM BEGINS BELOW --- >
# This is a long script and is best read in an IDE with all functions collapsed/folded.
# import modules (all from standard library)
import urllib.request
import urllib.error
import os
import sys
import time
import json
import traceback
# initialize global variables
origCwd = os.getcwd()
downloadList = []
version = 'Version: 1.8'
updated = 'Updated: July 2024'
usage = '''
litstash is a story downloader with support for the sites Literotica and xnxx,
including Wayback Machine captures of either site
usage:
litstash [option]
litstash ["URL"...]
OR (if running script with Python)
python litstash.py [option]
python litstash.py ["URL"...]
options:
-h, --help print usage guide
--version print version number
-a automatically download all detected submissions
URL:
- URLs should be surrounded by "quotes" to prevent an '&' from confusing the shell
- URLs are any of the following:
- Literotica submission (story, poem, audio, illustration)
- xnxx story (sexstories.com)
- any page containing links to either of the above
- Series Pages (for batch downloading a series)
- Author Pages (for batch downloading all of an author's works)
- Wayback Machine capture of any of the above
- multiple URLs can be included
examples:
python litstash.py --version
python litstash.py https://www.literotica.com/s/an-erotic-story-9 https://www.literotica.com/p/a-smutty-poem-8
python litstash.py https://www.literotica.com/series/se/00000
python litstash.py https://www.literotica.com/authors/a-literotica-author
python litstash.py "https://web.archive.org/web/20130919123456/https://www.literotica.com/s/a-deleted-story-4"
python litstash.py -a "https://web.archive.org/web/20130723123456/https://www.literotica.com/stories/memberpage.php?uid=0000000&page=submissions"
more:
- downloads will be saved in 'litstash-saves' created in the current working directory
- visit https://github.com/NocturnalNebula/litstash/releases to check for new versions
contact:
- created in Jan 2023 by NocturnalNebula
- email: nocturnalnebula@proton.me
'''
# CLASSES
class literotica:
def __init__(self, url):
# immediately defined
self.url = url
self.slug = self.url.split('/')[-1]
self.publisher = "Literotica"
self.apiData = {} # dict from rest api
self.pageSource = ''
# submission metadata
self.title = ''
self.username = ''
self.series = ''
self.date = ''
self.description = ''
self.category = ''
self.pages = 1 # total pages in submission, default=1, change later
# submission text attributes
self.text = ''
self.currentPage = 1
self.wordCount = ''
self.skip = 0 # skipping flag if there is a problem getting page source
# build items
self.output = ''
self.path = ''
self.filename = ''
def getApiData(self):
# collect data from api, put into a dict
url = 'https://literotica.com/api/3/stories/'+self.slug+'?params={"contentPage":'+str(self.currentPage)+'}'
source = getSource(url)
if source == 'skip': self.skip = 1; return
self.apiData = json.loads(source)
# submission should be skipped if they don't have page text, unless they are illustrations
if not 'pageText' in self.apiData:
if self.apiData['submission']['category_info']['pageUrl'] in ['adult-comics','erotic-art']:
return
print('No submission text. Skipping...')
self.skip = 1
# PRIMARY METHODS
def download(self):
# collect all data needed to export the submission
print(f"\n[Downloading] {cleanTitle(self.url)} ({getSite(self.url)})")
print(f"[URL] {self.url}")
# loop through each page of the story, scraping the text of each page
while self.currentPage <= self.pages:
self.getApiData()
if self.skip == 1: return
# get metadata on first loop
if self.currentPage == 1:
self.pages = self.apiData['meta']['pages_count']
if self.pages is None: self.pages = 1
# rearrange date into year/month/day format
date = self.apiData['submission']['date_approve'].split('/')
self.date = ('-').join([date[2],date[0],date[1]])
# ensure title is a string (default will be int if only digits)
self.title = str(self.apiData['submission']['title']).replace('/','-')
self.username = str(self.apiData['submission']['authorname'])
self.description = str(self.apiData['submission']['description'])
self.category = getCategory(self.apiData['submission']['category_info']['pageUrl'])
# get series data only if it exists
try:
self.series = self.apiData['submission']['series']['meta']['title']
except TypeError:
pass
# need to get real page source for illusration categories
if self.category == 'Adult Comics' or self.category == 'Erotic Art':
# get page source to gather pageText, send it into getImages
url = self.url + '?page=' + str(self.currentPage)
self.pageSource = getSource(url)
pageText = cleanIllustrationSource(self)
elif self.apiData['pageText'] is not None:
pageText = self.apiData['pageText']
pageText = pageText.replace('\r\n\r\n','</p>\n<p>')
pageText = pageText.replace('\r\n','<br>\n')
else:
pageText = ''
# if category = Audio, search page for audio links and append to pageText
if self.category == 'Audio' or self.category == 'Poetry With Audio':
url = self.url + '?page=' + str(self.currentPage)
pageText = getAudio(pageText, getSource(url), self.title, self.username)
# append current page text to master text string
self.text += f"<p>{pageText}</p>"
print(f"[Saved] Page {self.currentPage} of {self.pages}")
self.currentPage += 1
self.wordCount = wordCount(self.text)
# scan finished master text string for <img> tags and to download any images (for illustrated stories)
self.text = getImages(self.text, self.username)
def build(self):
# prepare all retrieved submission data for export
self.output = getOutput(self)
self.path = getPath(self.username)
self.filename = getFilename(self.date,self.title)
def export(self):
export(self.path, self.filename, self.output)
class waybackMachineLit:
def __init__(self, url):
# immediately defined
self.url = url
self.slug = self.url.split('/')[-1]
self.authorPageUrl = ''
self.publisher = "Literotica"
self.pageSource = ''
# submission metadata (filled with first page)
self.scheme = '' # Modern / Classic / Pre-Classic / Original
self.title = ''
self.username = ''
self.series = ''
self.date = ''
self.description = ''
self.category = ''
self.pages = 1 # total pages in submission (default = 1, change later)
# submission text attributes
self.text = ''
self.pageText = ''
self.currentPage = 1
self.wordCount = ''
self.skip = 0 # skipping flag if there is a problem getting page source
# build items
self.output = ''
self.path = ''
self.filename = ''
# HELPER METHODS
def getDateFromAuthor(self):
# for submissions without an upload date, retrieve it from the author page
if self.authorPageUrl == '':
print('Cannot find author page URL.')
print('Try a different Wayback Machine capture to include the upload date.')
self.date = '0000-00-00'
return
if self.authorPageUrl.startswith('//'):
self.authorPageUrl = 'https:'+ self.authorPageUrl
authorPageSource = getSource(self.authorPageUrl.replace('&','&'))
# some author pages won't be captured by wayback machine
if '<b>This member does not exists</b>' in authorPageSource:
print('No capture available of author page.')
print('Try a different Wayback Machine capture to include the upload date.')
self.date = '0000-00-00'
return
else:
# put the index before the relevant entry
i = authorPageSource.find(f'/{self.slug}')
if i == -1:
print('Cannot find submission upload date on author page.')
print('Try a different Wayback Machine capture to include the upload date.')
self.date = '0000-00-00'
return
# scan forward from submission url to a substring mataching the date format (>**/**/**) *=digit
date = ''
while len(date) < 9:
if authorPageSource[i] in '0123456789/>': date += authorPageSource[i]
else: date = ''
if len(date) > 0 and date.count('>') != 1: date = ''
i += 1
# create date format year/month/date
date = date[1:].split('/')
self.date = ('-').join(['20'+date[2],date[0],date[1]])
def getPageSource(self, url='', attempts=0):
if attempts == 3:
print('Wayback Machine capture is unavailable.')
self.skip = 1
return
if url != '':
source = getSource(url)
else:
# older captures (pre ~2010) have different url formats
if self.scheme == 'Original' or self.scheme == 'Post-Original':
pageSlug = f"&page={self.currentPage}"
else: pageSlug = f"?page={self.currentPage}"
if self.currentPage == 1: pageSlug = ''
source = getSource(self.url + pageSlug)
self.pageSource = source
if '>Got an HTTP 301 response at crawl time<' in self.pageSource:
print('Got an HTTP Error 301 from Wayback Machine. Redirecting...')
attempts += 1
self.getPageSource(sandwichMaker(self.pageSource,'class="impatient"><a href="','"'),attempts)
if '>Got an HTTP 302 response at crawl time<' in self.pageSource:
print('Got an HTTP Error 302 from Wayback Machine. Redirecting...')
attempts += 1
self.getPageSource(sandwichMaker(self.pageSource,'class="impatient"><a href="','"'),attempts)
if self.pageSource == 'skip':
self.skip = 1
return
def getScheme(self):
# determine lit site scheme of wayback capture
if self.pageSource == '':
print('Error: No page source was loaded')
self.skip = 1
return
# each scheme has subtle differences in html layout, but relevant to data extraction
if 'class="aa_ht"' in self.pageSource: self.scheme = 'Modern'
elif 'class="b-story-body-x x-r15"' in self.pageSource: self.scheme = 'Classic'
elif 'class="b-story-body"' in self.pageSource: self.scheme = 'Pre-Classic'
elif '<font size="2">' in self.pageSource: self.scheme = 'Original'
elif '<div id="content"><p>' in self.pageSource: self.scheme = 'Post-Original'
else:
print('Error: Unable to retrieve submission from this Wayback Machine capture.')
print('Try a different capture of the same submission.')
self.skip = 1
return
def downloadModern(self):
# get metadata on first loop (find all data in the page source)
if self.currentPage == 1:
self.title = sandwichMaker(self.pageSource, '<h1 class="j_bm headline j_eQ">', '<')
self.title = self.title.replace('"','"').replace(''',"'").replace('&','&').replace('/','-')
if '/s/' in self.url:
if self.pageSource.count(f"literotica.com/s/{self.slug}?page=") > 0:
self.pages = int(sandwichMaker(self.pageSource, f"literotica.com/s/{self.slug}?page=", '"', reverse=1))
if '/p/' in self.url:
if self.pageSource.count(f"literotica.com/p/{self.slug}?page=") > 0:
self.pages = int(sandwichMaker(self.pageSource, f"literotica.com/p/{self.slug}?page=", '"', reverse=1))
if '/i/' in self.url:
if self.pageSource.count(f"literotica.com/i/{self.slug}?page=") > 0:
self.pages = int(sandwichMaker(self.pageSource, f"literotica.com/i/{self.slug}?page=", '"', reverse=1))
self.username = sandwichMaker(self.pageSource, 'class="y_eR" title="', '">')
self.description = sandwichMaker(self.pageSource, 'name="description" content="', '">')
# put date in year/month/day format
date = sandwichMaker(self.pageSource, '"date_approve":"', '"').split('/')
self.date = ('-').join([date[2],date[0],date[1]])
self.wordCount = sandwichMaker(self.pageSource, '"words_count":', ',')
self.category = getCategory(sandwichMaker(self.pageSource, '/https://www.literotica.com/c/', '"'))
print('[Retrieved] Submission Metadata')
# extract and clean up pageText from pageSource
# illustration categories have <img> tags below normal page text
if self.category == 'Adult Comics' or self.category == 'Erotic Art':
self.pageText = sandwichMaker(self.pageSource,'<div class="aa_ht">','<div class="aa_hv aa_hy">')
else:
self.pageText = self.pageSource.split('<div class="aa_ht">')
self.pageText = self.pageText[1].replace('<div>','').replace('</div>','')
def downloadClassic(self):
# get metadata on first loop
if self.currentPage == 1:
title = sandwichMaker(self.pageSource,'<h1>','</h1>')
self.title = title.replace('"','"').replace(''',"'").replace('&','&').replace('/','-')
self.pages = int(sandwichMaker(self.pageSource,'<!-- x -->',' Pages'))
self.username = sandwichMaker(self.pageSource,'page=submissions">','</a>')
self.description = sandwichMaker(self.pageSource,'name="description" content="','"')
self.category = getCategory(sandwichMaker(self.pageSource, 'literotica.com/c/', '"'))
self.authorPageUrl = sandwichMaker(self.pageSource,'<!-- ! --></span><a href="','"')
self.getDateFromAuthor()
print('[Retrieved] Submission Metadata')
self.pageText = sandwichMaker(self.pageSource,'b-story-body-x x-r15"><div>','</div>')
def downloadPreClassic(self):
# get metadata on first loop
if self.currentPage == 1:
title = sandwichMaker(self.pageSource,'<h1>','</h1>')
self.title = title.replace('"','"').replace(''',"'").replace('&','&').replace('/','-')
self.pages = int(sandwichMaker(self.pageSource,'"b-pager-caption">',' Pages'))
self.username = sandwichMaker(self.pageSource,'page=submissions">','</a>')
self.description = sandwichMaker(self.pageSource,'name="description" content="','"/')
self.category = sandwichMaker(self.pageSource,'>','<',self.pageSource.find('category.php'))
self.authorPageUrl = sandwichMaker(self.pageSource,'class="b-story-user"><a href="','">')
self.getDateFromAuthor()
print('[Retrieved] Submission Metadata')
self.pageText = sandwichMaker(self.pageSource,'class="b-story-body">','</div>')
def downloadPostOriginal(self):
if self.currentPage == 1:
self.title = sandwichMaker(self.pageSource,'<h1>','</h1>')
self.title = self.title.replace('"','"').replace(''',"'").replace('&','&').replace('/','-')
print('Title: ' + self.title)
self.pages = self.pageSource.count(self.slug + '&page=')
if self.pages == 0: self.pages = 1
self.username = sandwichMaker(self.pageSource,'page=submissions">','</a>')
self.description = sandwichMaker(self.pageSource,'name="description" content="','"')
self.category = sandwichMaker(self.pageSource,'>','<',self.pageSource.find('category.php'))
self.authorPageUrl = sandwichMaker(self.pageSource,'by <a href="','"')
self.getDateFromAuthor()
print('[Retrieved] Submission Metadata')
self.pageText = '<p>' + sandwichMaker(self.pageSource,'<div id="content"><p>','</p>') + '</p>'
def downloadOriginal(self):
if self.currentPage == 1:
self.title = sandwichMaker(self.pageSource,'Helvetica"><strong>','<')
self.title = self.title.replace('"','"').replace(''',"'").replace('&','&').replace('/','-')
print('Title: ' + self.title)
self.pages = self.pageSource.count(self.slug + '&page=')
if self.pages == 0: self.pages = 1
self.username = sandwichMaker(self.pageSource,'page=submissions">','</a>',self.pageSource.find('Helvetica"><strong>'))
self.description = sandwichMaker(self.pageSource,'name="description" content="','"')
self.category = sandwichMaker(self.pageSource,'>','<',self.pageSource.find('category.php'))
self.authorPageUrl = sandwichMaker(self.pageSource,'by <a href="','"')
self.getDateFromAuthor()
print('[Retrieved] Submission Metadata')
self.pageText = '<p>' + sandwichMaker(self.pageSource,'<font size="2"><br/>','</font>') + '</p>'
# PRIMARY METHODS
def download(self):
# collect all data needed to export the submission, calling the appropiate download functions for each scheme
print(f"\n[Downloading] {cleanTitle(self.url)} ({getSite(self.url)})")
print(f"[URL] {self.url}")
# loop through each page of submission and gather all page text
while self.currentPage <= self.pages:
self.getPageSource()
if self.skip == 1: return
self.getScheme()
# call relevant method to extract page text
if self.scheme == 'Modern': self.downloadModern()
if self.scheme == 'Classic': self.downloadClassic()
if self.scheme == 'Pre-Classic': self.downloadPreClassic()
if self.scheme == 'Post-Original': self.downloadPostOriginal()
if self.scheme == 'Original': self.downloadOriginal()
if self.skip == 1: return
# extract and save any audio files (only for audio categories)
if self.category == 'Audio' or self.category == 'Poetry With Audio':
self.pageText = getAudio(self.pageText, self.pageSource, self.title, self.username)
# process page text for illustration categories
if self.category == 'Adult Comics' or self.category == 'Erotic Art':
self.pageText = cleanIllustrationSource(self)
self.text += self.pageText
print(f"[Saved] Page {self.currentPage} of {self.pages} ({self.scheme} Site Scheme)")
self.currentPage += 1
self.wordCount = wordCount(self.text)
# send to get images function to extract images from <img> tags
self.text = getImages(self.text, self.username)
def build(self):
# prepare all collected submission data for export
self.output = getOutput(self)
self.path = getPath(self.username)
self.filename = getFilename(self.date,self.title)
def export(self):
export(self.path, self.filename, self.output)
class xnxx:
def __init__(self, url):
# immediately defined
self.url = url
self.publisher = "xnxx"
self.pageSource = ''
# submission metadata
self.title = ''
self.username = ''
self.series = ''
self.date = ''
self.description = ''
self.category = ''
# submission text attributes
self.text = ''
self.wordCount = ''
self.skip = 0 # skipping flag if there is a problem getting page source
# build items
self.output = ''
self.path = ''
self.filename = ''
# PRIMARY METHODS
def download(self):
# collect all data needed to export the submission
print(f"\n[Downloading] {cleanTitle(self.url)} ({getSite(self.url)})")
print(f"[URL] {self.url}")
self.pageSource = getSource(self.url)
if self.pageSource == 'skip': self.skip = 1; return
title = sandwichMaker(self.pageSource,'<h2>\n','<span',self.pageSource.find('<div class="story_info">'))
if title == -1: self.title = 'unkown_title'
else:
self.title = (' ').join(list(filter(None, title.replace('\t','').split(' '))))
self.username = sandwichMaker(self.pageSource,'">','</a>', self.pageSource.find('/profile'))
if self.username == -1: self.username = 'unknown_author'
description = sandwichMaker(self.pageSource,'</h2>\n','</div>',self.pageSource.find('Introduction:'))
if description == -1: self.description = ''
else:
self.description = (' ').join(list(filter(None, description.replace('\t','').split(' '))))
category = sandwichMaker(self.pageSource,'<div class="top_info">\n','</div>').replace('\t','')
self.category = (' ').join(list(filter(None, category.split(' '))))
date = sandwichMaker(self.pageSource,'Posted ','<div id="report">',self.pageSource.find('<div class="story_date">'))
if date == -1: self.date = '0000-00-00'
else:
date = list(filter(None, date.replace('\t','').split(' ')))
if 'ago' in date: self.date = '0000-00-00'
else:
self.date = ('-').join([date[-1],getMonth(date[-2]),'0' + date[1][:-2] if int(date[1][:-2])<10 else date[1][:-2]])
self.text = sandwichMaker(self.pageSource, '<div class="block_panel">', '<!-- VOTES -->', self.pageSource.find('<!-- CONTENT -->'))
self.wordCount = wordCount(self.text)
def build(self):
# prepare all retrieved submission data for export
self.output = getOutput(self)
self.path = getPath(self.username)
self.filename = getFilename(self.date,self.title)
def export(self):
export(self.path, self.filename, self.output)
# HELPER FUNCTIONS
def sandwichMaker(textSource, topBread, bottomBread, start=0, reverse=0):
# return part of a string between two known substrings (the 'filling' of a sandwich)
# returns -1 if cannot find substring
if reverse == 1:
begin = textSource.rfind(topBread) + len(topBread)
else:
begin = textSource.find(topBread, start) + len(topBread)
if begin == (-1 + len(topBread)): return -1
end = textSource.find(bottomBread, begin)
filling = textSource[begin:end]
return filling
def cleanTitle(url):
# convert the submission url into a temp title to display while downloading
# xnxx url
if 'sexstories.com' in url:
if url.endswith('/'): url = url[:-1]
return url.split('/')[-1].replace('_', ' ').title()
# Original Literotica url (no title in url, use number)
if 'literotica.com/stories/showstory.php' in url:
return f"Title Unknown ({url.split('?')[-1]})"
# all other Literotica schemes
if 'literotica.com' in url:
cleanTitle = url.split('/')[-1].split('-')
# remove unimportant numbers from the end of the title
if len(cleanTitle) > 1:
if cleanTitle[-1].isdigit() and cleanTitle[-2].isdigit():
del cleanTitle[-1]
if 'ch' not in cleanTitle and 'pt' not in cleanTitle:
if cleanTitle[-1].isdigit(): del cleanTitle[-1]
# convert back to strings
return (' ').join(cleanTitle).title()
def getSource(url, attempts=0):
# get the webpage html source from a given url and sort all errors
# certain errors require a retry
if attempts == 7:
print('Too many attempts. Try again later.')
return 'skip'
try:
return urllib.request.urlopen(url).read().decode('utf-8')
# catch any error and disply some reasons, then either return or retry
except urllib.error.HTTPError as e:
print('HTTPError - Code: ' + str(e.code) + ' Reason: ' + str(e.reason) + '. ')
print('The following URL caused an error:')
print(url)
if e.code == 410:
return 'skip'
if e.code == 404:
if '//english.' in url:
# original and post-original schemes might need this change
print('Trying a different URL of the same page...')
url = url.replace('//english.','//www.')
return getSource(url, attempts)
return 'skip'
if e.code == 503:
print('Retrying in 5 seconds...')
time.sleep(5)
attempts += 1
return getSource(url, attempts)
if e.code == 504:
print('Gateway Time-out. Retrying in 5 seconds...')
time.sleep(5)
attempts += 1
return getSource(url, attempts)
if e.code == 502:
print('Retrying in 5 seconds...')
time.sleep(5)
attempts += 1
return getSource(url, attempts)
except urllib.error.URLError as e:
print('URLError - Reason: ' + str(e.reason) + '.')
print('The following URL caused an error:')
print(url)
if '104' in str(e.reason):
print('Retrying in 5 seconds...')
time.sleep(5)
attempts += 1
return getSource(url, attempts)
if '110' in str(e.reason):
print('Retrying in 5 seconds...')
time.sleep(5)
attempts += 1
return getSource(url, attempts)
if '111' in str(e.reason):
print('Retrying in 5 seconds...')
time.sleep(5)
attempts += 1
return getSource(url, attempts)
if '-3' in str(e.reason):
print('Retrying in 5 seconds...')
time.sleep(5)
attempts += 1
return getSource(url, attempts)
if '113' in str(e.reason):
print('URL should be in format "https://www.literotica.com/*/... (* = s, p, or i)"')
return 'skip'
except ValueError as e:
print('ValueError on the following URL')
print(url)
print('Literotica URLs should be in the format "https://www.literotica.com/*/... (* = s, p, or i)"')
return 'skip'
except http.client.IncompleteRead:
print('Error: Incomplete Read on the following URL:')
print(url)
print('Retrying in 5 seconds...')
time.sleep(5)
attempts += 1
return getSource(url, attempts)
return
def getPath(username):
# return save path for final export (no spaces in filenames)
return os.path.join(origCwd, 'litstash-saves', username.replace(' ','_'))
def getSite(url):
# check if the submission is from xnxx, literotica, wayback machine
if 'web.archive.org' in url:
if 'literotica.com' in url: return 'Wayback Machine/Literotica'
if 'sexstories.com' in url: return 'Wayback Machine/xnxx'
else:
if 'literotica.com' in url: return 'Literotica'
if 'sexstories.com' in url: return 'xnxx'
return 'unknown'
def cleanIllustrationSource(obj):
# remove unimportant html tags from page source of illustrations
# need to extract pageText iff obj is from literotica (not wayback machine)
if not 'web.archive.org' in obj.url:
pageText = sandwichMaker(obj.pageSource,'<div class="aa_ht">','<div class="aa_hv aa_hy">')
else:
pageText = obj.pageText
# remove all <div> and <div *> tags
counter = 0 # safety against accidental infinit loop
while pageText.count('<div ') > 0:
pageText = pageText.replace(sandwichMaker(pageText,'<div ','>'),'')
pageText = pageText.replace('<div >','')
counter += 1
if counter > 1000: break
pageText = pageText.replace('<div>','')
pageText = pageText.replace('</div>','')
# remove all <p *> tags
counter = 0
while pageText.count('<p ') > 0:
pageText = pageText.replace(sandwichMaker(pageText,'<p ','>'),'')
pageText = pageText.replace('<p >','<p>')
counter += 1
if counter > 1000: break
# remove all <a href=...> tags
counter = 0
while pageText.count('<a href=') > 0:
pageText = pageText.replace(sandwichMaker(pageText,'<a ','>'),'')
pageText = pageText.replace('<a >','')
counter += 1
if counter > 1000: break
pageText = pageText.replace('</a>','')
# change p to f in image names (gives higher res image)
start = 0
for i in range(pageText.count('<img src="')):
imageName = sandwichMaker(pageText,'<img src="','"',start).split('/')[-1]
i = pageText.find(imageName)
pageText = pageText[:i]+'f'+pageText[i+1:]
start = i
# remove any extra '<' or '>'
pageText = pageText.replace('<<','<').replace('<<<','<').replace('>>>','>').replace('>>','>')
# remove <li> and <ul> tags, there shouldn't be bullet points
pageText = pageText.replace('<li>','').replace('</li>','').replace('<ul id="illustra">','').replace('</ul>','')
# return the pageText of an ordinary illustrated story
return pageText
def getCategory(category):
# dictionary to convert from url slug of categories to real category names
categories = {
'anal-sex-stories' : 'Anal', 'audio-sex-stories' : 'Audio', 'bdsm-stories' : 'BDSM',
'celebrity-stories' : 'Celebrities & Fan Fiction', 'chain-stories' : 'Chain Stories',
'erotic-couplings' : 'Erotic Couplings', 'erotic-horror' : 'Erotic Horror',
'exhibitionist-voyeur' : 'Exhibitionist & Voyeur', 'fetish-stories' : 'Fetish',
'first-time-sex-stories' : 'First Time', 'gay-sex-stories' : 'Gay Male',
'group-sex-stories' : 'Group Sex', 'adult-how-to' : 'How To',
'adult-humor' : 'Humor & Satire', 'illustrated-erotic-fiction' : 'Illustrated',
'taboo-sex-stories' : 'Incest/Taboo', 'interracial-erotic-stories' : 'Interracial Love',
'lesbian-sex-stories' : 'Lesbian Sex', 'erotic-letters' : 'Letters & Transcripts',
'loving-wives' : 'Loving Wives', 'mature-sex' : 'Mature', 'mind-control' : 'Mind Control',
'non-english-stories' : 'Non-English', 'non-erotic-stories' : 'Non-Erotic',
'non-consent-stories' : 'NonConsent/Reluctance', 'non-human-stories' : 'NonHuman',
'erotic-novels' : 'Novels and Novellas', 'reviews-and-essays' : 'Reviews & Essays',
'adult-romance' : 'Romance', 'science-fiction-fantasy' : 'Sci-Fi & Fantasy',
'masturbation-stories' : 'Toys & Masturbation',
'transgender-crossdressers' : 'Transgender & Crossdressers',
'erotic-poetry' : 'Erotic Poetry', 'illustrated-poetry' : 'Illustrated Poetry',
'non-erotic-poetry' : 'Non-Erotic Poetry', 'erotic-audio-poetry' : 'Poetry With Audio',
'adult-comics' : 'Adult Comics', 'erotic-art' : 'Erotic Art'
}
return categories[category] if category in categories else category
def getKind(url):
# check if submission is a story, poem, or illustration
if '/s/' in url or '/stories/showstory.php' in url or 'sexstories.com' in url:
return 'Story'
elif '/i/' in url: return 'Illustration'
elif '/p/' in url: return 'Poem'
else: return 'unknown'
def getMonth(month):
month_dict = {
'January' : '01','February' : '02','March' : '03','April' : '04','May' : '05','June' : '06',
'July' : '07','August' : '08','September' : '09','October' : '10','November' : '11','December' : '12'
}
return month_dict[month]
def wordCount(text):
# approximate number of words in the submission text
return len(text.split())
def cleanHexCodes(text):
# remove hexcodes from strings and replace with true character
text = text.replace(''',"'").replace('!','!').replace('"','"').replace('#','#')
text = text.replace('%','%').replace('&','&').replace('(','(').replace(')',')')
text = text.replace('*','*').replace(',',',').replace('.','.').replace('/','/')
text = text.replace(':',':').replace(';',';').replace('?','?').replace('@','@')
return text
def cleanUrl(url):
# ensure each url begins with https:// and a proper domain (some scraped urls are incomplete)
# detect and fix xnxx url
if '/story/' in url:
if not 'sexstories.com' in url: url = 'https://www.sexstories.com' + url
# detect and fix literotica url (if not xnxx, it's literotica)
if not 'sexstories.com' in url:
if not 'literotica.com' in url: url = 'https://www.literotica.com' + url
# detect and fix Wayback Machine url
if '/web/' in url:
if not 'web.archive.org' in url: url = 'https://web.archive.org' + url
# insert 'im_' after retrieval date in wayback machine urls to create direct download links to resources
# specific to Wayback captures of literotica audios and illustrations
if '/illustra/' in url or '/audio/' in url:
url = url.replace('if_/','im_/')
if 'im_/' not in url:
i = url.rfind('/http')
url = url[:i]+'im_'+url[i:]
# ensure that each url begins with https:// before requesting source
if url.startswith('http://'): url = 'https://' + url[7:]
elif url.startswith('//'): url = 'https:' + url
elif url.startswith('www'): url = 'https://' + url
if not url.startswith('https://'): url = 'https://' + url
return url
def export(path,filename,output):
# save final export to file
# check if file path exists, create directories, and change working directory
if not os.path.isdir(path): os.makedirs(path, exist_ok=True)
os.chdir(path)
# output the extracted submission
f = open(filename, 'w', encoding='utf-8')
f.write(output)
f.close()
# return to original working directory
os.chdir(origCwd)
print(f"[Finished] Exported to: {os.path.join(path, filename)}")
def getOutput(obj):
# create the ultimate string which will be the final output
header = (
f'<title>{obj.title}</title>\n\n'
f'<meta name="title" content="{obj.title}">\n'
f'<meta name="author" content="{obj.username}">\n'
f'<meta name="tags" content="{obj.category}">\n'
f'<meta name="series" content="{obj.series}">\n'
f'<meta name="publisher" content="{obj.publisher}">\n'
f'<meta name="pubdate" content="{obj.date}">\n'
)
body_header = (
f'<font size = "1">{obj.url}</font><br>\n'
f'<font size = "5"><b>{obj.title}</b></font><br>\n'
f'<font size = "4">{obj.username}</font><br>\n'
f'<font size = "1">{obj.wordCount} words || {obj.category} || {obj.date}</font><br>\n'
f'<font size = "3"><i>{obj.description}</i></font><br>\n'
f'<font><b>- - - - - - - - - - - - - -</b></font><br>\n'
)
output = (
f'<html>\n\n'
f'<head>\n\n'
f'{header}\n'
f'</head>\n\n'
f'<body>\n\n'
f'{body_header}\n'
f'{obj.text}\n\n'
f'</body>\n\n'
f'</html>\n'
)
return cleanHexCodes(output)
def getFilename(date, title):
# prepare filename of export (include date for sorting, no spaces and minimal puncuation)
title = title.replace('.','').replace(' ','-')
# remove puncuation marks from title
title = title.replace('---','-').replace('--','-').replace(',','').replace('!','').replace('?','')
title = title.replace(':','').replace(';','').replace("'",'').replace('"','').replace('|','')
title = title.replace('[','').replace(']','').replace("<",'').replace('>','').replace('*','')
title = title.replace('/','-').replace('\\','-')
return f"{date}_{title}.html"
def saveFile(fileUrl, fileName, savePath, attempts=0):
# download a resource (image or audio file), sort errors, retry with adjusted URLs
# allow 5 retries
if attempts == 5:
print('Too many attempts. Try again later.')
return 'skip'
success = 0
# check if directory tree exists, create it, and change working directory
if not os.path.isdir(savePath): os.makedirs(savePath, exist_ok=True)
os.chdir(savePath)
try:
urllib.request.urlretrieve(fileUrl,fileName)
success = 1 # success flag
# create exceptions to catch any error and disply some reasons, then either return or retry
except urllib.error.HTTPError as e:
print('HTTPError - Code: ' + str(e.code) + ' Reason: ' + str(e.reason) + '. ')
print('The following URL caused an error:')
print(fileUrl)
if e.code == 410:
print('Skipping this file...')
pass
if e.code == 404:
if '//english.' in fileUrl: # some original and post-original scheme files might need this
print('Trying a different URL of the same file...')
fileUrl = fileUrl.replace('//english.','//www.')
return saveFile(fileUrl, fileName, savePath, attempts)
print('Skipping this file...')
pass
if e.code == 503:
print('Retrying in 5 seconds...')
time.sleep(5)
attempts += 1
return saveFile(fileUrl, fileName, savePath, attempts)
if e.code == 504:
print('Gateway Time-out. Retrying in 5 seconds...')
time.sleep(5)
attempts += 1
return saveFile(fileUrl, fileName, savePath, attempts)
if e.code == 502:
print('Retrying in 5 seconds...')
time.sleep(5)
attempts += 1
return saveFile(fileUrl, fileName, savePath, attempts)
except urllib.error.URLError as e:
print('URLError - Reason: ' + str(e.reason))
print('The following URL caused an error:')
print(fileUrl)
if 'incomplete' in str(e.reason):
print('Retrying in 5 seconds...')