Major overhaul of destination video merging.
[videoscripts/.git] / organize_videos
1 #!/usr/bin/perl
2 # Author: Alan J. Pippin
3 # Description: Find videos from a temporary dropbox location and merge and move them into their final destination.
4
5 use File::Copy;
6 use File::Basename;
7 use Getopt::Std;
8 use File::stat;
9 use Time::localtime;
10 use File::Pid;
11
12 ####################################################################################################
13 # Configuration parameters - CHANGE THESE TO SUITE YOUR NEEDS
14 my $srcpathname = "/naspool/pictures/New Photos"; # Path to look for videos to move from
15 my $dstpathname = "/naspool/videos/HomeVideos"; # Path to move the videos to
16 my $merge_videos_by_day = "/naspool/videos/bin/merge_videos_by_day";
17 my $minage = "+10"; # File creation dates must be older than X minutes to move
18 my $owner = "ajp"; # The owner of the files after they are moved
19 my $group = "pip"; # The group of the files after they are moved
20 my $mode = "664"; # The mode to set on each file after they are moved
21 my $playlist_extension = "pls"; # The extension to use when creating playlist files
22 my $video_suffix = "000"; # What number to start with when adding an incrementing suffix to the end of the final video clip to avoid name collisions
23 my $find_cmd = "find \"$srcpathname/\" -cmin $minage -a \\( -iregex \".*\.mov\" -o -iregex \".*\.3gp\" -o -iregex \".*\.mp4\" -o -iregex \".*\.mts\" -o -iregex \".*\.mkv\" \\)";
24 ####################################################################################################
25
26 # Sanity check
27 if(! -d $srcpathname) { print "-E- Can't find srcpath: $srcpathname\n"; exit 1; }
28 if(! -d $dstpathname) { print "-E- Can't find dstpath: $dstpathname\n"; exit 1; }
29 if(! -x $merge_videos_by_day) { print "-E- Can't find required script: $merge_videos_by_day\n"; exit 1; }
30
31 my %monthname2month = (
32                        "Jan" => "01",
33                        "Feb" => "02",
34                        "Mar" => "03",
35                        "Apr" => "04",
36                        "May" => "05",
37                        "Jun" => "06",
38                        "Jul" => "07",
39                        "Aug" => "08",
40                        "Sep" => "09",
41                        "Oct" => "10",
42                        "Nov" => "11",
43                        "Dec" => "12"
44                        );
45
46 my %month2monthname = (
47                        "01" => "Jan",
48                        "02" => "Feb",
49                        "03" => "Mar",
50                        "04" => "Apr",
51                        "05" => "May",
52                        "06" => "Jun",
53                        "07" => "Jul",
54                        "08" => "Aug",
55                        "09" => "Sep",
56                        "10" => "Oct",
57                        "11" => "Nov",
58                        "12" => "Dec"
59                        );
60
61 getopts("htvrpd:");
62
63 sub usage {
64     print "usage: $0 [-v] [-t] [-r] [-p] [-d <dir>]\n";
65     print "   -v = verbose; print file being moved (to).\n";
66     print "   -t = test; print what will happen, but don't do anything\n";
67     print "   -r = remove merged video clips; after a merge, remove the individual video files that were merged\n";
68     print "   -p = Only recreate video playlists. Do this for each year & month of video clips in the directory specified by -d <dir>.\n";
69     print "   -d <dir> = Directory to recreate the playlists in. Only needed if -p option is given\n";
70     return 1;
71 }
72
73 sub is_folder_empty {
74     my $dirname = shift;
75     opendir(my $dh, $dirname) or die "Not a directory";
76     return scalar(grep { $_ ne "." && $_ ne ".." } readdir($dh)) == 0;
77 }
78
79 sub create_playlists {
80     my ($dstdirs) = @_;
81     
82     foreach $dstdir (@{$dstdirs}) {
83         print "-> Recreating playlists in: $dstdir\n";
84         print "-> Creating playlists for each month & year of clips from this directory: $video_directory\n";
85         opendir(VIDEODIR, "$dstdir") or die "-E- could not open: $dstdir\n";
86         chdir "$dstdir" || die "-E- Unable to change directory to the dstdir: $dstdir\n";
87         
88         my @all_files = readdir VIDEODIR;
89         closedir(VIDEODIR);
90         @all_files = sort @all_files;
91
92         print "   Removing all existing playlists from the directory\n";
93         if(! defined $opt_t) { system("rm *.$playlist_extension > /dev/null 2>&1"); }
94     
95         foreach $file (@all_files) {
96             next if -d $file;
97             next if ($file !~ /\.avi$/i && $file !~ /\.mpg$/i && $file !~ /\.mkv$/i && $file !~ /\.3gp$/i && $file !~ /\.mov$/i && $file !~ /\.mts$/i);
98             if($file =~ /(\d\d\d\d)-(\d\d)-(\d\d)/) {
99                 $year = $1; $month = $2;
100                 print "   Adding $file to $year.$playlist_extension & $year-$month.$playlist_extension\n";
101                 if(! defined $opt_t) { system("echo \"$file\" >> $year.$playlist_extension"); }
102                 if(! defined $opt_t) { system("echo \"$file\" >> $year-$month.$playlist_extension"); }
103             } else {
104                 print "   Skipping $file since we can't extract the year and month from it\n"; 
105             }
106         }
107     }
108 }
109
110 # Sanity checks / Option processing
111 if(defined $opt_h) { usage(); exit 1; }
112 if(defined $opt_p) {
113     if(defined $opt_d) {
114         my @dstdirs = ("$opt_d"); 
115         create_playlists(\@dstdirs);
116     } else {
117         die "-E- You must specify the -d <dir> option when using the -p option\n"; 
118     }
119     exit 0;
120 }
121
122 # Only proceed if there are video files to organize
123 $video_files_found=`$find_cmd`;
124 if(!$video_files_found) { exit 0; }
125
126 # Only one instance of this script running at a time
127 my $pidfile = File::Pid->new({file => "/tmp/organize_videos.pid"});
128 exit if $pidfile->running();
129 $pidfile->write();
130
131 # Print the date
132 system("date");
133
134 # Merge videos prior to copying them over to the destination path
135 my $errno = 0;
136 my $merge_opts = "";
137 if(defined $opt_t) { $merge_opts .= "-t "; }
138 if(defined $opt_r) { $merge_opts .= "-r "; }
139 $errno=system("$merge_videos_by_day -s \"$srcpathname\" $merge_opts");
140 $errno = $errno >> 8;
141 if($errno) { die "-E- $merge_videos_by_day encountered some errors with exit code $errno\n"; }
142
143 # Copy the videos over to the destination path
144 my @dstdirs;
145 chdir "$srcpathname";
146 print "$find_cmd\n" if($opt_v);
147 foreach $file (`$find_cmd`) {
148
149     chomp($file);
150     $srcdir = dirname($file);
151     $file = basename($file);
152     $srcfile = $file;
153     $ext = $file; $ext =~ s/.*\.(\S+)$/$1/; $ext = lc($ext);
154     
155     print "Found movie: srcdir: $srcdir srcfile: $srcfile ext: $ext\n" if($opt_v);
156
157     # Throw out files not in the current srcpath
158     if((! -f "$srcfile") && (! -f "$srcdir/$srcfile")) { next; }
159         
160     # Make a note of the month, year, and day this video was taken (from the modification time of the file)
161     $date_taken = ctime(stat("$srcdir/$srcfile")->mtime);
162
163     # Get the date taken from the filename
164     if($srcfile =~ /^(\d+)-(\d+)-(\d+)/) {
165         $year = $1;
166         $month = $2;
167         $day = sprintf("%02d",$3);
168         $monthnum = $month;
169         $monthname = lc($month2monthname{$month});
170     }
171     # Get the date taken from the modification time
172     elsif($date_taken =~ /\S+\s+(\S+)\s+(\d+)\s+\S+\s+(\d+)/) {
173         $year = $3;
174         $month = $1;
175         $day = sprintf("%02d",$2);
176         $monthnum = $monthname2month{$month};
177         $monthname = lc($month2monthname{$month});
178     } else {
179         print "-E- Unable to parse year and month from this file: $srcdir/$srcfile\n";
180         next;
181     }
182
183     # We are ready to pick a destination folder to put the picture in
184     $dstdir = $dstpathname . "/" . $year;
185     push(@dstdirs,$dstdir);
186     $dstfile = $dstdir . "/" . $year . "-" . $monthnum . "-" . $day;
187
188     # Check for duplicate filenames at the destination
189     $newfile = $dstfile . "." . $video_suffix;
190     if(-e "$newfile.$ext") {
191         foreach $i ($video_suffix+1 .. '999') {
192             $newfile = $dstfile . "." . sprintf("%03d",$i);;
193             if(! -e "$newfile.$ext") { last; }
194         }
195         $dstfile = $newfile;
196     }
197     $dstfile = "$newfile.$ext";
198
199     if(defined $opt_t) {
200         print "-> Moving \"$srcdir/$srcfile\" to \"$dstfile\"\n";
201     } else {
202         # Make sure the destination directories exist
203         $errno=system("mkdir -p \"$dstdir\"");
204         if($errno) { print "-E- Error creating dstdir: $dstdir\n"; next; }
205         # Perform the move operation from $srcdir/$srcfile -> $dstfile
206         print "-> Moving \"$srcdir/$srcfile\" to \"$dstfile\"\n";
207         # Make sure the dstfile doesn't exist, if it does, don't do the move
208         if(! -f "$dstfile") {
209             $errno=system("mv \"$srcdir/$srcfile\" \"$dstfile\" 2>/dev/null");
210             if($errno) { print "-E- Error moving srcfile to dstfile: $srcdir/$srcfile -> $dstfile\n"; next; }
211         } else {
212             print "-> Skipping \"$srcdir/$srcfile\". Destfile \"$dstfile\" already exists.\n";
213         }
214         # Fix the permissions
215         system("chown $owner \"$dstfile\"");
216         system("chgrp $group \"$dstfile\"");
217         system("chmod $mode \"$dstfile\"");
218     }
219
220     # Check to see if there is an empty sub directory to remove
221     if(($srcdir ne $srcpathname) && ($srcpathname ne ".")) { 
222       if(is_folder_empty($srcdir)) { 
223           print "-> Subdir detected for videos ($srcdir != $srcpathname)\n" if($opt_v);
224           if(! defined $opt_t) { 
225               $tmpdir=`tempfile`;
226               system("rm $tmpdir");
227               system("mv \"$srcdir\" $tmpdir > /dev/null 2>/dev/null");
228               print "-> Moved empty subdir $srcdir to $tmpdir\n" if($opt_v);
229           }
230       }
231     }
232 }
233
234 # For each destination dir we copied new content into, recreate the playlists
235 create_playlists(\@dstdirs);
236
237 $pidfile->remove();
238
239 print "\n\n";