-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch-thread.pl
More file actions
executable file
·1643 lines (1333 loc) · 49.7 KB
/
fetch-thread.pl
File metadata and controls
executable file
·1643 lines (1333 loc) · 49.7 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
#!/usr/bin/perl
# Thread URL, if not already fetched into a file
$threadURL = "";
# Name the the game here - used as the main heading on the index page
# and the page title of updates
# This will also be automatically applied when renumbering a thread
$gameName = "?";
# These following settings should be set to 1 to enable them,
# or to 0 to disable them
# Fetch images and videos
# (you might want to temporarily disable this for faster testing)
$downloadFiles = 1;
# Fetch videos (for hybrid LPs)
$downloadVideos = 0;
# Use automatic chapter naming - names chapters by picking up the first
# bold-texted line of a post, or the first line matching one of the words
# in chapterWords list below)
$autoChapters = 1;
# You're unlikely to need to change the following settings:
# Minimum number of images (excluding emoticons) to make a post count
# as a valid update (otherwise it will be skipped)
$minImages = 2;
# Only use posts made by the thread author
$authorPosts = 1;
# Accept posts even if they have no images, as long as they have links
# to videos (<a href=... to a known video site) (can be useful for hybrid LPs)
$videoPosts = 0;
# Threshold above which automatic chapter naming will be used. Expressed
# as a percentage of posts where an automatic chapter name was found against
# the total number of chapters found in the thread.
$autoChapThresh = 75;
# Optional parameters specific to wget
# - Retry downloading files up to a maximum of 3 times
$wgetParms = "--tries=3";
# List of words that, if matched on a line, become the chapter title
@chapterWords = ('Chapter ', 'Update ', 'Episode ');
# List of sites that contain videos (so any hrefs referring to these
# sites are most likely videos)
@videoSites = ('dailymotion.com', 'youtube.com', 'video.google.[^/]+');
# Other sites containing videos (to mark a post as containing content,
# but not actually downloading the video/making a Backup link)
@otherVidSites = ('filefront.com', 'vimeo.com', 'blip.tv');
# These lines are required for Firefox and Chrome cookie handling
# Remove them if they cause problems but cookies may fail
use DBD::SQLite;
use File::Copy;
# Black hole file for checking a file exists on the server
$nullFile = "/dev/null";
# renum'ing? - ie, does index.html exist?
if(-s "index.html") {
&renumThread;
exit;
}
# Ok, we're fetching
# OS and cookie detection
# - Auto-detects by default
# Windows: Firefox, IE Mac OS X: Firefox, Safari
if($^O eq "MSWin32") {
$isWin32 = 1;
$nullFile = "NUL";
($uid, $pass) = &detectWinCookies;
} elsif($^O eq "darwin") {
$isMacOS = 1;
($uid, $pass) = &detectMacCookies;
# Set wget executable if it isn't already
if(-f 'wget' && ! -x 'wget') {
system("/bin/chmod u+x wget");
}
# Add the current directory to the path so wget works if it's there
$ENV{'PATH'} = $ENV{'PATH'} . ':.';
} elsif(-f $ENV{"HOME"} . "/sacookies") {
# - other OSes 'Auto-detect' effort, check ~/sacookies
# Read file to $cookies
local $/=undef;
open COOKIES, $ENV{"HOME"} . "/sacookies" or die "Failed to open file $!";
my $cookies = <COOKIES>;
close COOKIES;
# first two lines are uid and pass
($uid, $pass) = split("\n", $cookies);
}
# - or manual settings:
if(! $uid) {
# username ('bbuserid' cookie)
$uid = "123456";
# password ('bbpassword' cookie)
$pass = "65517c0bb4f3b05648502d1917fb2c6a";
}
$scriptStart = time;
print "Script started at ", scalar(localtime($scriptStart)), "\n\n";
# If no thread URL, and there isn't exactly one argument passed
# try to default to showthread.txt If that doesn't exist, fail
if(! $threadURL) {
if($#ARGV != 0) {
if(-s "showthread.txt") {
$ARGV[0] = "showthread.txt";
} else {
print "Syntax: $0 filename\n";
exit 1;
}
}
} else {
&getThread($threadURL);
$ARGV[0] = "autoFetchedThread.txt";
}
open(IN, "<$ARGV[0]") || die "Couldn't open file $ARGV[0]: $!\n";
# Pre-count the number of posts in the file
$postCount = 0;
while(<IN>) {
if(/<!-- EndContentMarker --/) { $postCount++; }
}
# And return to the start of the file
seek(IN, 0, SEEK_SET);
# $upd: -1 is no updates, 0 is the OP
$upd = -1; $post = 0; $gotUpdate = 0;
$authorName = "?"; $currAuthor = "?";
$firstDate = "?"; $lastDate = "?";
$threadName = "?"; $threadURL = "?";
$numVids = 0; $vidSize = 0;
$errors = ""; $skippedImgFile = ""; $skippedVidFile = "";
if($autoChapters) {
# Start by running through to check how many valid posts have
# automatically-recognised chapter titles
$chapTitleChecking = 1; $useAutoChapters = 1;
$chapTitlesGot = 0;
# Only interested in posts rather than stats/info here
# Still need to catch the author for authorPosts check
while(<IN>) {
# Found a post
if(/<!-- BeginContentMarker -->/) {
# Skip it if authorPosts is on and it's not by the thread author
unless($authorPosts && ($currAuthor ne $authorName)) {
&getPost;
}
}
elsif(/<dt class="author/) { # Store author for this post
($currAuthor) = m#<dt class="author(?: op)?" title="">(.+)</dt>#;
if($authorName eq "?" && $currAuthor) { # Store thread author (first author found)
$authorName = $currAuthor;
}
}
}
}
# Catch empty thread download
if($upd == -1 && $autoChapters) {
print "\nNo posts found in thread. Possibly your SA browser cookies were not found (see above), you don't have archives access (if applicable), or there is a temporary server error.\n";
print "\nThe contents of autoFetchedThread.txt may be useful.\n";
# Wait before exiting
print "\nPress enter to finish\n";
$junk = <STDIN>;
exit;
}
# Set automatic chapter naming to off
$useAutoChapters = 0;
# unless the percentage is met
if($autoChapters && ($chapTitlesGot / ($upd + 1)) >= ($autoChapThresh / 100)) {
$useAutoChapters = 1;
}
# Back to the start again
seek(IN, 0, SEEK_SET);
# Reset things
$chapTitleChecking = 0;
$upd = -1; $post = 0;
$currAuthor = "?"; $authorName = "?";
$OPcontent = "";
# Go through the file until you hit a post, useful thing or the file ends
while(<IN>) {
# Found a post
if(/<!-- BeginContentMarker -->/) {
# Skip it if authorPosts is on and it's not by the thread author
unless($authorPosts && ($currAuthor ne $authorName)) {
&getPost;
} else {
# Just increase the post count
$post++;
}
}
elsif(/<dt class="author/) { # Store author for this post
($currAuthor) = m#<dt class="author(?: op)?" title="">(.+)</dt>#;
if($authorName eq "?" && $currAuthor) { # Store thread author (first author found)
$authorName = $currAuthor;
}
}
# $gotUpdate is only set if the last post retrieved was
# a valid content-containing one (ie, one with images)
elsif(/<td class="postdate">/ && $gotUpdate) { # First/last post date
$junk = <IN>; # blank line
$junk = <IN>; # post number
$junk = <IN>; # thread/user numbers
$_ = <IN>; # actual date info
($lastDate) = m#(\w+ \d+, \d+) \d+:\d+#;
if($firstDate eq "?") { $firstDate = $lastDate; }
# Tack the date onto the update file in case of renumbering
if($upd > 0) {
open(OUT, ">>$postDir/index.html");
print OUT "<!-- date $lastDate -->\n";
close(OUT);
}
$gotUpdate = 0;
}
elsif(/<title>/) { # Thread name
($threadName) = m#^\s+<title>(.+) - The Something Awful Forums</title>#;
}
elsif(/<label>Search thread: /) { # Thread ID (generate URL)
($threadID) = m#name="threadid" value="(\d+)"#;
$threadURL = "http://forums.somethingawful.com/showthread.php?threadid=$threadID";
}
}
close(IN);
# Delete temporary file if we downloaded the thread ourselves
if($threadURL) { unlink 'autoFetchedThread.txt'; }
# Need to delete the 'next' links from the final update
# Read in the existing file
open(IN, "<$postDir/index.html");
@lines = <IN>;
close(IN);
# And write it straight back out, minus the offending lines
$checking = 0;
open(OUT, ">$postDir/index.html");
for $l (@lines) {
if($checking) {
next if $l =~ />Next</;
}
print OUT $l;
if($l =~ /<!-- NOTE: Don't change the layout of these/) {
$checking = 1;
} elsif($l =~ /<!-- Chapter Titles are specified in the TOC/) {
$checking = 0;
}
}
close(OUT);
# Fetch smilies (should be virtually guaranteed)
if(%smilies) {
mkdir "Smilies";
for $smileyURL (keys %smilies) {
$smileyFile = $smilies{$smileyURL};
# Strip the "../Smilies/" from the filename
$smileyFile =~ s#^.+/##;
print "Fetching smiley $smileyFile ($smileyURL)...";
if($downloadFiles) {
system(qq#wget $wgetParms -nv -o wgeterr.txt -O "Smilies/$smileyFile" "$smileyURL"#);
} else {
$? = 0; # fake success
}
if($? != 0) {
print "failed\n";
$errors .= "* failed download of $smileyFile ($smileyURL)\n";
open(ERR, "<wgeterr.txt");
while(<ERR>) { $errors .= $_; }
close(ERR);
} else {
print "ok\n";
}
}
}
# Retry fetching any images that failed previously
for $fImg (@failedImgs) {
($failDir, $failFile, $failURL, $failText) = @$fImg;
print "Retrying: $failText ($failURL)...";
if($downloadFiles) {
system(qq#wget $wgetParms -nv -o wgeterr.txt -O "$failDir/$failFile" "$failURL"#);
} else {
$? = 0; # fake success
}
if($? != 0) {
print "failed\n";
$errors .= "* failed download of $failDir/$failFile ($failURL), even after retrying\n";
# mark up missing image
# read file (need all in one line to do multi-line matches)
open(INDEX, "<$failDir/index.html");
$indexFile = do { local $/; <INDEX> };
close(INDEX);
# replace
$indexFile =~ s#<img src="$failFile" alt="" class="img" border="0">#<missing>$failFile</missing>#g;
$indexFile =~ s#<a href="$failFile(.*?)</a>#<missing>$failFile</missing>#gsm;
# write file
open(INDEX, ">$failDir/index.html");
print INDEX $indexFile;
close(INDEX);
open(ERR, "<wgeterr.txt");
while(<ERR>) { $errors .= $_; }
close(ERR);
} else {
print "ok\n";
$errors .= "* succeeded in retrying download of $failDir/$failFile ($failURL)\n";
}
}
# Remove wget error file (if it was generated, either here or earlier)
unlink 'wgeterr.txt';
# Create the index
open(IDX, ">index.html") || die "Couldn't create index: $!\n";
print IDX <<HEADER1;
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="content-language" content="en" />
</head>
<body>
<!-- NOTE: Don't change the layout of these, it will be parsed by a script. -->
<h1>Title: $gameName</h1>
<h1>Author: $authorName</h1>
<h1>Thread: $threadName</h1>
<h1>Begin Date: $firstDate</h1>
<h1>End Date: $lastDate</h1>
<h1>Num Updates: $upd</h1> <!-- This is the number of videos for a video LP-->
<h1>Author Webpage: ---</h1>
<!-- !!DO NOT REMOVE!! BEGIN_CONTENT !!DO NOT REMOVE!! -->
<h1>Introduction</h1>
$OPcontent<br />
<h1>Table of Contents</h1>
<ul class="toc">
<!-- BEGIN_TOC -->
HEADER1
for($i=1; $i<=$upd; $i++) {
print IDX qq#<li><a href="Update%20# . sprintf("%02d", $i) . qq#/">$chapTitles[$i]</a></li>\n#;
}
print IDX <<FOOTER;
<!-- END_TOC -->
</ul>
<!-- !!DO NOT REMOVE!! END_CONTENT !!DO NOT REMOVE!! -->
</body>
</html>
FOOTER
close(IDX);
#print "\nPer-post statistics:\n";
if(scalar(@videoURLs)) {
print "\nVideos downloaded:\n";
open(V, ">stats.txt");
$vNum = 1;
for($i=0; $i<=$#postStats; $i++) {
($img, $vid) = @{$postStats[$i]};
#if($vid) { print "V "; } else { print " "; }
#printf "%3d: %3d images, %2d videos\n", $i+1, $img, $vid
if($vid) {
if($vid == 1) {
$txt = sprintf "%10s: video %d\n", "Update " . ($i+1), $vNum;
} else {
$txt = sprintf "%10s: videos %d-%d\n", "Update " . ($i+1), $vNum, $vNum+$vid-1;
}
print $txt; print V $txt;
$vNum += $vid;
}
}
$txt = "- Total videos: " . scalar(@videoURLs) . "\n";
print $txt; print V $txt;
$txt = sprintf "- Total video size: %2.2f MB\n", ($vidSize / 1048576);
print $txt; print V $txt;
close(V);
} else {
unlink "stats.txt";
}
if($errors) {
print "\nErrors:\n";
print $errors;
open(V, ">>stats.txt");
print V "\nErrors:\n";
print V $errors;
close(V);
}
$scriptEnd = time;
print "\nScript ended at ", scalar(localtime($scriptEnd)), "\n";
$elapsed = $scriptEnd - $scriptStart;
print "Elapsed time: ";
if($elapsed < 60) { print "$elapsed seconds\n"; }
else {
$elapsedM = int($elapsed / 60); $elapsedS = $elapsed % 60;
printf "$elapsedM minute%s, $elapsedS second%s\n",
($elapsedM == 1 ? "":"s"), ($elapsedS == 1 ? "":"s");
}
if($isWin32) {
$winConsole->Title("Finished - $gameName");
}
# Wait before exiting
print "\nPress enter to finish\n";
$junk = <STDIN>;
# Subroutines
# Extract an entire post from a thread list, save the images
sub getPost {
$post++;
$img = 0; $vidStart = $numVids; $vidEnd = $vidStart;
$keepPost = 0; $quoting = 0;
$chapTitle = "";
undef %images; undef @newVids;
$postBody = "";
while(<IN>) {
# Ignore these
next if /<!-- google_ad_section_start -->/;
next if /<!-- google_ad_section_end -->/;
# End of post marker
last if /<!-- EndContentMarker -->/;
# Fix the line ending to match the downloader's platform
# (to make editing the output files easier)
tr/\r\n//d;
$_ .= "\n";
# Start/end a quote?
if(m#<blockquote #) {
$quoting = 1;
} elsif(m#</blockquote>#) {
$quoting = 0;
}
# Chapter title? (first bolded item in post, or matched word)
if(! $quoting && $useAutoChapters && ! $chapTitle) {
$isTitle = 0;
if(m#<b># && m#</b>#) {
($chapTitle) = m#<b>(.+)$#;
$isTitle = 1;
} else {
# Match word?
for $word (@chapterWords) {
if(/$word/) { $isTitle = 1; $chapTitle = $_; }
}
}
if($isTitle) {
# Remove any other tags
$chapTitle =~ s#</?[^>]+>##g;
# Remove line ending character
chomp;
}
}
# Check for HREFs to videos
if(m#<a href=#) {
do { # keep going until we get a valid video or run out of links
($URL, $title) = m#<a href="(http://[^"]+)"[^>]*>([^<]+)</a>#;
if(! $title) { # Can happen with image-only video links
($URL) = m#<a href="(http://[^"]+)"[^>]*>.+</a>#;
$title = "(no title)";
}
# Video?
$isVideo = 0;
for $site (@videoSites) {
if($URL =~ /$site/) { $isVideo = 1; }
}
if(! $isVideo) {
for $site (@otherVidSites) {
if($URL =~ /$site/) { $isVideo = 2; }
}
}
if($isVideo == 1) {
# Avoid duplicate videos
$vidNumber = 0;
for($i=0; $i<=$#videoURLs; $i++) {
if($videoURLs[$i] eq $URL) { $vidNumber = $i+1; }
}
# If we don't already have it, add it to the potential new video
# list (discarded if the post is not kept)
if(! $vidNumber) {
push(@newVids, $URL);
$vidEnd++;
$vidNumber = $vidEnd;
} # else vidNumber is already the number of the existing video
# Add a 'backup' link
unless(! $downloadFiles || ! $downloadVideos) {
s#(<a href[^<]+</a>)#$1 / <a href="../Videos/video$vidNumber.AVI" target="_blank" rel="nofollow">Backup</a>#;
}
}
if($isVideo) { # Do this even if it's not a downloadable video
if(! $quoting && $videoPosts) { $keepPost = 1; }
}
# Skip reprocessing this link
s#<a href#<x href#;
} while(m#<a href# && ! $isVideo);
# Restore links
s#<x href#<a href#g;
}
# Catch images
# loop in case there's multiple images on one line, try repeatedly
while(m#<img (width=\d+ )?src="http://# ||
m#<a href="http://[^/]+waffleimages\.com# ||
m#<a href="http://lpix\.org/# ||
m#<a href="http://[^/]+photobucket\.com# ||
m#<a href="http://[^/]*imgur\.com/# ||
m#<a href="http://[^/]*tinypic\.com/#) {
# Pick out the URL
($imgURL) = m#<img (?:width=\d+ )?src="(http://[^"]+)"#;
if(! $imgURL) { # oh, it's a href one
($imgURL) = m#<a href="(http://[^"]+)"#;
}
# Keep untouched URL for s/// later
$origImgURL = $imgURL;
# ImageSocket fix
$imgURL =~ s#http://imagesocket.com/#http://content.imagesocket.com/#;
# SALR (or similar) fix
$imgURL =~ s/#[^#]+$//;
# Un-mirror-server waffleimages links
$imgURL =~ s#http://[^/]+.mirror.waffleimages.com/files/../([^\.]+)\.(.+)$#http://img.waffleimages.com/$1/waffle.$2#;
# Do we already have this? (standard or smiley)
if($images{$imgURL}) {
# Yes - just change the link to the image to the existing one
$newImgLink = $images{$imgURL};
} elsif($smilies{$imgURL}) {
$newImgLink = $smilies{$imgURL};
} elsif($imgURL =~ m#http://i.somethingawful.com/forumsystem/emoticons/#
|| $imgURL =~ m#http://i.somethingawful.com/images/#
|| $imgURL =~ m#http://fi.somethingawful.com/images/smilies/#) {
# No, but it's a smiley
($smileyFile) = ($imgURL =~ m#/([^/]+)$#);
# Do we somehow already have it?
@haveList = grep(/$smileyFile$/, values %smilies);
if(@haveList) {
$errors .= "* Duplicate smiley $smileyFile at @haveList and $imgURL. Expect strange results.\n";
}
$newImgLink = "../Smilies/$smileyFile";
$smilies{$imgURL} = $newImgLink;
} else {
# No, so get a filename for it
$img++;
($newImgLink) = ($imgURL =~ m#/([^/]+)$#);
if($newImgLink !~ /\..{1,3}$/) { $newImgLink .= '.'; }
# Change spaces and magic characters to _
$newImgLink =~ s/ /_/g;
$newImgLink =~ s/%[\dA-F]{2}/_/g;
# Add the image number to it
$newImgLink = "$img-$newImgLink";
# and store the old/new image links in case they're used again
$images{$imgURL} = "$newImgLink";
if((! $quoting) && ($img >= $minImages)) { $keepPost = 1; }
}
# Adjust the post for the new image location
s/\Q$origImgURL\E/$newImgLink/;
}
$postBody .= $_;
}
if($chapTitleChecking) {
if($keepPost) {
$upd++;
if($chapTitle) { $chapTitlesGot++; }
$keepPost = 0;
}
} else {
# Accept the OP as a valid post regardless of any restrictions
# (unless we're chapter-checking)
if($upd == -1) { $keepPost = 1; }
}
if(! $keepPost) {
# Keeping requires: $minImage images or a video href (if videoPosts is on)
# not contained inside a [quote] (a <blockquote>)
if(! $chapTitleChecking) {
print "*** Skipping non-content post (would have been chapter ",$upd+1,")\n";
}
} else {
# This post was valid, so accept post date immediately below it
$gotUpdate = 1;
$upd++;
# Fix definitely typo filter
$postBody =~ s/\[NOTE: I AM TOO STUPID TO SPELL THE WORD "DEFINITELY" CORRECTLY\]/definitely/g;
# OP -> $OPcontent, otherwise write an index.html
if($upd == 0) {
$OPcontent = $postBody;
$OPcontent =~ s#img src="\.\./Smilies#img src="Smilies#g;
$postDir = ".";
} else {
# Create a title if one wasn't found in the post
if(! $chapTitle) { $chapTitle = "Chapter $upd"; }
# store it
$chapTitles[$upd] = $chapTitle;
# Create a directory to put it all in
$postDir = sprintf("Update %02d", $upd);
mkdir $postDir || die $!;
# Generate the HTML file
open(OUT, ">$postDir/index.html") || die $!;
print OUT <<HEADER;
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="content-language" content="en" />
</head>
<body>
<!-- NOTE: Don't change the layout of these, it will be parsed by a script. -->
HEADER
# Next/previous links
&addHdr;
print OUT "\n<!-- Chapter Titles are specified in the TOC in the index -->\n\n";
# Main content
print OUT "<!-- !!DO NOT REMOVE!! BEGIN_CONTENT !!DO NOT REMOVE!! -->\n";
print OUT $postBody;
print OUT "<!-- !!DO NOT REMOVE!! END_CONTENT !!DO NOT REMOVE!! -->\n";
print OUT "</body>\n";
print OUT "</html>\n";
close(OUT);
}
# Download images
$iNum = 0; $iCount = keys %images;
foreach $imgURL (sort { $images{$a} <=> $images{$b} } keys %images) {
$iNum++;
$imgFile = "$postDir/$images{$imgURL}";
# Skip already-downloaded files
if(-s $imgFile) {
print "Skipping image $imgFile ($imgURL), already exists\n";
$skippedImgFile = $imgFile;
$skippedImgURL = $imgURL;
next; # continue with for loop
} elsif($skippedImgFile) {
# fix for paintedover
if($imgURL =~ /paintedover/) {
$wgetExtra = qq#--referer="http://forums.somethingawful.com/" #;
} else {
$wgetExtra = '';
}
# re-get the last skipped one before continuing with the new files
print "Re-getting last existing image ($skippedImgURL)...";
if($downloadFiles) {
system(qq#wget $wgetExtra$wgetParms -nv -o wgeterr.txt -O "$skippedImgFile" "$skippedImgURL"#);
} else {
$? = 0; # fake success
}
if($? != 0) {
print "failed\n";
# Store for retrying later
$skippedImgFile =~ m#(.*)/(.*)#;
push(@failedImgs, [$1, $2, $skippedImgURL, "regetting last existing image"]);
} else {
print "ok\n";
}
$skippedImgFile = "";
}
# download it
print "Fetching image $iNum/$iCount ($imgURL) for post $post / $postCount...";
if($isWin32) {
# set title bar to indicate progress
$winConsole->Title("Post $post / $postCount : image $iNum - $gameName");
}
# paintedover demands a forums referer
if($imgURL =~ /paintedover/) {
$wgetExtra = qq#--referer="http://forums.somethingawful.com/" #;
} else {
$wgetExtra = '';
}
if($downloadFiles) {
system(qq#wget $wgetExtra$wgetParms -nv -o wgeterr.txt -O "$imgFile" "$imgURL"#);
} else {
$? = 0; # fake success
}
if($? != 0) {
print "failed\n";
$imgFile =~ m#(.*)/(.*)#;
push(@failedImgs, [$1, $2, $imgURL, "image $iNum in update $upd"]);
} else {
print "ok\n";
}
}
# and accept the URLs into the video list
if(defined(@newVids)) {
push(@videoURLs, @newVids);
# Download FLVs
# Make a directory for them (which does nothing if it already exists)
mkdir "Videos";
for($vid=$vidStart; $vid<$vidEnd; $vid++) {
$numVids++;
# Skip already-downloaded files
if(-s "Videos/video$numVids") {
print "Skipping video Videos/video$numVids ($videoURLs[$vid]), already exists\n";
$skippedVidFile = "Videos/video$numVids";
$skippedVidURL = $videoURLs[$vid];
# Update videos size
$vidSize += (-s "Videos/video$numVids");
next; # continue with for loop
} elsif($skippedVidFile) {
# re-get the last skipped one before continuing with the new files
print "Re-getting last existing video ($skippedVidURL)...\n";
# 'Remove' size first
$vidSize -= (-s "$skippedVidFile");
$success = &downloadVid($skippedVidURL, $skippedVidFile);
if(! $success) {
print "failed\n";
$errors .= "* failed to redownload pre-existing video $skippedVidFile ($skippedVidURL)\n";
} else {
print "...ok\n";
}
# Add size back
$vidSize += (-s "$skippedVidFile");
$skippedVidFile = "";
}
print "Trying to download video $numVids ($videoURLs[$vid])...\n";
$success = &downloadVid($videoURLs[$vid], "Videos/video$numVids");
if(! $success) {
print "failed\n";
$errors .= "* failed to download video $numVids for update $upd ($videoURLs[$vid])\n";
} else {
print "...ok\n";
$vidSize += (-s "Videos/video$numVids");
}
}
}
# Store per-post stats
push(@postStats, [$img, $vidEnd-$vidStart]);
}
}
# Add header text to chapter pages (next chapter, previous chapter)
sub addHdr {
if($upd > 1) {
print OUT qq#<a href="../Update%20# . (sprintf("%02d",$upd-1)) . qq#/index.html">Previous</a><br>\n#;
}
print OUT qq#<a href="../Update%20# . (sprintf("%02d",$upd+1)) . qq#/index.html">Next</a><br>\n#;
}
# Download FLV files from video sites
sub downloadVid {
($vidURL, $vidFile) = @_;
# If not fetching, fake success
if(! $downloadFiles) { return 1; }
if(! $downloadVideos) { return 1; }
# fix URL for possible youtube issue
$vidURL =~ s#youtube.com/\?#youtube.com/watch\?#;
system(qq#wget $wgetParms -q -O tmpvid.txt "$vidURL"#);
if($? != 0) {
print "couldn't download original URL...";
unlink 'tmpvid.txt';
return 0;
}
$ok = 0;
if($vidURL =~ /video.google/) { # Google Video
open(I, "<tmpvid.txt") || die $!;
while(<I>) {
next unless /<noscript>/;
($flvURL) = m# src="([^"]+)" #;
if($flvURL) {
$ok = 1;
$flvURL =~ s#^/googleplayer.swf\?&videoUrl=##;
# URL-decode URL (from 'man perlfaq9')
$flvURL =~ s/%([A-Fa-f\d]{2})/chr hex $1/eg;
last;
}
}
close(I);
} elsif($vidURL =~ /dailymotion.com/) { # Dailymotion
$var = "";
open(I, "<tmpvid.txt") || die $!;
while(<I>) {
next unless /= new SWFObject/;
($var) = /^var (.+) = new SWFObject/;
last;
}
if($var) {
while(<I>) {
next unless /$var.addVariable\("url",/;
($flvURL) = /"url", "([^"]+)"/;
last;
}
}
close(I);
if($flvURL) {
$flvURL =~ s/%([A-Fa-f\d]{2})/chr hex $1/eg;
$ok = 1;
}
} elsif($vidURL =~ /youtube/) {
$part1 = ""; $part2 = "";
open(I, "<tmpvid.txt") || die $!;
while(<I>) {
next unless /var swfArgs = /;
($part1, $part2) = /, "video_id": "([^"]+)", .+, "t": "([^"]+)",/;
last;
}
close(I);
if($part1) {
$flvURL = "http://youtube.com/get_video?video_id=$part1&t=$part2";
$ok = 1;
}
} else { # Other video site currently not handled
$ok = 0;
}
unlink 'tmpvid.txt';
if(! $ok) {
return 0;
} else {
system(qq#wget $wgetParms -O "$vidFile" "$flvURL"#);
if($? == 0) { return 1; }
else { return 0; }
}
}
# Download original thread from SA forums
sub getThread {
($threadURL) = $_[0];
print "* Fetching thread from $threadURL...\n";
if($uid) {
$cookies = qq#--header "Cookie: bbuserid=$uid; bbpassword=$pass"#;
}
open(FIRST, qq#wget $wgetParms -nv -O - $cookies "$threadURL" |#);
$pages = 1; $authorID = 0; $firstPage = "";
while(<FIRST>) {
if(/<div class="pages top"/) {
($pages) = />Pages \((\d+)\): /;
} elsif(! $authorID && $authorPosts && m#&userid=\d+">\?</a>$#) {
($authorID) = /userid=(\d+)/;
if($pages > 1) { # if there's more than one page, need to restart
while(<FIRST>) { }; # finish reading content to avoid Broken Pipe error
last;
}
}
$firstPage .= $_;
}
close(FIRST);
# If got the author ID and there's more than one page, need to reget first page to get correct number of pages
if($authorID && $pages > 1) {
print "* Fetching thread from $threadURL with author ID $authorID...\n";
$threadURL .= "&userid=$authorID";
open(FIRST, qq#wget $wgetParms -nv -O - $cookies "$threadURL" |#);
$pages = 1; $firstPage = "";
while(<FIRST>) {
if(/<div class="pages top"/) {
($pages) = />Pages \((\d+)\): /;
}
$firstPage .= $_;
}
close(FIRST);
}
open(OUT, ">autoFetchedThread.txt") || die "Couldn't write temporary thread file: $!";
print OUT $firstPage;
if($pages > 1) {
print "\n* $pages pages to fetch\n";
for($i=2; $i<=$pages; $i++) {
open(PAGE, qq#wget $wgetParms -nv -O - $cookies "${threadURL}&pagenumber=$i" |#);
while(<PAGE>) { print OUT ; }
close(PAGE);
}
}
close(OUT);
}
# Automatically detect browser cookies (Windows)
sub detectWinCookies {