#!/bin/sh # vim:set ft=tcl: \ exec tclsh "$0" "$@" # require Tcl version of at least 8.5 since I use 'ni' and 'in' in expressions for lists package require Tcl 8.5 package require sqlite3 if { $argc < 1 } { puts {Populates photo cache directory for users from the database} puts {Usage:} puts " $argv0 database_filename" puts {} puts {Example:} puts " $argv0 2013_Spring_Phys742" exit } set dbfile [lindex $argv 0] source ./GradeBook_lib.tcl set config_file "./gb_config.tcl" if { [file exists $config_file] && ("$config_file" ne "") } { source $config_file } else { puts "error: config file {$config_file} does not exist" exit } if { [file exists $dbfile] } { sqlite3 db $dbfile } else { puts "error: non existing DB filename {$dbfile}" exit } proc getAllIds {ids_col table_with_ids} { set ids {} set eval_str "SELECT \"$ids_col\" FROM \"$table_with_ids\"" set err [catch { db eval $eval_str v { if { [info exist v($ids_col)] } { lappend ids $v($ids_col) } } } errStat ] if { $err } { puts "the following error happen: $errStat" msg_level_critical } return $ids } proc cachePhotoForId { IdNum } { # attempt to cache the photo for a given id global GradebookServerConfig set photo_album_base_url $GradebookServerConfig(photo_album_base_url) set photo_album_cache $GradebookServerConfig(photo_album_cache) # generate url pointing to a photo of a user with the given IdNum set photo_file "${IdNum}.jpg" set cached_photo_file "$photo_album_cache/${photo_file}" set url "$photo_album_base_url/$photo_file" if { [file exists "$cached_photo_file"] } { # file already cached no need to download return } if { ![file exists "$photo_album_cache"] } { # cache directory missing let's make it set errMkDir [catch { file mkdir "$photo_album_cache" } errStat ] if { $errMkDir } { puts "Error: $errStat" return } } # Download url to cache # below replacing whitespace with %20 and # with %23 in the URL in $target set url [string map {{ } %20 {#} %23 } $url] set command_str exec lappend command_str wget lappend command_str -q lappend command_str -c lappend command_str --output-document=$cached_photo_file lappend command_str $url # TODO: devise some sort of lock mechanism to protect against duplicate downloads set err [catch {eval $command_str} result] if { $err } { puts "Something wrong with download of {$url}" # remove erroneous download file file delete $cached_photo_file } else { puts "Successful download of {$url}" } } set table_with_ids GradesTable set ids_col IdNum if { ![doesColumnExists $ids_col $table_with_ids] } { puts "something wrong with database: the column {$ids_col} does not exist in table {$table_with_ids}" db close exit } set ids [getAllIds "$ids_col" "$table_with_ids"] foreach id $ids { if { "$id" eq "" } { # invalid/useless id continue } cachePhotoForId $id } db close # vim: ts=2 sw=2 foldmethod=indent: