5 # A.k.a `Best web-album Of the world, Or your money back, Humerus'.
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.
13 # Copyright (c) 2004 Guillaume Cottenceau <gc3 at bluewin.ch>
15 # This software may be freely redistributed under the terms of the GNU
16 # public license version 2.
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.
25 require 'rexml/document'
28 require 'booh/booh-lib'
29 require 'booh/html-merges'
31 #- bind text domain as soon as possible because some _() functions are called early to build data structures
32 bindtextdomain("booh")
36 [ '--help', '-h', GetoptLong::NO_ARGUMENT, _("Get help message") ],
38 [ '--no-check', '-n', GetoptLong::NO_ARGUMENT, _("Don't check for needed external programs at startup") ],
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") ],
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") ],
49 [ '--sizes', '-S', GetoptLong::REQUIRED_ARGUMENT, _("Specify the list of images sizes to use instead of all specified in the theme (this is a comma-separated list)") ],
51 [ '--mproc', '-m', GetoptLong::REQUIRED_ARGUMENT, _("Specify the number of processors for multi-processors machines") ],
53 [ '--for-gui', '-g', GetoptLong::NO_ARGUMENT, _("Do the minimum work to be able to see the album under the GUI (don't generate all thumbnails)") ],
55 [ '--verbose-level', '-v', GetoptLong::REQUIRED_ARGUMENT, _("Set max verbosity level (0: errors, 1: warnings, 2: important messages, 3: other messages)") ],
58 #- default values for some globals
63 puts _("Usage: %s [OPTION]...") % File.basename($0)
65 printf " %3s, %-15s %s\n", ary[1], ary[0], ary[3]
70 parser = GetoptLong.new
71 parser.set_options(*$options.collect { |ary| ary[0..2] })
73 parser.each_option do |name, arg|
83 $source = arg.sub(%r|/$|, '')
84 if !File.directory?($source)
85 die _("Argument to --source must be a directory")
88 $dest = arg.sub(%r|/$|, '')
89 if File.exists?($dest) && !File.directory?($dest)
90 die _("If --destination exists, it must be a directory")
92 if $dest != make_dest_filename($dest)
93 die _("Sorry, destination directory can't contain non simple alphanumeric characters.")
96 # system("rm -rf #{$dest}")
101 if File.readable?(arg)
102 $xmldoc = REXML::Document.new File.new(arg)
105 die _('Config file does not exist or is unreadable.')
109 msg 1, _("Config skeleton file already exists, backuping to %s.backup") % arg
110 File.rename(arg, "#{arg}.backup")
112 $config_writeto = arg
114 when '--merge-config'
115 if File.readable?(arg)
116 msg 2, _("Merge config notice: backuping current config file to %s.backup") % arg
117 $xmldoc = REXML::Document.new File.new(arg)
118 File.rename(arg, "#{arg}.backup")
119 $config_writeto = arg
120 $mode = 'merge_config'
122 die _('Config file does not exist or is unreadable.')
135 when '--verbose-level'
136 $verbose_level = arg.to_i
146 if !$source && $xmldoc
147 $source = $xmldoc.root.attributes['source']
148 $dest = $xmldoc.root.attributes['destination']
149 $theme = $xmldoc.root.attributes['theme']
150 $limit_sizes = $xmldoc.root.attributes['limit-sizes']
154 die _("Missing --source or --config parameter.")
157 die _("Missing --destination parameter.")
163 select_theme($theme, $limit_sizes)
166 additional_params = ''
168 additional_params += "limit-sizes='#{$limit_sizes}'"
170 $xmldoc = Document.new "<booh version='#{$VERSION}' source='#{utf8($source)}' destination='#{utf8($dest)}' theme='#{$theme}' #{additional_params}/>"
171 $xmldoc << XMLDecl.new(XMLDecl::DEFAULT_VERSION, $CURRENT_CHARSET)
184 def check_installation
188 missing = %w(convert identify exif transcode mencoder).delete_if { |prg| system("which #{prg} >/dev/null 2>/dev/null") }
190 die _("The following programs are typically needed: `%s'. Re-run with --no-check if you're sure you're fine without them.") % missing.join(', ')
194 def replace_line(surround, keyword, line)
196 contents = eval "$#{keyword}"
197 line.sub!(/#{surround}#{keyword}#{surround}/, contents)
199 die _("No `%s' found for substitution") % keyword
203 def build_html_skeletons
204 $html_images = File.open("#{$FPATH}/themes/#{$theme}/skeleton_image.html").readlines
205 $html_thumbnails = File.open("#{$FPATH}/themes/#{$theme}/skeleton_thumbnails.html").readlines
206 $html_index = File.open("#{$FPATH}/themes/#{$theme}/skeleton_index.html").readlines
207 for line in $html_images + $html_thumbnails + $html_index
208 while line =~ /~~~(\w+)~~~/
209 replace_line('~~~', $1, line)
214 def find_caption_value(xmldir, filename)
215 xmldir.elements["[@filename='#{utf8(filename)}']"].attributes['caption']
218 def find_captions(xmldir, images)
219 return images.collect { |img| find_caption_value(xmldir, img) }
222 #- stolen from CVSspam
224 text.sub(/[^a-zA-Z0-9\-,.*_\/]/) do
225 "%#{sprintf('%2X', $&[0])}"
229 def html_reload_to_thumbnails
230 html_reload_to_thumbnails = $preferred_size_reloader.clone
231 html_reload_to_thumbnails.gsub!(/~~theme~~/, $theme)
232 html_reload_to_thumbnails.gsub!(/~~default_size~~/, $default_size['name'])
233 return html_reload_to_thumbnails
236 def discover_iterations(iterations, line)
237 if line =~ /~~iterate(\d)_open(_max(\d+))?~~/
238 for iter in iterations.values
241 iter['close_wait'] = $1.to_i
244 iterations[$1.to_i] = { 'open' => true, 'max' => $3, 'opening' => '', 'closing' => '' }
246 line.sub!(/.*/, '~~thumbnails~~')
250 elsif line =~ /~~iterate(\d)_close~~/
251 iterations[$1.to_i]['open'] = false;
252 iterations[$1.to_i]['close'] = true;
255 for iter in iterations.values
257 iter['opening'] += line
260 if !iter['close'] && iter['close_wait'] && iterations[iter['close_wait']]['close']
261 iter['closing'] += line
268 def reset_iterations(iterations)
269 for iter in iterations.values
274 def run_iterations(iterations)
276 for level in iterations.keys.sort
277 if iterations[level]['value'] == 1 || level == iterations.keys.max
278 html += iterations[level]['opening']
280 iterations[level]['value'] += 1
281 if iterations[level]['max'] && iterations[level]['value'] > iterations[level]['max'].to_i
282 iterations[level]['value'] = 1
283 iterations[level-1]['value'] = 1
284 html += iterations[level-1]['closing']
290 def close_iterations(iterations)
292 for level in iterations.keys.sort.reverse
293 html += iterations[level]['closing']
298 def img_element(fullpath)
299 if size = get_image_size(fullpath)
300 sizespec = 'width="${size[:x]}" height="${size[:y]}"'
304 return '<img src="' + File.basename(fullpath) + '" ' + sizespec + ' border="0"/>'
308 return name.gsub(/-/, '')
311 def substitute_html_sizes(html, sizeobj, type)
313 if $images_size.length > 1
314 for sizeobj2 in $images_size
315 if sizeobj != sizeobj2
316 if type == 'thumbnails'
317 sizestrings << '<a href="thumbnails-' + sizeobj2['name'] + '.html">' + sizename(sizeobj2['name']) + '</a>'
319 sizestrings << '<a id="link' + size2js(sizeobj2['name']) + '">' + sizename(sizeobj2['name']) + '</a>'
322 sizestrings << sizename(sizeobj2['name'])
326 html.sub!(/~~sizes~~(.+)~~/) { sizestrings.join($1) }
331 `find #{$source} -type d`.sort.each { |dir|
334 die _("Source directory or sub-directories can't contain a single-quote character, sorry.")
337 #- place xml document on proper node if exists, else create
338 xmldir = $xmldoc.elements["//dir[@path='#{utf8(dir)}']"]
339 if $mode == 'use_config'
344 if $mode == 'gen_config' || ($mode == 'merge_config' && !xmldir)
345 #- add the <dir..> element if necessary
346 parent = File.dirname(dir)
347 xmldir = $xmldoc.elements["//dir[@path='#{utf8(parent)}']"]
349 xmldir = $xmldoc.root
351 xmldir = xmldir.add_element 'dir', { 'path' => utf8(dir) }
355 #- read images/videos entries from config or from directories depending on mode
357 if $mode == 'use_config'
358 msg 2, _("Handling %s from config list...") % dir
359 xmldir.elements.each { |element|
360 if %w(image video).include?(element.name)
361 entries << from_utf8(element.attributes['filename'])
365 msg 2, _("Examining %s...") % dir
366 entries = Dir.entries(dir).sort
367 #- populate config in case of gen_config, add new files in case of merge_config
369 type = entry2type(file)
370 if type && !xmldir.elements["#{type}[@filename='#{utf8(file)}']"]
371 xmldir.add_element type, { "filename" => utf8(file), "caption" => utf8(file.sub(/\.[^\.]+$/, '')[0..17]) }
374 if $mode == 'merge_config'
375 #- cleanup removed files from config and reread entries from config to get proper ordering
377 xmldir.elements.each { |element|
378 fullpath = "#{dir}/#{from_utf8(element.attributes['filename'])}"
379 if %w(image video).include?(element.name)
380 if !File.readable?(fullpath)
381 msg 1, _("Config merge: removing %s from config; use the backup file to retrieve caption info if this was a mistake") % fullpath
382 xmldir.delete(element)
384 entries << from_utf8(element.attributes['filename'])
390 images = entries.find_all { |e| entry2type(e) == 'image' }
391 msg 3, _("\t%s images") % images.length
392 videos = entries.find_all { |e| entry2type(e) == 'video' }
393 msg 3, _("\t%s videos") % videos.length
395 dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
396 system("mkdir -p '#{dest_dir}'")
398 #- pass through if there are no images and videos
399 if images.size == 0 && videos.size == 0
403 msg 2, _("Outputting in %s...") % dest_dir
405 #- populate data structure with sizes from theme
406 for sizeobj in $images_size
407 fullscreen_images ||= {}
408 fullscreen_images[sizeobj['name']] = []
409 thumbnail_images ||= {}
410 thumbnail_images[sizeobj['name']] = []
411 thumbnail_videos ||= {}
412 thumbnail_videos[sizeobj['name']] = []
415 images.size >= 1 and msg 3, _("\tcreating images thumbnails...")
417 #- create thumbnails for images
419 base_dest_img = dest_dir + '/' + make_dest_filename(img.sub(/\.[^\.]+$/, ''))
421 thumbnail_dest_img = base_dest_img + "-#{$default_size['thumbnails']}.jpg"
422 gen_thumbnails_element("#{dir}/#{img}", xmldir, true, [ { 'filename' => thumbnail_dest_img, 'size' => $default_size['thumbnails'] } ])
424 for sizeobj in $images_size
425 size_fullscreen = sizeobj['fullscreen']
426 size_thumbnails = sizeobj['thumbnails']
427 fullscreen_dest_img = base_dest_img + "-#{size_fullscreen}.jpg"
428 thumbnail_dest_img = base_dest_img + "-#{size_thumbnails}.jpg"
429 fullscreen_images[sizeobj['name']] << File.basename(fullscreen_dest_img)
430 thumbnail_images[sizeobj['name']] << File.basename(thumbnail_dest_img)
431 gen_thumbnails_element("#{dir}/#{img}", xmldir, true, [ { 'filename' => fullscreen_dest_img, 'size' => size_fullscreen },
432 { 'filename' => thumbnail_dest_img, 'size' => size_thumbnails } ])
437 videos.size >= 1 and msg 3, _("\tcreating videos thumbnails...")
439 #- create thumbnails for videos
440 videos.each { |video|
443 thumbnail_dest_img = dest_dir + '/' + make_dest_filename(video.sub(/\.[^\.]+$/, '')) + "-#{$default_size['thumbnails']}.jpg"
444 thumbnail_ok &&= gen_thumbnails_element("#{dir}/#{video}", xmldir, true, [ { 'filename' => thumbnail_dest_img, 'size' => $default_size['thumbnails'] } ])
446 for sizeobj in $images_size
447 size_thumbnails = sizeobj['thumbnails']
448 thumbnail_dest_img = dest_dir + '/' + make_dest_filename(video.sub(/\.[^\.]+$/, '')) + "-#{size_thumbnails}.jpg"
449 thumbnail_videos[sizeobj['name']] << File.basename(thumbnail_dest_img)
450 thumbnail_ok &&= gen_thumbnails_element("#{dir}/#{video}", xmldir, true, [ { 'filename' => thumbnail_dest_img, 'size' => size_thumbnails } ])
453 destvideo = "#{dest_dir}/#{video}"
454 if !File.exists?(destvideo)
455 psys("cp '#{dir}/#{video}' '#{destvideo}'")
458 system("rm -f #{dest_dir}/screenshot.jpg000000.jpg")
462 #- copy any resource file that goes with the theme (css, images..)
463 for entry in Dir.entries("#{$FPATH}/themes/#{$theme}")
464 if !%w(. .. skeleton_image.html skeleton_thumbnails.html skeleton_index.html metadata CVS).include?(entry)
465 if !File.exists?("#{dest_dir}/#{entry}")
466 psys("cp '#{$FPATH}/themes/#{$theme}/#{entry}' '#{dest_dir}'")
471 msg 3, _("\tgenerating HTML pages...")
473 #- generate thumbnails.html (page with thumbnails)
474 for sizeobj in $images_size
475 html = $html_thumbnails.collect { |l| l.clone }
478 i.sub!(/~~run_slideshow~~/, images.size <= 1 ? '' : '<a href="image-' + sizeobj['name'] + '.html?run_slideshow">' + utf8(_('Run slideshow!')) + '</a>')
479 i.sub!(/~~title~~/, xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir)))
480 substitute_html_sizes(i, sizeobj, 'thumbnails')
481 discover_iterations(iterations, i)
484 reset_iterations(iterations)
486 type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
488 html_thumbnails += run_iterations(iterations)
490 index = images.index(file)
491 html_thumbnails.gsub!(/~~image_iteration~~/,
492 '<a href="image-' + size2js(sizeobj['name']) + '.html?current=' + fullscreen_images[sizeobj['name']][index] +
493 '" name="' + fullscreen_images[sizeobj['name']][index] + '">' +
494 img_element("#{dest_dir}/#{thumbnail_images[sizeobj['name']][index]}") + '</a>')
495 html_thumbnails.gsub!(/~~caption_iteration~~/,
496 find_caption_value(xmldir, images[index]) || utf8(images[index]))
497 html_thumbnails.gsub!(/~~ifimage\?~~(.+?)~~fi~~/) { $1 }
498 html_thumbnails.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/, '')
499 elsif type == 'video'
500 index = videos.index(file)
501 if File.exists?("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}")
502 html_thumbnails.gsub!(/~~image_iteration~~/,
503 '<a href="' + videos[index] + '">' + img_element("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}") + '</a>')
505 html_thumbnails.gsub!(/~~image_iteration~~/,
506 '<a href="' + videos[index] + '">' + utf8(_("(no preview)")) + '</a>')
508 html_thumbnails.gsub!(/~~caption_iteration~~/,
509 find_caption_value(xmldir, videos[index]) || utf8(videos[index]))
510 html_thumbnails.gsub!(/~~ifimage\?~~(.+?)~~fi~~/, '')
511 html_thumbnails.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/) { $1 }
515 html_thumbnails += close_iterations(iterations)
517 i.sub!(/~~thumbnails~~/, html_thumbnails)
518 i.gsub!(/~~theme~~/, $theme)
519 i.gsub!(/~~current_size~~/, sizeobj['name'])
521 ios = File.open("#{dest_dir}/thumbnails-#{sizeobj['name']}.html", "w")
526 #- generate "main" thumbnails.html page that will reload to correct size thanks to cookie
527 ios = File.open("#{dest_dir}/thumbnails.html", "w")
528 ios.write(html_reload_to_thumbnails)
531 #- generate image.html (page with fullscreen images)
533 captions4js = find_captions(xmldir, images).collect { |e| e ? '"' + e.gsub('"', '\"' ) + '"' : '""' }.join(', ')
534 for sizeobj in $images_size
535 html = $html_images.collect { |l| l.clone }
536 images4js = fullscreen_images[sizeobj['name']].collect { |e| "\"#{e}\"" }.join(', ')
539 for sizeobj2 in $images_size
540 if sizeobj != sizeobj2
541 otherimages4js += "var images_#{size2js(sizeobj2['name'])} = new Array(" + fullscreen_images[sizeobj2['name']].collect { |e| "\"#{e}\"" }.join(', ') + ")\n"
542 othersizes << "\"#{size2js(sizeobj2['name'])}\""
546 i.gsub!(/~~images~~/, images4js)
547 i.gsub!(/~~other_images~~/, otherimages4js)
548 i.gsub!(/~~other_sizes~~/, othersizes.join(', '))
549 i.gsub!(/~~captions~~/, captions4js)
550 i.gsub!(/~~title~~/, xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir)))
551 i.gsub!(/~~thumbnails~~/, '<a href="thumbnails-' + sizeobj['name'] + '.html" id="thumbnails">' + utf8(_('Return to thumbnails')) + '</a>')
552 i.gsub!(/~~theme~~/, $theme)
553 i.gsub!(/~~current_size~~/, sizeobj['name'])
554 substitute_html_sizes(i, sizeobj, 'image')
556 ios = File.open("#{dest_dir}/image-#{size2js(sizeobj['name'])}.html", "w")
566 #- add attributes to <dir..> elements needing so
567 if $mode != 'use_config'
568 msg 3, _("\tfixating configuration file...")
569 $xmldoc.elements.each('//dir') { |element|
570 path = captionpath = element.attributes['path']
571 descendant_element = element.elements['descendant::image'] || element.elements['descendant::video']
572 if !descendant_element
573 msg 3, _("\t\tremoving %s, no element in it") % path
574 element.remove #- means we have a directory with nothing interesting in it
576 captionfile = "#{descendant_element.parent.attributes['path']}/#{descendant_element.attributes['filename']}"
577 basename = File.basename(path)
578 if element.elements['dir']
579 if !element.attributes['subdirs-caption']
580 element.add_attribute('subdirs-caption', basename)
582 if !element.attributes['subdirs-captionfile']
583 element.add_attribute('subdirs-captionfile', captionfile)
586 if element.elements['image'] || element.elements['video']
587 if !element.attributes['thumbnails-caption']
588 element.add_attribute('thumbnails-caption', basename)
590 if !element.attributes['thumbnails-captionfile']
591 element.add_attribute('thumbnails-captionfile', captionfile)
598 #- write down to disk config if necessary
600 ios = File.open($config_writeto, "w")
601 $xmldoc.write(ios, 0)
606 msg 3, _(" completed necessary stuff for GUI, exiting.")
610 #- second pass to create index.html files
611 msg 3, _("\trescanning directories to generate all `index.html' files...")
613 `find #{$source} -type d`.each { |dir|
615 xmldir = $xmldoc.elements["//dir[@path='#{utf8(dir)}']"]
619 dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
621 if xmldir.elements['dir']
622 html = $html_index.collect { |l| l.clone }
625 caption = xmldir.attributes['subdirs-caption']
626 i.gsub!(/~~title~~/, caption)
627 if xmldir.parent.name == 'dir'
630 parent = xmldir.parent
631 while parent.name == 'dir'
632 parentcaption = parent.attributes['subdirs-caption']
633 nav = "<a href='#{path}/index.html'>#{parentcaption}</a> #{utf8(_(" > "))} #{nav}"
635 parent = parent.parent
637 i.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/) { $1 }
638 i.gsub!(/~~navigation~~/, nav + caption)
640 i.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/, '')
642 discover_iterations(iterations, i)
646 reset_iterations(iterations)
648 #- deal with "current" album (directs to "thumbnails" page)
649 if xmldir.attributes['thumbnails-caption']
650 thumbnail = "#{dest_dir}/thumbnails-thumbnail.jpg"
651 gen_thumbnails_subdir(from_utf8(xmldir.attributes['thumbnails-captionfile']), xmldir, false,
652 [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ], 'thumbnails')
653 html_index += run_iterations(iterations)
654 html_index.gsub!(/~~image_iteration~~/, "<a href='thumbnails.html'>" + img_element(thumbnail) + '</a>')
655 html_index.gsub!(/~~caption_iteration~~/, xmldir.attributes['thumbnails-caption'])
657 #- cleanup temp for videos
658 system("rm -f #{dest_dir}/screenshot.jpg000000.jpg")
660 #- deal with sub-albums (direct to subdirs/index.html pages)
661 xmldir.elements.each('dir') { |child|
662 subdir = make_dest_filename(from_utf8(File.basename(child.attributes['path'])))
663 thumbnail = "#{dest_dir}/thumbnails-#{subdir}.jpg"
664 html_index += run_iterations(iterations)
665 captionfile, caption = find_subalbum_caption_info(child)
666 gen_thumbnails_subdir(captionfile, child, false,
667 [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ], find_subalbum_info_type(child))
668 html_index.gsub!(/~~caption_iteration~~/, caption)
669 html_index.gsub!(/~~image_iteration~~/, "<a href='#{make_dest_filename(subdir)}/index.html'>" + img_element(thumbnail) + '</a>')
670 #- cleanup temp for videos
671 system("rm -f #{dest_dir}/screenshot.jpg000000.jpg")
674 html_index += close_iterations(iterations)
677 i.gsub!(/~~thumbnails~~/, html_index)
681 html = html_reload_to_thumbnails
684 ios = File.open("#{dest_dir}/index.html", "w")
688 #- substitute "return to albums" correctly
689 `find '#{dest_dir}' -maxdepth 1 -name "thumbnails*.html"`.each { |thumbnails|
691 contents = File.open(thumbnails.chomp).readlines
693 if xmldir.elements['dir']
694 i.sub!(/~~return_to_albums~~/, '<a href="index.html">' + utf8(_('Return to albums')) + '</a>')
696 if xmldir.parent.name == 'dir'
697 i.sub!(/~~return_to_albums~~/, '<a href="../index.html">' + utf8(_('Return to albums')) + '</a>')
699 i.sub!(/~~return_to_albums~~/, '')
703 ios = File.open(thumbnails, "w")
709 msg 3, _(" all done.")