This repository has been archived by the owner on Jun 5, 2018. It is now read-only.
/
goldenpod
executable file
·3568 lines (3220 loc) · 97.9 KB
/
goldenpod
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
# GoldenPod
# Copyright (C) Eskild Hustvedt 2005, 2006, 2007, 2009, 2010, 2017, 2018
#
# 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 <http://www.gnu.org/licenses/>.
# Force strict mode, and useful warnings
use strict;
use warnings;
# Require perl 5.14 to get unicode_strings, say, //, package blocks
use 5.014;
# Make perl automatically die if any of these fails
use Fatal qw/ open chdir mkdir close /;
# Used to find our directory and name
use File::Basename;
# Used to create our dirs
use File::Path qw(mkpath);
# We need realpath and getcwd
use Cwd qw(getcwd realpath);
# Parsing of commandline parameters
use Getopt::Long;
# Copying files
use File::Copy;
# Used to get OS name for user agent
use POSIX qw(uname);
# open() call to commands
use IPC::Open2;
# Used to store our downloaded state
use JSON::PP;
# Used to get backtraces when we die() of bugs
use Carp qw(confess);
# Using true/false is easier to read than 0/1
use constant { true => 1, false => 0 };
# Allow bundling of options with GeteOpt
Getopt::Long::Configure ('bundling', 'prefix_pattern=(--|-)');
# Version number
my $Version = '0.9';
# The path to our podcast list config file
my $PodcastList;
# Our verbosity
my $Verbose = 0;
# When set to any true value this disables logging. When set to 2 it
# disables logging and directs all of our output to /dev/null
my $NoLog = 0;
# When set to true, goldenpod will only download the first entry in a feed
my $FirstOnly = 0;
# When set to true, goldenpod will not download anything at all, but will
# add all entries in all feeds to its list of already downloaded files.
my $NoDownloadMode = 0;
# When set to true, goldenpod will delete files when in --copy mode
my $CopyFiles_Delete = 0;
# The path to our config dir, set by initialize()
my $UserConfigDir;
# If true, enables dry-run mode
my $DryRun_Mode = 0;
# A regex used to ignore files, either from the config or --ignore-pattern
my $IgnorePattern;
# Where to copy files to when in --copy mode
my $CopyFilesTo;
# True if we should delete old podcasts
my $RemoveOldFiles = 0;
# The number of --files to --copy or --rmold
my $FileNumber = undef;
# Internal application state. The state itself is lazy-loaded when it is needed, so
# you almost certainly want either getMetaState() or getDownloadedState()
# instead of looking at this directly.
my $state = {};
# Our config
my %Config;
# Return values that are captured by our SIGCHLD handler
my %ReturnVals;
# Our user agent string
my $UserAgent = 'GoldenPod/'.$Version.' (%OS%; podcatcher; Using %downloader%)';
my %Has = (
LWP => 0,
curl => 0,
HTMLE => undef,
);
# The global date, as used in directory names, value set in main()
my $date;
# The downloader
my $downloader = 'LWP';
# These are global state varibles for the LWP download component
my $lastP = 0;
my $prevLen = 0;
my $AudioRegex = '(ogg|oga|mp3|m4a|wave?|flac|wma|ape|tta|aac|mp2|mpa|ram?|aiff?|au|mpu)';
# This makes sure children are slayed properly and their return values
# are kept (in the %ReturnVals hash)
$SIG{CHLD} = sub
{
my $PID = wait;
$ReturnVals{$PID} = $? >> 8;
return(1);
};
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Help function declerations
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Purpose: Print formatted --help output
# Usage: PrintHelp('-shortoption', '--longoption', 'description');
# Description will be reformatted to fit within a normal terminal
sub PrintHelp
{
# The short option
my $short = shift,
# The long option
my $long = shift;
# The description
my $desc = shift;
# The generated description that will be printed in the end
my $GeneratedDesc;
# The current line of the description
my $currdesc = '';
# The maximum length any line can be
my $maxlen = 80;
# The length the options take up
my $optionlen = 20;
# Check if the short/long are LONGER than optionlen, if so, we need
# to do some additional magic to take up only $maxlen.
# The +1 here is because we always add a space between them, no matter what
if ((length($short) + length($long) + 1) > $optionlen)
{
$optionlen = length($short) + length($long) + 1;
}
# Split the description into lines
foreach my $part (split(/ /,$desc))
{
if(defined $GeneratedDesc)
{
if ((length($currdesc) + length($part) + 1 + 20) > $maxlen)
{
$GeneratedDesc .= "\n";
$currdesc = '';
}
else
{
$currdesc .= ' ';
$GeneratedDesc .= ' ';
}
}
$currdesc .= $part;
$GeneratedDesc .= $part;
}
# Something went wrong
die('Option mismatch') if not $GeneratedDesc;
# Print it all
foreach my $description (split(/\n/,$GeneratedDesc))
{
printf "%-4s %-15s %s\n", $short,$long,$description;
# Set short and long to '' to ensure we don't print the options twice
$short = '';$long = '';
}
# Succeed
return true;
}
# Purpose: Output the program --help info.
# Usage: Help();
sub Help
{
initialize('util');
my $all = shift;
Version();
printf("\nUsage: %s", basename($0));
printf("\n or : %s [OPTIONS]\n\n", basename($0));
PrintHelp('', '--version', 'Display version information and exit');
PrintHelp('-h', '--help', 'This help screen');
PrintHelp('-h', '--help-all', 'Print an extended help screen with additional options');
# Inform the user about the default based upon the value of $Config{DefaultVerbosity}
if ($Config{DefaultVerbosity})
{
PrintHelp('-v', '--verbose', 'Be verbose (default)');
PrintHelp('-s', '--silent', 'Be silent');
}
else
{
PrintHelp('-v', '--verbose', 'Be verbose');
PrintHelp('-s', '--silent', 'Be silent (default)');
}
PrintHelp('', '--list', 'Print the list of podcasts added to goldenpod');
PrintHelp('-a', '--add [URL]', 'Add the URL specified as a feed in goldenpod. You may optionally supply a second parameter, which makes the feed use the fuzzy parser with the regular expression supplied.');
PrintHelp('-r', '--remove [URL]', 'Remove the URL specified from goldenpod\'s feed list.');
PrintHelp('', '--ping URL', 'Test URL using both parsers and display which parser is recommended for it.');
PrintHelp('', '--stats', 'Print some simple statistics');
PrintHelp('-u', '--dry-run', 'Display what would be done but don\'t do it. Implies --verbose');
PrintHelp('','--mark-as-downloaded [URL]','Marks all entries in [URL] as having already been downloaded. Implies --verbose');
PrintHelp('-f', '--first-only', 'Only download the first file in any feed. Permanently ignore the others.');
PrintHelp('-c', '--copy [path]', 'Copy the last N downloaded files to path. N is either 4 or the number supplied to --files.');
PrintHelp('-n', '--files N', 'Copy N files instead of 4 (use with --copy or --rmold)');
PrintHelp('-d', '--delete', 'Delete all other files in the target --copy directory');
PrintHelp('-o', '--rmold', 'Delete N old podcasts where N is 4 or the number supplied to --files');
PrintHelp('-i', '--ignore-pattern', 'Ignore filenames matching the regexp pattern supplied when downloading, copying or deleting podcasts.');
PrintHelp('','--quick','Download the first podcast found in the feed supplied to this parameter and exit');
PrintHelp('','--clean','Clean up the podcasts directory and catalogue.');
if ($all)
{
PrintHelp('', '--debuginfo', 'Print the files goldenpod works with and some system information');
PrintHelp('-l', '--nolog', 'Don\'t create a message logfile when in silent mode.');
PrintHelp('', '--prefer-curl', 'Prefer to use curl for downloading if available, instead of LWP (curl is used by default if LWP is missing)');
PrintHelp('', '--fuzzydump URL', 'Dump the list of files found by the fuzzy parser in URL. See the manpage for more information');
PrintHelp('', '--rssdump URL', 'Dump the list of files found by the standard parser in URL. See the manpage for more information');
PrintHelp('','--file-source PATH','If the file located at PATH was downloaded by goldenpod, output which feed it came from');
}
}
# Purpose: Print version and warranty information
# Usage: Version();
sub Version
{
print "GoldenPod $Version\n";
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Download helpers
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# GPLWP is a subclass of LWP::UserAgent that overrides the progress method in
# order to output more useful progress messages from goldenpod.
package GPLWP
{
our @ISA = qw(LWP::UserAgent);
sub progress
{
shift;
no warnings 'once';
return if not $main::Verbose;
my ($status, $response) = @_;
$| = 1;
if ($status eq 'tick')
{
main::progressed();
}
elsif ($status eq 'begin')
{
main::progressed();
}
elsif ($status eq 'end')
{
return;
}
else
{
$status = int($status * 100);
main::iprint(sprintf('%-4s',$status.'%'));
}
}
}
# Purpsoe: Initialize the downloader
# Usage: initDownload();
sub initDownload
{
state $downloadInitialized = 0;
if ($downloadInitialized)
{
return;
}
detectDownloader();
my $os = [uname()]->[0];
$os = $os eq 'Linux' ? 'GNU/Linux' : $os;
$UserAgent =~ s/%OS%/$os/g;
$UserAgent =~ s/%downloader%/$downloader/g;
$downloadInitialized = 1;
}
# Purpose: Detect our downloader
# Usage: detectDownloader();
sub detectDownloader
{
if(InPath('curl'))
{
$Has{curl} = 1;
if ($downloader eq 'curl')
{
return;
}
}
if(eval('use LWP::UserAgent; 1;'))
{
$Has{LWP} = 1;
return;
}
if(not $Has{LWP} and not $Has{curl})
{
die("Both LWP and curl are missing\n");
}
elsif ($Has{curl})
{
$downloader = 'curl';
return;
}
else
{
die("No downloader found. GoldenPod needs either LWP (libwww-perl) or curl.\n");
}
}
# Purpose: Fetch a URL, either returning the data or writing a file
# Usage: fetchURL( SOME_URL, FileName?);
# Will download to FileName if present, if undef then it will return
# the content;
sub fetchURL
{
# Initialize the downloader if needed
initDownload();
my $URL = shift;
my $targetFile = shift;
if(not $URL =~ m#^\S+://#)
{
$URL = 'http://'.$URL;
}
if ($downloader eq 'LWP')
{
sayd('Going to download '.$URL.' with LWP');
# Reset our state
$lastP = 0;
$prevLen = 0;
# GPLWP is a GoldenPod wrapper around LWP
my $UA = GPLWP->new(
agent => $UserAgent.' libwwwperl',
requests_redirectable => [ 'GET', 'HEAD' ],
);
$UA->default_header('Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8');
# Honor proxy settings in env
$UA->env_proxy();
my $response;
# if we have a target file then we just use ->mirror, that downloads
# it to a file instead and handles all the nasties for us.
if ($targetFile)
{
sayd('Using ->mirror to download');
printv('Downloading '.$URL.' ... ');
$response = $UA->mirror($URL,$targetFile);
}
# If we don't, just use standard get
else
{
sayd('Using ->get to download');
printv('Fetching '.$URL.' ... ');
$response = $UA->get($URL);
}
if ($Verbose)
{
iprint('100% done');
printv ("\n");
}
if(!$response->is_success && !($targetFile && $response->code == 304))
{
if ($response->code == 304 && $targetFile)
{
return 1;
}
warn("Download of $URL failed: ".$response->status_line."\n");
return;
}
if ($targetFile)
{
return 1;
}
else
{
# Return the content
return $response->content;
}
}
elsif ($downloader eq 'curl')
{
sayd('Going to download '.$URL.' with curl');
my ($Child_IN, $Child_OUT, $Output);
# Curl options:
# -C to continue when possible
# -k for insecure (allow ssl servers with odd certificates)
# -L to follow location hints
# -A sets the user agent string
my @CurlArgs = ( qw(-C - -k -L -A),$UserAgent);
# Set verbosity
if ($Verbose)
{
push(@CurlArgs,'-#');
}
else
{
push(@CurlArgs, qw(--silent --show-error));
}
my $message = 'Fetching';
# Output to a file
if ($targetFile)
{
$message = 'Downloading';
push(@CurlArgs,'-O');
}
sayd('Calling curl with: '.join(' ',@CurlArgs));
printv($message.' '.$URL."\n");
my $PID = open2($Child_OUT, $Child_IN, 'curl',@CurlArgs,$URL) or die("Unable to open3() connection to curl: $!\n");
# Read from curl
while(<$Child_OUT>)
{
if (not $targetFile)
{
$Output .= $_;
}
}
close($Child_OUT);
close($Child_IN);
# If we don't have a return value yet, wait one second and see if we get one
if(not defined $ReturnVals{$PID})
{
sleep(1);
}
if(defined $ReturnVals{$PID} and not $ReturnVals{$PID} == 0)
{
warn("Download of $URL failed, curl exited with the return value ".$ReturnVals{$PID}."\n");
return;
}
# Return the output
return $Output;
}
else
{
die("Unknown downloader: $downloader\n");
}
}
# Purpose: Download a URL
# Usage: DownloadURL(ToDir, URL);
# Also handles creating the ToDir
sub DownloadURL
{
my ($ToDir, $URL) = @_;
my $CWD = getcwd();
if(not -d $ToDir)
{
mkdir($ToDir) or die("Unable to mkdir $ToDir: $!\n");
}
chdir($ToDir);
my @fileName = split('\?', basename($URL));
if(fetchURL($URL,$fileName[0]))
{
return (true,$fileName[0]);
}
else
{
return false;
}
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Helper functions
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Purpose: Exit the software, cleaning up if needed
# Usage: exitProgram( RETURN VALUE );
sub exitProgram
{
my $return = shift // 0;
# Ensure any dirty state gets written out
writeDirtyState();
exit $return;
}
# Purpose: Read in a file, returning its contents or erroring out
# Usage: $content = slurpFile($file);
sub slurpFile
{
my $file = shift;
open(my $in,'<',$file) || die('Failed to open '.$file.' for reading: '.$!);
local $/ = undef;
my $contents = <$in> || die('Failed to read from '.$file.': '.$!);
close($in) || warn('Warning: failed to close filehandle for '.$file.': '.$!);
return $contents;
}
# Purpose: Write out a file, DYING if it fails
# Usage: writeFile($file,$content);
sub writeFile
{
my $file = shift;
my $content = shift;
open(my $out,'>:encoding(UTF-8)',$file) || die('Failed to open '.$file.' for writing'.$!);
print {$out} $content || die('Failed to write from '.$file.': '.$!);
close($out) || warn('Warning: failed to close filehandle for '.$file.': '.$!);
return;
}
# Purpose: Check if a file has already been downloaded
sub hasAlreadyBeenDownloaded
{
my $feed = shift // '';
my $file = shift;
my $downloadedState = getDownloadedState();
if(defined $downloadedState->{$feed})
{
if(defined $downloadedState->{$feed}->{$file})
{
return 1;
}
}
# Check the __GLOBAL__ namespace as well
if ($feed ne '__GLOBAL__')
{
return hasAlreadyBeenDownloaded('__GLOBAL__',$file);
}
return;
}
# Purpose: A print that removes previous text before printing. Used for status Information messages.
# Usage: iprint(text);
sub iprint
{
local $| = false;
my $data = shift;
if ($prevLen)
{
for(my $i = 0; $i < $prevLen; $i++)
{
print "\b \b";
}
}
$prevLen = length($data);
print $data;
local $| = true;
}
# Purpose: Output pretty progression indicator
# Usage: progressed();
# - Outputs something every ten times it is called
sub progressed
{
$lastP++;
my $v;
if(not defined($lastP) or $lastP == 1 or $lastP == 5){
$v = '-';
}elsif($lastP == 2 or $lastP == 6) {
$v = '\\';
}elsif($lastP == 3 or $lastP == 7) {
$v = '|';
}elsif($lastP == 4 or $lastP == 8) {
$v = '/';
}
$lastP = $lastP == 8 ? 0 : $lastP;
iprint($v);
return true;
}
# Purpose: print() something if we're verbose
# Usage: printv(OPTS);
# OPTS are identical to print();
sub printv
{
if($Verbose)
{
print(@_);
}
}
# Purpose: say() something if debug output is enabled
# Usage: sayd(OPTS);
# OPTS are identical to say();
sub sayd
{
if ($Verbose >= 99)
{
say('Debug: ',@_);
}
}
# Purpose: Get the path to the logfile
# Usage: logfile = GetLogFile();
sub GetLogFile
{
return $Config{WorkingDir}.'/goldenpod.log';
}
# Purpose: Prepare logging (if needed)
# Usage: PrepareLogging();
sub PrepareLogging
{
if(not $NoLog)
{
my $ProgramLog = GetLogFile();
# Unless we're verbose, write stuff to $ProgramLog
open(STDOUT, '>>',$ProgramLog);
open(STDERR, '>>',$ProgramLog);
# Log the date and time we started
print 'Started at ' . localtime(time);
}
# If we're not verbose and $NoLog is 2 (-l) then write stuff to /dev/null ;)
elsif($NoLog == 2)
{
open(STDOUT, '>', '/dev/null');
open(STDERR, '>', '/dev/null');
}
}
# Purpose: Check for a file in path
# Usage: InPath(FILE)
sub InPath
{
foreach (split /:/, $ENV{PATH}) { if (-x "$_/@_" and ! -d "$_/@_" ) { return "$_/@_"; } } return false;
}
# Purpose: Check if a directory is empty
# Usage: DirIsEmpty(PATH);
# Returns 1 if it is empty, 0 if it isn't.
sub DirIsEmpty
{
my $dir = shift;
opendir(TESTDIR, $dir);
my @TestDir = readdir(TESTDIR);
closedir(TESTDIR);
if(not scalar @TestDir > 2)
{
return true;
}
return false;
}
# Purpose: Prefix a "0" to a number if it is only one digit.
# Usage: my $NewNumber = PrefixZero(NUMBER);
sub PrefixZero
{
my $number = shift;
if ($number =~ /^\d$/)
{
return("0$number");
}
return($number);
}
# Purpose: Get OS/distro version information
# Usage: print "OS: ",GetDistVer(),"\n";
sub GetDistVer
{
# Try LSB first
my %LSB;
if (-e '/etc/lsb-release')
{
LoadConfigFile('/etc/lsb-release',\%LSB);
if(defined($LSB{DISTRIB_ID}) and $LSB{DISTRIB_ID} =~ /\S/ and defined($LSB{DISTRIB_RELEASE}) and $LSB{DISTRIB_RELEASE} =~ /\S/)
{
my $ret = '/etc/lsb-release: '.$LSB{DISTRIB_ID}.' '.$LSB{DISTRIB_RELEASE};
if(defined($LSB{DISTRIB_CODENAME}))
{
$ret .= ' ('.$LSB{DISTRIB_CODENAME}.')';
}
return($ret);
}
}
# GNU/Linux and BSD
foreach(qw/arch mandriva mandrakelinux mandrake fedora redhat red-hat ubuntu debian gentoo suse distro dist slackware freebsd openbsd netbsd dragonflybsd NULL/)
{
if (-e "/etc/$_-release" or -e "/etc/$_-version" or -e "/etc/${_}_version" or $_ eq 'NULL') {
my ($DistVer, $File, $VERSION_FILE);
if(-e "/etc/$_-release") {
$File = "$_-release";
open($VERSION_FILE, '<', "/etc/$_-release");
$DistVer = <$VERSION_FILE>;
} elsif (-e "/etc/$_-version") {
$File = "$_-version";
open($VERSION_FILE, '<', "/etc/$_-release");
$DistVer = <$VERSION_FILE>;
} elsif (-e "/etc/${_}_version") {
$File = "${_}_version";
open($VERSION_FILE, '<', "/etc/${_}_version");
$DistVer = <$VERSION_FILE>;
} elsif ($_ eq 'NULL') {
last unless -e '/etc/version';
$File = 'version';
open($VERSION_FILE, '<', '/etc/version');
$DistVer = <$VERSION_FILE>;
}
close($VERSION_FILE);
$DistVer //= '';
chomp($DistVer);
return("/etc/$File: $DistVer");
}
}
# Didn't find anything yet. Get uname info
my ($sysname, $nodename, $release, $version, $machine) = POSIX::uname();
if ($sysname =~ /darwin/i) {
my $DarwinName;
my $DarwinOSVer;
# Darwin kernel, try to get OS X info.
if(InPath('sw_vers')) {
if(eval('use IPC::Open2;1')) {
if(open2(my $SW_VERS, my $NULL_IN, 'sw_vers')) {
while(<$SW_VERS>) {
chomp;
if (s/^ProductName:\s+//gi) {
$DarwinName = $_;
} elsif(s/^ProductVersion:\s+//) {
$DarwinOSVer = $_;
}
}
close($SW_VERS);
}
}
}
if(defined($DarwinOSVer) and defined($DarwinName)) {
return("$DarwinName $DarwinOSVer ($machine)");
}
}
# Detect additional release/version files
my $RelFile;
foreach(glob('/etc/*'))
{
next if not /(release|version)/i;
next if m/\/(subversion|lsb-release)$/;
if ($RelFile)
{
$RelFile .= ', '.$_;
}
else
{
$RelFile = ' ('.$_;
}
}
if ($RelFile)
{
$RelFile .= ')';
}
else
{
$RelFile = '';
}
# Some distros set a LSB DISTRIB_ID but no version, try DISTRIB_ID
# along with the kernel info.
if ($LSB{DISTRIB_ID})
{
return($LSB{DISTRIB_ID}."/Unknown$RelFile ($sysname $release $version $machine)");
}
return("Unknown$RelFile ($sysname $release $version $machine)");
}
# Purpose: Display useful information
# Usage: DumpInfo();
sub DumpInfo
{
initialize('util');
Version();
print "\n";
my $pattern = "%-28s: %s\n";
printf($pattern, 'Configuration file',$UserConfigDir.'/goldenpod.conf');
printf($pattern, 'Podcast list',$PodcastList);
if ($Verbose and not $NoLog)
{
printf($pattern, 'Logfile',GetLogFile());
}
printf($pattern, 'Target download directory',$Config{WorkingDir});
my $gpodderNetMode = 'off';
if (length($Config{gpodderNetUser}) && length($Config{gpodderNetPassword}))
{
$gpodderNetMode = 'on';
}
printf($pattern, 'gpodder.net integration',$gpodderNetMode);
printf($pattern, 'Perl version', sprintf('%vd',$^V));
# Don't output useless "used only once, possible typo" warnings
no warnings 'once';
if (eval('use LWP;use LWP::UserAgent;1;'))
{
printf($pattern,'LWP version',$LWP::VERSION);
printf($pattern,'LWP::UserAgent version',$LWP::UserAgent::VERSION);
}
else
{
printf($pattern,'LWP','missing');
}
my $HTMLEV = 'missing';
if(eval('use HTML::Entities qw(decode_entities);1'))
{
$HTMLEV = $HTML::Entities::VERSION;
}
printf($pattern,'HTML::Entities',$HTMLEV);
printf($pattern, 'OS',GetDistVer());
eval('use Digest::MD5;');
my $md5 = Digest::MD5->new();
my $self = $0;
if(not -f $self)
{
$self = InPath($self);
}
open(my $f,'<',$self);
$md5->addfile($f);
my $digest = $md5->hexdigest;
close($f);
printf($pattern,'MD5',$digest);
}
# Purpose: Output where a file came from, if possible
# Usage: ouptutSourceOfFile( FILE );
sub outputSourceOfFile
{
initialize('util');
my $file = realpath(shift);
my @components = split('/',$file);
# We're interested in the last two components of the file
my $path = join('/',$components[-2],$components[-1]);
my $metaState = getMetaState();
my $stateEntry = $metaState->{files}->{$path};
if ($stateEntry && ref($stateEntry) && $stateEntry->{from})
{
my $name = getFeedNameFromMeta( $stateEntry->{from} );
say $path.':';
say 'From the feed at '.$stateEntry->{from}.' ('.$name.')';
if ($stateEntry->{sourceURL})
{
say 'Downloaded from '.$stateEntry->{sourceURL};
}
}
else
{
say $path.': is from an unknown source (downloaded by an old version of goldenpod or not downloaded by goldenpod)';
}
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Helper routines for --copy and --rmold
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Purpose: Returns the value supplied to --files or 4
# Usage: HowManyFiles();
sub HowManyFiles
{
my $FileCount = $FileNumber ? $FileNumber : 4;
# Unless it's an integer we can't continue
if ($FileCount =~ /\D/)
{
die "Error: The option passed to --files ($FileCount) is not an integer number.\n";
}
return $FileCount;
}
# Purpose: Finds and sorts files in the current directory by time (newest first)
# and returns an array containing them.
# Usage: my @List = SortedFileList();
# NOTE: Ignores files that aren't symlinks.
sub SortedFileList
{
my $FromDir = shift;
my (@SortedFileList, %FileCopyList);
# For compatibility with older GoldenPods
my $CWD = getcwd();
chdir($FromDir);
# Create a hash of possible filenames
foreach my $FileName (glob("$FromDir/*"))
{
# Is it a link? If it isn't then we don't bother testing it
next if not -l $FileName;
# If the link points to something that doesn't exist them we omit it.
if (-e (readlink $FileName))
{
# We don't care about directories
if(not -d $FileName)
{
$FileCopyList{Cwd::realpath(readlink($FileName))} = 1;
}
}
}
# Create a sorted array of filenames
# map { [ $_, -M $_||0 ] } keys(%FileCopyList); = that means make a two dimensional array so that $_->[0]="filename.txt" and $_->[1] is the -M value
# sort { $a->[1] <=> $b->[1] } = sort the array we just thought of by the $_->[1] index, ie the -M times
# map { $_->[0] } take the sorted array and convert it back to a plain list of filenames by reading out the $_->[0] values. These are now in the right order as they are sorted
@SortedFileList = map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [ $_, -M $_ ] } keys(%FileCopyList);
chdir($CWD);
return @SortedFileList;
}
# Purpose: Clean up the catalogue.
# Usage: CleanCatalogue();
sub CleanCatalogue
{
my $CatalogueBase = shift;
die("Catalogue didn't exist. Maybe you haven't downloaded anything yet?\n") if not -e $CatalogueBase;
# For compatibility with older GoldenPods
my $CWD = getcwd();
chdir($CatalogueBase);
my $removedSomething = false;
print 'Cleaning up the catalogue...';
foreach my $CurrentDirectory (glob("$CatalogueBase/*"))
{
chdir($CurrentDirectory);
foreach my $CurrentFile (glob("$CurrentDirectory/*"))
{
next if not -l $CurrentFile;
if(not -e readlink($CurrentFile))
{
$removedSomething = true;
unlink($CurrentFile);
}
}
chdir('..');
}
chdir($CWD);
if (not $removedSomething)
{
print "nothing to clean\n";
}
else
{
print "done\n";
}
}
# Purpose: Remove empty directories in ./
# Usage: RemoveEmptyDirs();
sub RemoveEmptyDirs
{
my $FromDirectory = shift;
my $removed = 0;
foreach my $Directory (glob("$FromDirectory/*"))
{
next if not -d $Directory;
if(DirIsEmpty($Directory))
{
rmdir($Directory);
$removed++;
}
}
return $removed;
}
# Purpose: Rewrite all playlists
# Usage: RewritePlaylists(Base CatalogueDir);
# Call this before you delete directories to remove old playlists that are no
# longer used.
sub RewritePlaylists
{
my $CatalogueBase = shift;
print 'Rewriting playlists...';
my $CWD = getcwd();
foreach (glob("$CatalogueBase/*"))
{
# Only process directories and don't process 'All'
if(not -d $_ or basename($_) eq 'All')
{
next;
}
# This variable will be 1 if we wrote something to the playlist
my $WrotePlaylistContent = 0;
# The dirname, as used in the playlist filenames
my $DirName = basename($_);
if (-e $_.'/'.$DirName.'m3u')
{
unlink($_.'/'.$DirName.'.m3u');
}
# Skip directory if it's empty
if(DirIsEmpty($_))
{
next;
}
# Open our new playlist
open(my $PLAYLIST, '>', "$_/$DirName.m3u");
chdir($_);
# Create the playlist based upon the output of SortedFileList
foreach my $CurrentFile (SortedFileList($_))
{
# Skip playlists
next if $CurrentFile =~ /\.m3u$/;