a5cf023c413738e4a4394ecffb547862f34ab342
[booh] / bin / booh
1 #!/usr/bin/ruby
2 #
3 #                         *  BOOH  *
4 #
5 # A.k.a `Best web-album Of the world, Or your money back, Humerus'.
6 #
7 # The acronyn sucks, however this is a tribute to Dragon Ball by
8 # Akira Toriyama, where the last enemy beaten by heroes of Dragon
9 # Ball is named "Boo". But there was already a free software project
10 # called Boo, so this one will be it "Booh". Or whatever.
11 #
12 #
13 # Copyright (c) 2004 Guillaume Cottenceau <gc3 at bluewin.ch>
14 #
15 # This software may be freely redistributed under the terms of the GNU
16 # public license version 2.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software
20 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21
22 require 'getoptlong'
23 require 'gettext'
24 include GetText
25 require 'rexml/document'
26 include REXML
27
28 require 'booh/booh-lib'
29 require 'booh/html-merges'
30
31 #- bind text domain as soon as possible because some _() functions are called early to build data structures
32 bindtextdomain("booh")
33
34 #- options
35 $options = [
36     [ '--help',          '-h', GetoptLong::NO_ARGUMENT,       _("Get help message") ],
37
38     [ '--no-check',      '-n', GetoptLong::NO_ARGUMENT,       _("Don't check for needed external programs at startup") ],
39
40     [ '--source',        '-s', GetoptLong::REQUIRED_ARGUMENT, _("Directory which contains original images/videos as files or subdirs") ],
41     [ '--destination',   '-d', GetoptLong::REQUIRED_ARGUMENT, _("Directory which will contain the web-album") ],
42 #    [ '--clean',         '-c', GetoptLong::NO_ARGUMENT,       _("Clean destination directory") ],
43
44     [ '--theme',         '-t', GetoptLong::REQUIRED_ARGUMENT, _("Select HTML theme to use") ],
45     [ '--config',        '-C', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing images and videos within directories with captions") ],
46     [ '--config-skel',   '-k', GetoptLong::REQUIRED_ARGUMENT, _("Filename where the script will output a config skeleton") ],
47     [ '--merge-config',  '-M', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing, where to merge new images/videos from --source") ],
48
49     [ '--mproc',         '-m', GetoptLong::REQUIRED_ARGUMENT, _("Specify the number of processors for multi-processors machines") ],
50
51     [ '--verbose-level', '-v', GetoptLong::REQUIRED_ARGUMENT, _("Set max verbosity level (0: errors, 1: warnings, 2: important messages, 3: other messages)") ],
52 ]
53
54 #- default values for some globals 
55 $switches = []
56 $stdout.sync = true
57
58 def usage
59     puts _("Usage: %s [OPTION]...") % File.basename($0)
60     $options.each { |ary|
61         printf " %3s, %-15s %s\n", ary[1], ary[0], ary[3]
62     }
63 end
64
65 def handle_options
66     parser = GetoptLong.new
67     parser.set_options(*$options.collect { |ary| ary[0..2] })
68     begin
69         parser.each_option do |name, arg|
70             case name
71             when '--help'
72                 usage
73                 exit(0)
74
75             when '--no-check'
76                 $no_check = true
77
78             when '--source'
79                 $source = arg.sub(%r|/$|, '')
80                 if !File.directory?($source)
81                     die _("Argument to --source must be a directory")
82                 end
83             when '--destination'
84                 $dest = arg.sub(%r|/$|, '')
85                 if File.exists?($dest) && !File.directory?($dest)
86                     die _("If --destination exists, it must be a directory")
87                 end
88                 if $dest != make_dest_filename($dest)
89                     die _("Sorry, destination directory can't contain non simple alphanumeric characters.")
90                 end
91 #            when '--clean'
92 #                system("rm -rf #{$dest}")
93
94             when '--theme'
95                 $theme = arg
96             when '--config'
97                 if File.readable?(arg)
98                     $xmldoc = REXML::Document.new File.new(arg)
99                     $mode = 'use_config'
100                 else
101                     die _('Config file does not exist or is unreadable.')
102                 end
103             when '--config-skel'
104                 if File.exists?(arg)
105                     msg 1, _("Config skeleton file already exists, backuping to %s.backup") % arg
106                     File.rename(arg, "#{arg}.backup")
107                 end
108                 $config_writeto = arg
109                 $mode = 'gen_config'
110             when '--merge-config'
111                 if File.readable?(arg)
112                     msg 2, _("Merge config notice: backuping current config file to %s.backup") % arg
113                     $xmldoc = REXML::Document.new File.new(arg)
114                     File.rename(arg, "#{arg}.backup")
115                     $config_writeto = arg
116                     $mode = 'merge_config'
117                 else
118                     die _('Config file does not exist or is unreadable.')
119                 end
120
121             when '--mproc'
122                 $mproc = arg.to_i
123                 $pids = []
124
125             when '--verbose-level'
126                 $verbose_level = arg.to_i
127
128             end
129         end
130     rescue
131         puts $!
132         usage
133         exit(1)
134     end
135
136     if !$source && $xmldoc
137         $source = $xmldoc.root.attributes['source']
138         $dest = $xmldoc.root.attributes['destination']
139         $theme = $xmldoc.root.attributes['theme']
140     end
141
142     if !$source
143         die _("Missing --source or --config parameter.")
144     end
145     if !$dest
146         die _("Missing --destination parameter.")
147     end
148     if !$theme
149         $theme = 'simple'
150     end
151     select_theme($theme)
152
153     if !$xmldoc
154         $xmldoc = Document.new "<booh version='#{$VERSION}' source='#{utf8($source)}' destination='#{utf8($dest)}' theme='#{$theme}'/>"
155         $xmldoc << XMLDecl.new( XMLDecl::DEFAULT_VERSION, $CURRENT_CHARSET )
156         $mode = 'gen_config'
157     end
158
159 end
160
161 def check_installation
162     if $no_check
163         return
164     end
165     if missing = %w(convert identify exif transcode mencoder).delete_if { |prg| system("which #{prg} >/dev/null 2>/dev/null") }
166         die _("The following programs are typically needed: `%s'. Re-run with --no-check if you're sure you're fine without them.") % missing.join(', ')
167     end
168 end
169
170 def replace_line(surround, keyword, line)
171     begin
172         contents = eval "$#{keyword}"
173         line.sub!(/#{surround}#{keyword}#{surround}/, contents)
174     rescue NameError
175         die _("No `%s' found for substitution") % keyword
176     end
177 end
178
179 def build_html_skeletons
180     $html_images     = File.open("#{$FPATH}/themes/#{$theme}/skeleton_image.html").readlines
181     $html_thumbnails = File.open("#{$FPATH}/themes/#{$theme}/skeleton_thumbnails.html").readlines
182     $html_index      = File.open("#{$FPATH}/themes/#{$theme}/skeleton_index.html").readlines
183     for line in $html_images + $html_thumbnails + $html_index
184         while line =~ /~~~(\w+)~~~/
185             replace_line('~~~', $1, line)
186         end
187     end
188 end
189
190 def find_caption_value(xmldir, filename)
191     xmldir.elements["[@filename='#{utf8(filename)}']"].attributes['caption']
192 end
193
194 def find_captions(xmldir, images)
195     return images.collect { |img| find_caption_value(xmldir, img) }
196 end
197
198 #- stolen from CVSspam
199 def urlencode(text)
200   text.sub(/[^a-zA-Z0-9\-,.*_\/]/) do
201     "%#{sprintf('%2X', $&[0])}"
202   end
203 end
204
205 def html_refresh(target)
206     return "<html><head><META http-equiv='refresh' content='0;URL=#{target}'></head><body></body><html>"
207 end
208
209 def discover_iterations(iterations, line)
210     if line =~ /~~iterate(\d)_open(_max(\d+))?~~/
211         for iter in iterations.values
212             if iter['open']
213                 iter['open'] = false
214                 iter['close_wait'] = $1.to_i
215             end
216         end
217         iterations[$1.to_i] = { 'open' => true, 'max' => $3, 'opening' => '', 'closing' => '' }
218         if $1.to_i == 1
219             line.sub!(/.*/, '~~thumbnails~~')
220         else
221             line.sub!(/.*/, '')
222         end
223     elsif line =~ /~~iterate(\d)_close~~/
224         iterations[$1.to_i]['open']  = false;
225         iterations[$1.to_i]['close'] = true;
226         line.sub!(/.*/, '')
227     else
228         for iter in iterations.values
229             if iter['open']
230                 iter['opening'] += line
231                 line.sub!(/.*/, '')
232             end
233             if !iter['close'] && iter['close_wait'] && iterations[iter['close_wait']]['close']
234                 iter['closing'] += line
235                 line.sub!(/.*/, '')
236             end
237         end
238     end
239 end
240
241 def reset_iterations(iterations)
242     for iter in iterations.values
243         iter['value'] = 1
244     end
245 end
246
247 def run_iterations(iterations)
248     html = ''
249     for level in iterations.keys.sort
250         if iterations[level]['value'] == 1 || level == iterations.keys.max
251             html += iterations[level]['opening']
252         end
253         iterations[level]['value'] += 1
254         if iterations[level]['max'] && iterations[level]['value'] > iterations[level]['max'].to_i
255             iterations[level]['value'] = 1
256             iterations[level-1]['value'] = 1
257             html += iterations[level-1]['closing']
258         end
259     end
260     return html
261 end
262
263 def close_iterations(iterations)
264     html = ''
265     for level in iterations.keys.sort.reverse
266         html += iterations[level]['closing']
267     end
268     return html
269 end
270
271 def img_element(fullpath)
272     sizespec = `identify '#{fullpath}'` =~ / JPEG (\d+)x(\d+) / ? 'width="' + $1 + '" height="' + $2 + '"' : ''
273     return '<img src="' + File.basename(fullpath) + '" ' + sizespec + ' border="0"/>'
274 end
275
276 def walk_source_dir
277
278     `find #{$source} -type d`.sort.each { |dir|
279         dir.chomp!
280         if dir =~ /'/
281             die _("Source directory or sub-directories can't contain a single-quote character, sorry.")
282         end
283
284         #- place xml document on proper node if exists, else create
285         xmldir = $xmldoc.elements["//dir[@path='#{utf8(dir)}']"]
286         if $mode == 'use_config'
287             if !xmldir
288                 next
289             end
290         else
291             if $mode == 'gen_config' || ($mode == 'merge_config' && !xmldir)
292                 #- add the <dir..> element if necessary
293                 parent = File.dirname(dir)
294                 xmldir = $xmldoc.elements["//dir[@path='#{utf8(parent)}']"]
295                 if !xmldir
296                     xmldir = $xmldoc.root
297                 end
298                 xmldir = xmldir.add_element 'dir', { 'path' => utf8(dir), 'new' => 1 }
299             end
300         end
301
302         #- read images/videos entries from config or from directories depending on mode
303         entries = []
304         if $mode == 'use_config'
305             msg 2, _("Handling %s from config list...") % dir
306             xmldir.elements.each { |element|
307                 if %w(image video).include?(element.name)
308                     entries << from_utf8(element.attributes['filename'])
309                 end
310             }
311         else
312             msg 2, _("Examining %s...") % dir
313             entries = Dir.entries(dir).sort
314             #- populate config in case of gen_config, add new files in case of merge_config
315             for file in entries
316                 type = entry2type(file)
317                 if type && !xmldir.elements["#{type}[@filename='#{utf8(file)}']"]
318                     xmldir.add_element type, { "filename" => utf8(file), "caption" => utf8(file.sub(/\.[^\.]+$/, '')[0..17]) }
319                 end
320             end
321             if $mode == 'merge_config'
322                 #- cleanup removed files from config and reread entries from config to get proper ordering
323                 entries = []
324                 xmldir.elements.each { |element|
325                     fullpath = "#{dir}/#{from_utf8(element.attributes['filename'])}"
326                     if %w(image video).include?(element.name)
327                         if !File.readable?(fullpath)
328                             msg 1, _("Config merge: removing %s from config; use the backup file to retrieve caption info if this was a mistake") % fullpath
329                             xmldir.delete(element)
330                         else
331                             entries << from_utf8(element.attributes['filename'])
332                         end
333                     end
334                 }
335             end
336         end
337         images = entries.find_all { |e| entry2type(e) == 'image' }
338         msg 3, _("\t%s images") % images.length
339         videos = entries.find_all { |e| entry2type(e) == 'video' }
340         msg 3, _("\t%s videos") % videos.length
341
342         dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
343         system("mkdir -p '#{dest_dir}'")
344
345         #- copy any resource file that goes with the theme (css, images..)
346         for entry in Dir.entries("#{$FPATH}/themes/#{$theme}")
347             if !%w(. .. skeleton_image.html skeleton_thumbnails.html skeleton_index.html parameters.rb CVS).include?(entry)
348                 if !File.exists?("#{dest_dir}/#{entry}")
349                     psys("cp '#{$FPATH}/themes/#{$theme}/#{entry}' '#{dest_dir}'")
350                 end
351             end
352         end
353
354         #- pass through if there are no images and videos
355         if images.size == 0 && videos.size == 0
356             next
357         end
358
359         msg 2, _("Outputting in %s...") % dest_dir
360
361         #- populate data structure with sizes from theme
362         for sizeobj in $images_size
363             fullscreen_images ||= {}
364             fullscreen_images[sizeobj['name']] = []
365             thumbnail_images ||= {}
366             thumbnail_images[sizeobj['name']] = []
367             thumbnail_videos ||= {}
368             thumbnail_videos[sizeobj['name']] = []
369         end
370
371         images.size >= 1 and msg 3, _("\tcreating images thumbnails...")
372
373         #- create thumbnails for images
374         images.each { |img|
375             base_dest_img = dest_dir + '/' + make_dest_filename(img.sub(/\.[^\.]+$/, ''))
376             for sizeobj in $images_size
377                 size_fullscreen = sizeobj['fullscreen']
378                 size_thumbnails = sizeobj['thumbnails']
379                 fullscreen_dest_img = base_dest_img + "-#{size_fullscreen}.jpg"
380                 thumbnail_dest_img  = base_dest_img + "-#{size_thumbnails}.jpg"
381                 fullscreen_images[sizeobj['name']] << File.basename(fullscreen_dest_img)
382                 thumbnail_images[sizeobj['name']]  << File.basename(thumbnail_dest_img)
383                 gen_thumbnails("#{dir}/#{img}", xmldir, [ { 'filename' => fullscreen_dest_img, 'size' => size_fullscreen },
384                                                           { 'filename' => thumbnail_dest_img, 'size' => size_thumbnails } ])
385             end
386         }
387
388         videos.size >= 1 and msg 3, _("\tcreating videos thumbnails...")
389
390         #- create thumbnails for videos
391         videos.each { |video|
392             thumbnail_ok = true
393             for sizeobj in $images_size
394                 size_thumbnails = sizeobj['thumbnails']
395                 thumbnail_dest_img = dest_dir + '/' + make_dest_filename(video.sub(/\.[^\.]+$/, '')) + "-#{size_thumbnails}.jpg"
396                 thumbnail_videos[sizeobj['name']] << File.basename(thumbnail_dest_img)
397                 thumbnail_ok &&= gen_thumbnails("#{dir}/#{video}", xmldir, [ { 'filename' => thumbnail_dest_img, 'size' => size_thumbnails } ])
398             end
399             destvideo = "#{dest_dir}/#{video}"
400             if !File.exists?(destvideo)
401                 psys("cp '#{dir}/#{video}' '#{destvideo}'")
402             end
403             #- cleanup temp
404             system("rm -f #{dest_dir}/screenshot.jpg00000*")
405         }
406
407         #- fake for gettext to find these; if themes need more sizes, english name for them should be added here
408         sizenames = { 'small' => utf8(_("small")), 'medium' => utf8(_("medium")), 'large' => utf8(_("large")) }
409
410         msg 3, _("\tgenerating HTML pages...")
411         
412         #- generate thumbnails.html (page with thumbnails)
413         for sizeobj in $images_size
414             html = $html_thumbnails.collect { |l| l.clone }
415             iterations = {}
416             for i in html
417                 i.sub!(/~~run_slideshow~~/, images.size <= 1 ? '' : '<a href="image-' + sizeobj['name'] + '.html?run_slideshow">' + utf8(_('Run slideshow!')) + '</a>')
418                 i.sub!(/~~title~~/, xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir)))
419                 for sizeobj2 in $images_size
420                     if sizeobj != sizeobj2
421                         i.sub!(/~~size_#{sizeobj2['name']}~~/, '<a href="thumbnails-' + sizeobj2['name'] + '.html">' + sizenames[sizeobj2['name']] + '</a>')
422                     else
423                         i.sub!(/~~size_#{sizeobj2['name']}~~/, sizenames[sizeobj2['name']])
424                     end
425                 end
426                 discover_iterations(iterations, i)
427             end
428             html_thumbnails = ''
429             reset_iterations(iterations)
430             for file in entries
431                 type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
432                 if type
433                     html_thumbnails += run_iterations(iterations)
434                     if type == 'image'
435                         index = images.index(file)
436                         html_thumbnails.gsub!(/~~image_iteration~~/,
437                                               '<a href="image-' + sizeobj['name'] + '.html?current=' + fullscreen_images[sizeobj['name']][index] + '">' +
438                                                   img_element("#{dest_dir}/#{thumbnail_images[sizeobj['name']][index]}") + '</a>')
439                         html_thumbnails.gsub!(/~~caption_iteration~~/,
440                                               find_caption_value(xmldir, images[index]) || utf8(images[index]))
441                         html_thumbnails.gsub!(/~~ifimage\?~~(.+?)~~fi~~/) { $1 }
442                         html_thumbnails.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/, '')
443                     elsif type == 'video'
444                         index = videos.index(file)
445                         if File.exists?("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}")
446                             html_thumbnails.gsub!(/~~image_iteration~~/,
447                                                   '<a href="' + videos[index] + '">' + img_element("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}") + '</a>')
448                         else
449                             html_thumbnails.gsub!(/~~image_iteration~~/,
450                                                   '<a href="' + videos[index] + '">' + utf8(_("(no preview)")) + '</a>')
451                         end
452                         html_thumbnails.gsub!(/~~caption_iteration~~/,
453                                               find_caption_value(xmldir, videos[index]) || utf8(videos[index]))
454                         html_thumbnails.gsub!(/~~ifimage\?~~(.+?)~~fi~~/, '')
455                         html_thumbnails.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/) { $1 }
456                     end
457                 end
458             end
459             html_thumbnails += close_iterations(iterations)
460             for i in html
461                 i.sub!(/~~thumbnails~~/, html_thumbnails)
462             end
463             ios = File.open("#{dest_dir}/thumbnails-#{sizeobj['name']}.html", "w")
464             ios.write(html)
465             ios.close
466         end
467
468         #- generate image.html (page with fullscreen images)
469         if images.size > 0
470             #- don't ask me why I need so many backslashes... the aim is to print \\\" for each " in the javascript source
471             captions4js = find_captions(xmldir, images).collect { |e| e ? '"' + e.gsub('"', '\\\\\\\\\\\\\\\\\"' ) + '"' : '""' }.join(', ')
472             for sizeobj in $images_size
473                 html = $html_images.collect { |l| l.clone }
474                 images4js = fullscreen_images[sizeobj['name']].collect { |e| "\"#{e}\"" }.join(', ')
475                 otherimages4js = ''
476                 othersizes = []
477                 for sizeobj2 in $images_size
478                     if sizeobj != sizeobj2
479                         otherimages4js += "var images_#{sizeobj2['name']} = new Array(" + fullscreen_images[sizeobj2['name']].collect { |e| "\"#{e}\"" }.join(', ') + ")\n"
480                         othersizes << "\"#{sizeobj2['name']}\""
481                     end
482                 end
483                 for i in html
484                     i.sub!(/~~images~~/, images4js)
485                     i.sub!(/~~other_images~~/, otherimages4js)
486                     i.sub!(/~~other_sizes~~/, othersizes.join(', '))
487                     i.sub!(/~~captions~~/, captions4js)
488                     i.sub!(/~~title~~/, xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir)))
489                     i.sub!(/~~thumbnails~~/, '<a href="thumbnails-' + sizeobj['name'] + '.html">' + utf8(_('Return to thumbnails')) + '</a>')
490                     for sizeobj2 in $images_size
491                         if sizeobj != sizeobj2
492                             i.sub!(/~~size_#{sizeobj2['name']}~~/,
493                                    '<a href="image-' + sizeobj2['name'] + '.html" id="link' + sizeobj2['name'] + '">' + sizenames[sizeobj2['name']] + '</a>')
494                         else
495                             i.sub!(/~~size_#{sizeobj2['name']}~~/,
496                                    sizenames[sizeobj2['name']])
497                         end
498                     end
499                 end
500                 ios = File.open("#{dest_dir}/image-#{sizeobj['name']}.html", "w")
501                 ios.write(html)
502                 ios.close
503             end
504         end
505     }
506
507     msg 3, ''
508
509     #- add attributes to <dir..> elements needing so
510     if $mode != 'use_config'
511         msg 3, _("\tfixating configuration file...")
512         $xmldoc.elements.each('//dir[@new]') { |element|
513             path = captionpath = element.attributes['path']
514             child = element
515             captionfile = nil
516             while true
517                 child = child.elements[1]
518                 if !child
519                     element.remove  #- means we have a directory with nothing interesting in it
520                     break
521                 elsif child.name == 'dir'
522                     captionpath = child.attributes['path']
523                 else
524                     captionfile = "#{captionpath}/#{child.attributes['filename']}"
525                     break
526                 end
527             end
528             basename = File.basename(path)
529             if element.elements['dir']
530                 element.add_attribute('subdirs-caption', basename)
531                 element.add_attribute('subdirs-captionfile', captionfile)
532             end
533             if element.elements['image'] || element.elements['video']
534                 element.add_attribute('thumbnails-caption', basename)
535                 element.add_attribute('thumbnails-captionfile', captionfile)
536             end
537             element.delete_attribute('new')
538         }
539     end
540
541     #- write down to disk config if necessary
542     if $config_writeto
543         ios = File.open($config_writeto, "w")
544         $xmldoc.write(ios, 0)
545         ios.close
546     end
547
548     #- second pass to create index.html files
549     default_thumbnails = $images_size.detect { |sizeobj| sizeobj['default'] }
550     if !default_thumbnails
551         die _("Theme `%s' has no default size.") % $theme
552     else
553         default_thumbnails = default_thumbnails['name']
554     end
555
556     msg 3, _("\trescanning directories to generate all `index.html' files...")
557
558     `find #{$source} -type d`.each { |dir|
559         dir.chomp!
560         xmldir = $xmldoc.elements["//dir[@path='#{utf8(dir)}']"]
561         if !xmldir
562             next
563         end
564         dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
565
566         html = $html_index.collect { |l| l.clone }
567         iterations = {}
568         for i in html
569             caption = xmldir.attributes['subdirs-caption'] || xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir))
570             i.gsub!(/~~title~~/, caption)
571             if xmldir.parent.name == 'dir'
572                 nav = ''
573                 path = '..'
574                 parent = xmldir.parent
575                 while parent.name == 'dir'
576                     parentcaption = parent.attributes['subdirs-caption'] || parent.attributes['thumbnails-caption'] || File.basename(parent.attributes['path'])
577                     nav = "<a href='#{path}/index.html'>#{parentcaption}</a> #{utf8(_(" > "))} #{nav}"
578                     path += '/..'
579                     parent = parent.parent
580                 end
581                 i.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/) { $1 }
582                 i.gsub!(/~~navigation~~/, nav + caption)
583             else
584                 i.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/, '')
585             end
586             discover_iterations(iterations, i)
587         end
588
589         html_index = ''
590         reset_iterations(iterations)
591
592         if xmldir.elements['dir']
593             #- deal with "current" album (directs to "thumbnails" page)
594             if xmldir.attributes['thumbnails-caption']
595                 thumbnail = "#{dest_dir}/thumbnails-thumbnail.jpg"
596                 gen_thumbnails(from_utf8(xmldir.attributes['thumbnails-captionfile']), xmldir, [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ])
597                 html_index += run_iterations(iterations)
598                 html_index.gsub!(/~~image_iteration~~/, "<a href='thumbnails-#{default_thumbnails}.html'>" + img_element(thumbnail) + '</a>')
599                 html_index.gsub!(/~~caption_iteration~~/, xmldir.attributes['thumbnails-caption'])
600             end
601             #- cleanup temp for videos
602             system("rm -f #{dest_dir}/screenshot.jpg00000*")
603
604             #- deal with sub-albums (direct to subdirs/index.html pages)
605             xmldir.elements.each('dir') { |child|
606                 subdir = make_dest_filename(from_utf8(File.basename(child.attributes['path'])))
607                 thumbnail = "#{dest_dir}/thumbnails-#{subdir}.jpg"
608                 html_index += run_iterations(iterations)
609                 #- first look for subdirs info; if not, means there is no subdir
610                 caption = child.attributes['subdirs-caption']
611                 if caption
612                     gen_thumbnails(from_utf8(child.attributes['subdirs-captionfile']), child, [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ])
613                     html_index.gsub!(/~~caption_iteration~~/, caption)
614                 else
615                     gen_thumbnails(from_utf8(child.attributes['thumbnails-captionfile']), child, [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ])
616                     html_index.gsub!(/~~caption_iteration~~/, child.attributes['thumbnails-caption'])
617                 end
618                 html_index.gsub!(/~~image_iteration~~/, "<a href='#{make_dest_filename(subdir)}/index.html'>" + img_element(thumbnail) + '</a>')
619                 #- cleanup temp for videos
620                 system("rm -f #{dest_dir}/screenshot.jpg00000*")
621             }
622
623         else
624             html = html_refresh("thumbnails-#{default_thumbnails}.html")
625         end
626
627         html_index += close_iterations(iterations)
628         for i in html
629             i.gsub!(/~~thumbnails~~/, html_index)
630         end
631
632         ios = File.open("#{dest_dir}/index.html", "w")
633         ios.write(html)
634         ios.close
635
636         #- substitute "return to albums" correctly
637         `find '#{dest_dir}' -maxdepth 1 -name "thumbnails*.html"`.each { |thumbnails|
638             thumbnails.chomp!
639             contents = File.open(thumbnails.chomp).readlines
640             for i in contents
641                 if xmldir.elements['dir']
642                     i.sub!(/~~return_to_albums~~/, '<a href="index.html">' + utf8(_('Return to albums')) + '</a>')
643                 else
644                     if xmldir.parent.name == 'dir'
645                         i.sub!(/~~return_to_albums~~/, '<a href="../index.html">' + utf8(_('Return to albums')) + '</a>')
646                     else
647                         i.sub!(/~~return_to_albums~~/, '')
648                     end
649                 end
650             end
651             ios = File.open(thumbnails, "w")
652             ios.write(contents)
653             ios.close
654         }
655     }
656
657     msg 3, _(" all done.")
658 end
659
660 handle_options
661 check_installation
662
663 build_html_skeletons
664
665 walk_source_dir