View unanswered posts    View active topics

All times are UTC - 6 hours





Post new topic Reply to topic  [ 2 posts ] 
Print view Previous topic   Next topic  
Author Message
Search for:
PostPosted: Tue Jul 18, 2006 4:58 am 
Offline
Joined: Sat Jan 28, 2006 11:29 am
Posts: 83
I wrote these scripts to enable me to easily import all my divx and regular DVD's into the Myth Database, so as to be able to select a video in mythvideo and then be prompted to insert the relevant disk (if not already inserted). Your Disks should be numbered 0001,0002 etc. I keep mine in a disk folder.

The add dvd script, prompts for the next disk and remembers the previous one. It scans for files adds them all to the database and grabs the info from imdb for each one. To end it hit ok without inserting a disk. You can type a 1 digit number in the prompt to change the category or a 5 digit number where digit1=new category and digits2-5 = new disk number. It remembers the settings so if banging in a few hundred disks you can just pop them in one after the other.

It uses the first imdb entry it gets and sometimes is wrong. You can call getimdb script seperately, it takes all kinds of argument permutations explained at top of the script. I use it in conjunction with webmin. You may need to get covers manually, the database entry alreay points to the correct one. I used the imdbnum.jpg for movies or for series imdbnum.01.jpg

The final script is the playback one, I just change the app to use for playback to this script for videos in myth setup. the script will handle all kinds of video. I used to use mplayer but now use xine.

It is a lot, lot harder to explain how to use than to actually use. it has no error checking or idiot proofing. It was totally proprietry for my use and seems complicated but it is doing a lot of work. I get the feeling they may be too convoluted or akward for people to use, but at least it acts as a framework for how it might work one day. They may need modifying to make them more generic as the playback script for example in my case uses diff settings dependant on whether it is running on a 16:9 TV or a 4:3 projector. But anyone is free to do what they will to the scripts to improve or simplify them. Maybe it really needs an installer script. Maybe I'll get round to doing one, but these have been sat here for a few months now so I thought I'll just post them. Once installed and working they appear very seamless and work easily.

There is one downside that in 0.19 the mythvideo dev trashed the code so it doesn't work as a database properly anymore. Obviously these scripts are creating database entries for files that don't exist. So you don't want to run the regular scan for movies code and delete files not found. On myth 0.18 it worked really well but in 0.19 .... oh don't get me started...

I'm not sure if the forums word wrapping will corrupt things or not. If so I can put a zip somewhere. Each scripts header has some info and the appropriate storage location. Obviously they all need chmod 770 to make them executeable. Also it scans and so places files in library folder at root of mythvideo so I created a symlink to the dvd drive
Code:
#ln -sf /cdrom /myth/video/library


OK here goes...

Code:
#!/bin/bash
# Written by HappyTalk April 2006
# /usr/local/bin/add_dvd.sh
# called before video manager to prompt for dvd num and update last entries (using prev dvd number)

FAKEPATH='/myth/video/library' #path that files will appear to be at in myth
POSTERPATH="/myth/video/.covers/"
CATEGORY=4 #change on fly for diff disks if you wish
CATS=( None Comedy Doc Drama Movie Music SciFi Karaoke )

EXITVAL=0
export DVDNUMFILE="/home/mythtv/.DVDINFO"
ECHO_OUT='/myth/tmp/add_dvd.log'

#-------------------------------------------------

#converts string in $1 to proper case & _ = spaces, rets in $2
function ProperCase() {
   WORDS=${1//"_"/" "}
   PCASE=""   
   for WORD in ${WORDS[@]}
   do
      PCASE="${PCASE}`echo ${WORD:0:1} | tr "[:lower:]" "[:upper:]"`"
      PCASE="${PCASE}`echo ${WORD:1} | tr "[:upper:]" "[:lower:]"` "
   done
   eval "$2='${PCASE% }'"
}


function AddVideo() {
   echo db_title = \"${DB_TITLE}\" | tee -a ${ECHO_OUT}
   echo db_filename = \"${DB_FILENAME}\"  | tee -a ${ECHO_OUT}
   echo db_playcommand = ${DB_PLAYCOMMAND}  | tee -a ${ECHO_OUT}

   #need to check if exists already! ie if playcommand already exists as that is only unique thing
   VIDEO_ID=$(mysql -u root -e "SELECT intid FROM mythconverg.videometadata WHERE playcommand = '${DB_PLAYCOMMAND}';" -BN)

   if [[ ${VIDEO_ID} == "" ]] ; then
      VIDEO_ID=$(mysql -u root -e "INSERT INTO mythconverg.videometadata VALUES (-1,'${DB_TITLE}','Unknown','None','NR','00000000',1895,0,0,1,'${DB_FILENAME}','No Cover',-1,1,'${DB_PLAYCOMMAND}', ${CATEGORY}); SELECT LAST_INSERT_ID();" -BN)
      echo Added video $VIDEO_ID: \"${DB_TITLE}\" | tee -a ${ECHO_OUT}
      let FILECOUNT+=1 #inc filecount

      getimdb.sh $VIDEO_ID "$MAINTITLE"
      
      if [[ $SERIES != "" ]] ; then
         mysql -u root -e "UPDATE mythconverg.videometadata SET coverfile = CONCAT('${POSTERPATH}',inetref,'-${SERIES}00.jpg') WHERE intid = ${VIDEO_ID};"
      fi   
      
   else
      echo ID: ${VIDEO_ID} already set for \"${DB_TITLE}\" | tee -a ${ECHO_OUT}
   fi   
}

#-----------------------------------------------------------------



while [ ${EXITVAL} -eq 0 ] ; do ### endless loop for if $1 = -1
   
   FILECOUNT=0

   #prompt for new DVD Num
   sudo /usr/bin/eject /dev/scd0
   xterm -xrm "xterm*allowSendEvents: true" -bg NavyBlue -fg White +sb -fa 'Arial Bold' -fs 32 -geometry 32x5+200+200 -e prompt_dvdnum.sh

   DVDINFO=$(< ${DVDNUMFILE}) #read DVDNUM < ${DVDNUMFILE}
   CATEGORY=${DVDINFO:1:1}
   DVDNUM=${DVDINFO:2:4}
   CATSTRING=${CATS[${CATEGORY}]}
   echo Category=\"$CATSTRING\" DVD Number=\"$DVDNUM\" | tee -a ${ECHO_OUT}

   #TEST PROMPT
   #echo $((10#$DVDNUM + 1)) > $DVDNUMFILE #and save it
   #exit 1

   mount /cdrom
   DISKID=`volname /dev/scd0`

   if [[ ${DISKID} == "" ]] ; then #no disk inserted so quit out of loop
      echo 'No disk inserted exiting...' | tee -a ${ECHO_OUT}
      EXITVAL=1 #set exitval so quits out
   else
      echo DVD_VOLUME = \"$DISKID\" | tee -a ${ECHO_OUT}

      O=$IFS
      IFS=$'\n'
      #VIDFILES=(`find /cdrom -type f -iname *.avi -or -iname *.mpg`)
      VIDFILES=(`find /cdrom -type f -iregex '.*\.\(mpg\|mpeg\|avi\|wmv\|mov\|rm\|asf\|mp4\|ogm\)'`)
      DVDFILES=(`find /cdrom -type f -iregex '.*\.\(ifo\)'`)
      IFS=$O

      if [[ ${#DVDFILES[@]} -gt 0 ]] ; then
         ProperCase "${DISKID}" DB_TITLE
         DB_FILENAME="${FAKEPATH}/${DB_TITLE}.ifo"
         DB_PLAYCOMMAND="playvideo.sh dvdrom ${DVDNUM}"   
         AddVideo # call func to actually add the video info to db
      else
         for (( i = 0 ; i < ${#VIDFILES[@]} ; i++ )) #for (( i = 28 ; i < 29 ; i++ ))
         do
            echo Adding video $i = \"${VIDFILES[$i]}\" | tee -a ${ECHO_OUT}

            VIDFILE=${VIDFILES[$i]//"'"/"''"} #replace single quotes with 2 single quotes so mysql doesn't spaz out
            VIDFILENAME=${VIDFILE##*/} #remove path from start
            echo videofilename = \"${VIDFILENAME}\" | tee -a ${ECHO_OUT}

            DB_TITLE=${VIDFILENAME%.*} #remove file extension from end
            DB_TITLE=${DB_TITLE%.01}    #remove .01 from end if there (.02 is OK as will be stacked, so invisible  anyway)
            DB_TITLE=${DB_TITLE% [*}   #remove [xx] from end
            DB_TITLE=${DB_TITLE% (*}   #remove (2001,...) from end

            #check for series
            MAINTITLE=${DB_TITLE%%.?x??.*} #extract SERIES from start if poss
            if [[ $MAINTITLE != $DB_TITLE ]] ; then
               DB_TITLE=${DB_TITLE:${#MAINTITLE}+1} #chop SERIES OFF START
               SERIES=${DB_TITLE:0:1}
               DB_FILENAME=${FAKEPATH}/$CATSTRING/$MAINTITLE/${VIDFILENAME} #filename stored without excess path, though user can add extra after library/ to get subfolders in gallery view for series etc
            else
               DB_FILENAME=${FAKEPATH}/$CATSTRING/${VIDFILENAME} #filename stored without excess path, though user can add extra after library/ to get subfolders in gallery view for series etc
               SERIES=""
            fi
            
            DB_PLAYCOMMAND="playvideo.sh \"${VIDFILE/'${FAKEPATH}'/'/cdrom'}\" ${DVDNUM}"

            AddVideo # call func to actually add the video info to db
            echo ------ | tee -a ${ECHO_OUT}
         done
      fi
      sudo /usr/bin/eject /dev/scd0

      xterm -bg NavyBlue -fg White +sb -fa 'Arial Bold' -fs 32 -geometry 26x5+200+200 -e prompt.sh "${FILECOUNT} new files added" "" 1 #no keys presses req'd
      echo ${FILECOUNT} new video files added to database | tee -a ${ECHO_OUT}

      echo $(( $DVDINFO + 1 )) > $DVDNUMFILE #and save it

      echo --------------- | tee -a ${ECHO_OUT}
   fi
done #### loop until no disk inserted

echo ----------------------------------------------- | tee -a ${ECHO_OUT}

exit 0


Code:
#!/bin/bash
# Written by HappyTalk April 2006
# /usr/local/bin/getimdb.sh
# Arg[1] = VIDEO_ID to update (ignores prev imdb num
# Arg[1] = "" => Uses first db record with inetref="00000000"
# Arg[1] = "-1" => Update ALL db records with inetref="00000000"

# Arg[2] = (optional) IMDBNUM => if Arg[1] = VIDEO_ID then arg[2] may be used to force the IMDBNUM to use rather than rely on a lookup
# Arg[2] = (optional) Title => if Arg[1] = VIDEO_ID then arg[2] may be used to force the title to use rather than rely on a lookup

# return 0 = OK
# return 1 = No more records to update (if $1 = -1 will always return 1 for ok or higher for error)
# return 2 = No title name found in database, hence not able to search. (inetref set = "" so won't search again, unless exact initid sent or inetref set = "00000000"
# return 3 = No IMDB entry found (inetref set = "" as above)

LOGFILE='/myth/video/.covers/getimdb.log'
POSTERPATH="/myth/video/.covers/"
ADDCOUNT=0
STACKCOUNT=0
COPYCOUNT=0
BADCOUNT=0
NOIMDBCOUNT=0
EXITVAL=0

DOTITLE=0  #turn copying imdb title over current title on/off. Turn off for series where 1x10 is req'd
STACKING=1 #turn stacking on/off


#case $2 in *[^[:digit:]]*) echo not a number;; *) echo okay;; esac
function IsNumber() { case $1 in *[^[:digit:]]*) return 1 ;; *) return 0 ;; esac }  # function IsNumber() { case $1 in *[^[:digit:]]*) echo 0 ;; *) echo 1 ;; esac }

while [ $EXITVAL -eq 0 ] ; do ### endless loop for if $1 = -1
   VIDEO_ID=""
   IMDBNUM=""
   TITLE=""
   
   if [[ $1 == "" || $1 == "-1" ]] ; then
      # Only do for category = movies
      VIDEO_ID=`mysql -u root -e "SELECT intid FROM mythconverg.videometadata WHERE inetref = '00000000' && category = 4 LIMIT 0, 1;" -BN`

      if [[ $VIDEO_ID = "" ]] ; then #no unchecked items left
         echo "FINISHED: No more records to update" | tee -a ${LOGFILE}
         EXITVAL=10
      fi
   else
      VIDEO_ID=$1
      if [[ ${#2} = 7 ]] && IsNumber "$2"; then    # if [[ ${#2} = 7 && $(IsNumber $2) = 1 ]] ; then
         IMDBNUM=$2
      else
         TITLE=$2
      fi
   fi

#echo videoid = \"$VIDEO_ID\" , title = \"$TITLE\" , imdbnum = \"$IMDBNUM\"
#exit 1
   
   if [[ $EXITVAL -eq 0 && $IMDBNUM == "" ]] ; then
      echo video_id = \"$VIDEO_ID\" | tee -a ${LOGFILE}

      if [[ $TITLE == "" ]] ; then
         TITLE=`mysql -u root -e "SELECT title FROM mythconverg.videometadata WHERE intid = $VIDEO_ID;" -BN`
      fi
      
      if [[ $TITLE = "" ]] ; then #not found in imdb
         echo "ERROR: No title set for record $VIDEO_ID" | tee -a ${LOGFILE}
         let BADCOUNT+=1 # ((BADCOUNT += 1)) inc number of files with no imdb val
         EXITVAL=11
      else
         echo original title = \"${TITLE}\" | tee -a ${LOGFILE}
      #   TITLE=${TITLE%% -*} #remove all after first space hyphen (lose CD1/CD2/1x01 etc)
      #   TITLE=${TITLE%% .*} #remove all after first dot found
         echo search title = \"$TITLE\" | tee -a ${LOGFILE}

         ### Get IMDBNUM
         
         DVDCMD=(/usr/share/mythtv/mythvideo/scripts/imdb.pl -M tv=no\;video=no "$TITLE") #for movies
#         DVDCMD=(/usr/share/mythtv/mythvideo/scripts/imdb.pl -M tv=yes\;video=yes "$TITLE") #for tv shows
         IMDBNUM=`"${DVDCMD[@]}"` #0159273:Behind Enemy Lines (2001) 0091713:Behind Enemy Lines (1986) 0115647:Behind Enemy Lines (1998) 0093345:Killer Instinct (1987)
         IMDBNUM=${IMDBNUM%%:*}   #get all before ':' (extract imdbnum)

         if [[ $IMDBNUM == "" ]] ; then #not found in imdb
            echo "ERROR: No IMDB Number found"  | tee -a ${LOGFILE}
            let NOIMDBCOUNT+=1 #inc number of files with no imdb val
            EXITVAL=12
         fi
      fi

      if [[ $EXITVAL -ne 0 ]] ; then  #If no title or imdbnum, clear imdbnum so doesn't search again
         mysql -u root -e "UPDATE mythconverg.videometadata SET inetref = '' WHERE intid = '${VIDEO_ID}';"   
      fi
   fi   

   if [[ $EXITVAL -eq 0 ]] ; then
      echo imdbnum = \"$IMDBNUM\" | tee -a ${LOGFILE}

      VIDEO_ID_ORIG=`mysql -u root -e "SELECT intid FROM mythconverg.videometadata WHERE inetref = '${IMDBNUM}' && intid <> '${VIDEO_ID}' LIMIT 0, 1;" -BN`
      if [[ $VIDEO_ID_ORIG == "" ]] ; then #IMDBNUM not already in db for other movie so add new one
         ### Download Poster locally to POSTERPATH
         DVDCMD=(/usr/share/mythtv/mythvideo/scripts/imdb.pl -P "$IMDBNUM")
         POSTERURL=`"${DVDCMD[@]}"` # http://www.impawards.com/2001/posters/behind_enemy_lines.jpg
         POSTERPATHNAME="${POSTERPATH}${IMDBNUM}.jpg"
         
         if [[ $POSTERURL != "" ]] ; then         
            echo copying poster file from \"$POSTERURL\" to \"$POSTERPATHNAME\" | tee -a ${LOGFILE}
            cd "${POSTERPATH}"
            wget -b -a "wget-log" -O "${IMDBNUM}.jpg" "${POSTERURL}" #grab poster in background
         else
#            POSTERPATHNAME="No Cover: ${POSTERPATHNAME}"
            echo No Poster Found!!! | tee -a ${LOGFILE}
         fi

         ### Get Movie info
         DVDCMD=(/usr/share/mythtv/mythvideo/scripts/imdb.pl -D "$IMDBNUM")
         IMDBINFO=`"${DVDCMD[@]}"`
         # imdbinfo = Title:Behind Enemy Lines Year:2001 Director:John Moore Plot:A Navy navigator is shot down over enemy territory and is ruthlessly pursued by a secret police enforcer and the opposing troops. Meanwhile his commanding officer goes against orders in an attempt to rescue him. UserRating:6.0 MovieRating:Rated PG-13 for war violence and some language. Runtime:106 Writers: Jim Thomas Cast: Owen Wilson,Gene Hackman,Gabriel Macht,Charles Malik Whitfield,David Keith,Olek Krupa,Joaquim de Almeida,Vladimir Mashkov,Marko Igonda,Eyal Podell,Geoffrey Pierson,Aernout Van Lynden,Sam Jaeger,Shane Johnson,Don Winston Genres: Action,War,Drama,Thriller Countries: USA
         echo imdb_Info = \"$IMDBINFO\" | tee -a ${LOGFILE}

         # Extract Title
         IMDB_Title=${IMDBINFO##Title:}
         IMDB_Title=${IMDB_Title%%?Year:*}
         IMDB_Title=${IMDB_Title//\'/\\\'} #sub ' with \' (single ' escapes all chars except ') Alt = IMDB_Title=${IMDB_Title//"'"/"''"}
         echo imdb_Title = \"$IMDB_Title\" | tee -a ${LOGFILE}

         # Extract Year
         IMDB_Year=${IMDBINFO##*Year:}
         IMDB_Year=${IMDB_Year%%?Director:*}
         echo imdb_Year = \"$IMDB_Year\" | tee -a ${LOGFILE}

         # Extract Director
         IMDB_Director=${IMDBINFO##*Director:}
         IMDB_Director=${IMDB_Director%%?Plot:*}
         IMDB_Director=${IMDB_Director//\'/\\\'}
         echo imdb_Director = \"$IMDB_Director\" | tee -a ${LOGFILE}

         # Extract Plot
         IMDB_Plot=${IMDBINFO##*Plot:}
         IMDB_Plot=${IMDB_Plot%%?UserRating:*}
         IMDB_Plot=${IMDB_Plot//\'/\\\'}
         echo imdb_Plot = \"$IMDB_Plot\" | tee -a ${LOGFILE}

         # Extract UserRating
         IMDB_UserRating=${IMDBINFO##*UserRating:}
         IMDB_UserRating=${IMDB_UserRating%%?MovieRating:*}
         echo imdb_UserRating = \"$IMDB_UserRating\" | tee -a ${LOGFILE}

         # Extract MovieRating
         IMDB_MovieRating=${IMDBINFO##*MovieRating:}
         IMDB_MovieRating=${IMDB_MovieRating%%?Runtime:*}
         IMDB_MovieRating=${IMDB_MovieRating//\'/\\\'}
         echo imdb_MovieRating = \"$IMDB_MovieRating\" | tee -a ${LOGFILE}

         # Extract Runtime
         IMDB_Runtime=${IMDBINFO##*Runtime:}
         IMDB_Runtime=${IMDB_Runtime%%?Writers:*}
         echo imdb_Runtime = \"$IMDB_Runtime\" | tee -a ${LOGFILE}

         # Extract Writers
         IMDB_Writers=${IMDBINFO##*Writers: }
         IMDB_Writers=${IMDB_Writers%%?Cast:*}
         IMDB_Writers=${IMDB_Writers//\'/\\\'}
         echo imdb_Writers = \"$IMDB_Writers\" | tee -a ${LOGFILE}

         # Extract Cast
         IMDB_Cast=${IMDBINFO##*Cast: }
         IMDB_Cast=${IMDB_Cast%%?Genres:*}
         IMDB_Cast=${IMDB_Cast//\'/\\\'}
         echo imdb_Cast = \"$IMDB_Cast\" | tee -a ${LOGFILE}

         # Extract Genres : Add to videogenre & videometadatagenre
         IMDB_Genres=${IMDBINFO##*Genres: }
         IMDB_Genres=${IMDB_Genres%%?Countries:*}
         IMDB_Genres=${IMDB_Genres//\'/\\\'}
         echo imdb_Genres = \"$IMDB_Genres\" | tee -a ${LOGFILE}

         # Extract Countries : Add to videocountry & videometadatacountry
         IMDB_Countries=${IMDBINFO##*Countries: }
         IMDB_Countries=${IMDB_Countries//\'/\\\'}
         echo imdb_Countries = \"$IMDB_Countries\" | tee -a ${LOGFILE}

         # UPDATE DB (REMOVED category = 4)
         if [[ $DOTITLE == 1 ]] ; then         
            mysql -u root -e "UPDATE mythconverg.videometadata SET title = '${IMDB_Title}', director = '${IMDB_Director}', plot = '${IMDB_Plot}', rating = '${IMDB_MovieRating}', inetref = '${IMDBNUM}', year = '${IMDB_Year}', userrating = '${IMDB_UserRating}', length = '${IMDB_Runtime}', coverfile = '${POSTERPATHNAME}' WHERE intid = '${VIDEO_ID}';"
         else
            mysql -u root -e "UPDATE mythconverg.videometadata SET director = '${IMDB_Director}', plot = '${IMDB_Plot}', rating = '${IMDB_MovieRating}', inetref = '${IMDBNUM}', year = '${IMDB_Year}', userrating = '${IMDB_UserRating}', length = '${IMDB_Runtime}', coverfile = '${POSTERPATHNAME}' WHERE intid = '${VIDEO_ID}';"
         fi   

         O=$IFS         
         IFS=","
         IMDB_Country_Array=(${IMDB_Countries})
         IMDB_Genre_Array=(${IMDB_Genres})
         IFS=$O

         # videogenre + videometadatagenre
         mysql -u root -e "DELETE FROM mythconverg.videometadatagenre WHERE idvideo = '${VIDEO_ID}';"
         for (( i = 0 ; i < ${#IMDB_Genre_Array[@]} ; i++ ))
         do
            NewGenre=${IMDB_Genre_Array[$i]}
            GENRE_ID=`mysql -u root -e "SELECT intid FROM mythconverg.videogenre WHERE genre = '${NewGenre}';" -BN`

            if [[ ${GENRE_ID} == "" ]] ; then
               GENRE_ID=`mysql -u root -e "INSERT INTO mythconverg.videogenre VALUES (-1,'${NewGenre}'); SELECT LAST_INSERT_ID();" -BN`
               echo Added new genre: \"${NewGenre}\" | tee -a ${LOGFILE}
            else   
               echo Genre already exists: \"${NewGenre}\" | tee -a ${LOGFILE}
            fi
            mysql -u root -e "INSERT INTO mythconverg.videometadatagenre VALUES ('${VIDEO_ID}','${GENRE_ID}');"
         done

         # videocountry + videometadatacountry
         mysql -u root -e "DELETE FROM mythconverg.videometadatacountry WHERE idvideo = '${VIDEO_ID}';"
         for (( i = 0 ; i < ${#IMDB_Country_Array[@]} ; i++ ))
         do
            NewCountry=${IMDB_Country_Array[$i]}
            COUNTRY_ID=`mysql -u root -e "SELECT intid FROM mythconverg.videocountry WHERE country = '${NewCountry}';" -BN`

            if [[ ${COUNTRY_ID} == "" ]] ; then
               COUNTRY_ID=`mysql -u root -e "INSERT INTO mythconverg.videocountry VALUES (-1,'${NewCountry}'); SELECT LAST_INSERT_ID();" -BN`
               echo Added new country: \"${NewCountry}\" | tee -a ${LOGFILE}
            else   
               echo Country already exists: \"${NewCountry}\" already exists | tee -a ${LOGFILE}
            fi
            mysql -u root -e "INSERT INTO mythconverg.videometadatacountry VALUES ('${VIDEO_ID}','${COUNTRY_ID}');"
         done

         let ADDCOUNT+=1 #inc number of new files added
         EXITVAL=1
      else #got matching imdb record so no need to re-add
         # copy fields
         # src = VIDEO_ID_ORIG
         # dest VIDEO_ID

         STACKOK=0 #assume not stackable
         if [[ $STACKING == 1 ]] ; then
            # may have found earlier match, see if id before hand is a match
            VIDEO_ID_ADJ=$(mysql -u root -e "SELECT intid FROM mythconverg.videometadata WHERE inetref = '${IMDBNUM}' && intid = $((VIDEO_ID - 1));" -BN)
            if [[ $VIDEO_ID_ADJ != "" ]] ; then
               VIDEO_ID_ORIG=${VIDEO_ID_ADJ}
            fi   
            
            if [[ $VIDEO_ID -eq $((VIDEO_ID_ORIG + 1)) ]] ; then
               EPNUM1=$(mysql -u root -e "SELECT filename FROM mythconverg.videometadata WHERE intid = $VIDEO_ID_ORIG;" -BN)
               EPNUM1=$((${EPNUM1:(-6):2}))
               EPNUM2=$(mysql -u root -e "SELECT filename FROM mythconverg.videometadata WHERE intid = $VIDEO_ID;" -BN)
               EPNUM2=$((${EPNUM2:(-6):2} - 1))
               echo EPNUM1=$EPNUM1 , EPNUM2=$EPNUM2
               if [ ${EPNUM1} -gt 0 ] && [ ${EPNUM1} -eq ${EPNUM2} ] ; then # both eps must end with adjacent nums eg xxxx.01.??? and xxxx.02.??? to be stackable
                  STACKOK=1
               fi
            fi
         fi
         
         if [[ ${STACKOK} == 1 ]] ; then
            #copy & stack! as adjacent to original. so will only stack at most 2 videos together (don't want series to stack, just 2cd movies)
            #note for series first 2 eps will therefore end up stacked, but they can be manually unstacked
            #it is NOT advisable to stack more than 2 entries or myth will keep trying to play them one after the other.
            if [[ $DOTITLE == 1 ]] ; then         
               mysql -u root -e "USE mythconverg; UPDATE videometadata AS src, videometadata AS dest SET dest.title=src.title, dest.director=src.director, dest.plot=src.plot, dest.rating=src.rating, dest.inetref=src.inetref, dest.year=src.year, dest.userrating=src.userrating, dest.length=src.length, dest.coverfile=src.coverfile, src.childid=${VIDEO_ID}, dest.browse=0 WHERE src.intid=${VIDEO_ID_ORIG} AND dest.intid=${VIDEO_ID};"
            else   
               mysql -u root -e "USE mythconverg; UPDATE videometadata AS src, videometadata AS dest SET dest.director=src.director, dest.plot=src.plot, dest.rating=src.rating, dest.inetref=src.inetref, dest.year=src.year, dest.userrating=src.userrating, dest.length=src.length, dest.coverfile=src.coverfile, src.childid=${VIDEO_ID}, dest.browse=0 WHERE src.intid=${VIDEO_ID_ORIG} AND dest.intid=${VIDEO_ID};"
            fi
            
            echo Stacked id:${VIDEO_ID} on id:${VIDEO_ID_ORIG} | tee -a ${LOGFILE}
            let STACKCOUNT+=1 #inc number of new files stacked
         else
            # normal copy NOTE neither one sets title this is left to differ from other entry with same imdb
            if [[ $DOTITLE == 1 ]] ; then         
               mysql -u root -e "USE mythconverg; UPDATE videometadata AS src, videometadata AS dest SET dest.title=src.title, dest.director=src.director, dest.plot=src.plot, dest.rating=src.rating, dest.inetref=src.inetref, dest.year=src.year, dest.userrating=src.userrating, dest.length=src.length, dest.coverfile=src.coverfile, src.childid=-1, dest.browse=1 WHERE src.intid=${VIDEO_ID_ORIG} AND dest.intid=${VIDEO_ID};"
            else   
               mysql -u root -e "USE mythconverg; UPDATE videometadata AS src, videometadata AS dest SET dest.director=src.director, dest.plot=src.plot, dest.rating=src.rating, dest.inetref=src.inetref, dest.year=src.year, dest.userrating=src.userrating, dest.length=src.length, dest.coverfile=src.coverfile, src.childid=-1, dest.browse=1 WHERE src.intid=${VIDEO_ID_ORIG} AND dest.intid=${VIDEO_ID};"
            fi
            
            echo Copied id:${VIDEO_ID} from id:${VIDEO_ID_ORIG} | tee -a ${LOGFILE}
            let COPYCOUNT+=1 #inc number of new files copied data from original
         fi
         EXITVAL=2
      fi
   fi

   if [[ $1 -eq -1 && $EXITVAL -ne 10 ]] ; then
      EXITVAL=0 #reset exitval so does next entry if req'd
      echo ---------- | tee -a ${LOGFILE}
   fi
   
done #### loop until all records updated if $1 = -1

echo IMDB Results: new_imdb=${ADDCOUNT}, stacked=${STACKCOUNT}, copied_imdb=${COPYCOUNT}, no_title=${BADCOUNT}, no_imdb=${NOIMDBCOUNT}, exitval=${EXITVAL} | tee -a ${LOGFILE}
echo ------------------------------------------ | tee -a ${LOGFILE}

exit $EXITVAL


Code:
#!/bin/bash
# Written by HappyTalk April 2006
# /usr/local/bin/getimdbrange.sh
# This will call getimdb repeatedly based on what you pass in
# Arg[1] = range type to do

if [[ $1 -eq 1 ]] ; then
# Arg[1] = 1 => get/set imdbnum for first item then set rest to same (unless its blank)
# Arg[2] = IMDBNUM or Title or blank to use title in database
# Arg[3] = text to locate in filename

   VIDEO_ID=0 #start id to search from change if req'd
   IDCNT=0
   IMDBNUM="$2"
#   while [[ ${VIDEO_ID} != "" && $IMDBNUM != "" ]] ; do
   while [[ ${VIDEO_ID} != "" ]] ; do
      VIDEO_ID=`mysql -u root -e "SELECT intid FROM mythconverg.videometadata WHERE filename LIKE '%${3}%' && intid > ${VIDEO_ID} LIMIT 0, 1;" -BN`
      if [[ ${VIDEO_ID} != "" ]] ; then
         #echo Set $VIDEO_ID to $IMDBNUM
         getimdb.sh $VIDEO_ID "$IMDBNUM"

         #if [[ $IDCNT == 0 ]] ; then #get IMDBNUM for first item to use for rest (unless blank in which case will exit)
         #   IMDBNUM=`mysql -u root -e "SELECT inetref FROM mythconverg.videometadata WHERE intid = ${VIDEO_ID};" -BN`
         #fi
         let IDCNT+=1
      fi   
   done
   echo GetIMDBRange: Set $((IDCNT -1)) IMDB IDs = $IMDBNUM
   
elif [[ $1 -eq 2 ]] ; then
# Arg[1] = 2
# Arg[2] = IMDBNUM or Title
# Arg[3] = start id
# Arg[4] = end id

   for (( i = $3 ; i <= $4 ; i++ ))
   do
      getimdb.sh $i "$2"
   done

   echo GetIMDBRange: Set IMDB ID $3 to $4 = $2 Finished | tee -a ${ECHO_OUT}
   echo ------------------------------------------ | tee -a ${ECHO_OUT}
else
   echo NO COMMAND TYPE SPECIFIED!!!
fi


Code:
#!/bin/bash
# Written by HappyTalk April 2006
# /usr/bin/local/playvideo.sh
# script to play any files. Uses xine for DVD/VCD & mplayer for others
# checks aspect setting in db (even if not used & dpi set correctly in XF86Config mplayer STILL needs to be told)
# args[1] cdrom => play dvd/vcd/enqueue&play videos from DVD drive
# args[1] filename.ifo => play the DVD from the folder containing filename.ifo
# TBA args[1] filename.iso => play the DVD from an iso (prolly just pass direct to xine)
# args[1] filename.dat => play the VCD from the folder containing filename.dat
# args[1] filename => play that video file from folder
# double // can be used in filename (path) to make videos appear in sub folder eg /myth/video/library/simpsons//simpsons.s1/simpsons.0x01.Bart dies.avi
# args[2] disknumber => Play file(s) off DVD. Check if file is on current inserted dvd, if not then eject drive & prompt

XSIZE=1024 #change these if you use diff
YSIZE=768
FNAMEALT=/myth/video/pc$1  #Where file will be mounted if dvd is inserted into Windows PC where my DVD is mounted to appear at /myth/video/pc/cdrom on this linux box
ALIGN=98 #Align positions in % of where to appear on screen 0=top,50=centre,100=bottom (overriden for TV)

MPLAY="/usr/bin/mplayer"
MPLAY_VID="-fs -zoom -vo xv -cache 16384"
MPLAY_AUD="-ao alsa:device=default -srate 48000"

XINE="/usr/bin/xine"
XINE_DVD="-pfhq -V xxmc --no-splash --post tvtime:method=Greedy2Frame,enable=1,chroma_filter=1,use_progressive_frames=yes --post unsharp:luma_amount=1.00 --post denoise3d:luma=4"
#XINE_VID="-pfhq -V xv  --no-splash"
XINE_VID="-pfhq -V xv   --no-splash --post tvtime:method=Greedy2Frame,enable=1,chroma_filter=1 --post unsharp --post denoise3d"
#XINE_VID="-pfhq -V xv   --no-splash --post tvtime:method=Greedy2Frame,enable=1,pulldown=vektor,framerate_mode=full,judder_correction=yes,use_progressive_frames=yes --post denoise3d --post unsharp:luma_amount=0.5"
XINE_CONFIG="/home/mythtv/.xine/config"

#--------------------------------------------------------------------

#calcs fake screen height needed for movie alignment (as mplayer has no better way of doing this)
function YOffset() {
   NEWY=0
   if [[ ${ALIGN} -ne  50 ]] ; then #only align on 4:3 Projector NOT 16:9 TV
      VIDINFO=$($MPLAY -identify -frames 0 -vo null -ao null "$1" 2>/dev/null)

      # Extract ID_VIDEO_WIDTH
      VIDEO_WIDTH=${VIDINFO##*ID_VIDEO_WIDTH=}
      VIDEO_WIDTH=${VIDEO_WIDTH%%?ID_VIDEO_HEIGHT*}

      # Extract ID_VIDEO_HEIGHT
      VIDEO_HEIGHT=${VIDINFO##*ID_VIDEO_HEIGHT=}
      VIDEO_HEIGHT=${VIDEO_HEIGHT%%?ID_VIDEO_FPS*}

      # Extract ID_VIDEO_ASPECT
      VIDEO_ASPECT=${VIDINFO##*ID_VIDEO_ASPECT=}
      VIDEO_ASPECT=${VIDEO_ASPECT%%?ID_AUDIO_CODEC*}
      if [ ${VIDEO_ASPECT:0:1} -eq 0 ] ; then #make any aspect ratios < 1 = 1
         if [ ${VIDEO_WIDTH} -eq 0 ] || [ ${VIDEO_HEIGHT} -eq 0 ] ; then
            VIDEO_ASPECT=1.3333
         else
            VIDEO_ASPECT=$(echo "scale=4; $VIDEO_WIDTH / $VIDEO_HEIGHT" | bc)
         fi
      fi
      
      if [[ ${ALIGN} -le 50 ]] ; then    
         NEWY=$(echo "scale=0; ${XSIZE}  / ${VIDEO_ASPECT} " | bc)
      else
         NEWY=$(echo "scale=0; 2 * ${YSIZE} - (${XSIZE}  / ${VIDEO_ASPECT}) - 25 " | bc) #-25 => 12 pixels (25/2) above bottom edge
         if [ ${NEWY} -le ${YSIZE} ] ; then
            NEWY=0
         fi
      fi
      
      echo ALIGN_CALC=VIDEO_WIDTH=${VIDEO_WIDTH}, VIDEO_HEIGHT=${VIDEO_HEIGHT}, VIDEO_ASPECT=${VIDEO_ASPECT} NEWYSIZE=${NEWY} >> ${ECHO_OUT}
      eval "$2=$NEWY"
   fi   
}

#--------------------------------------------------------------------

FNAME=$1
DVDNUM=$2
ERRFLAG=0
ECHO_OUT="/myth/tmp/playvideolog.txt"

echo  >> ${ECHO_OUT} #blank line

if [ -n "$DVDNUM" ] ; then #dvd
   if [[ $FNAME != dvdrom ]] ; then
   
      if [ -e "$FNAMEALT" ] ; then #is file on pc dvd-rom
         FNAME=$FNAMEALT
      else
         mount /cdrom # mount current cd in case already in there

         if [ ! -e "$FNAME" ] ; then #file doesnt exist so prompt for dvd
            sudo /usr/bin/eject /dev/scd0 #eject dvd drive
            #echo "Please insert dvd $DVDNUM:"
            xterm -xrm "xterm*allowSendEvents: true" -bg NavyBlue -fg White +sb -fs 60 -fa 'Arial Bold' -fs 32 -geometry 26x5+200+200 -e prompt.sh "  Please Insert DVD ${DVDNUM}" "  Then Press Play"
            mount /cdrom
            
            if [ -e "$FNAMEALT" ] ; then #is file on pc dvd-rom
               FNAME=$FNAMEALT
            elif [ ! -e "$FNAME" ] ; then #file STILL doesn't exist so prompt error
               ERRFLAG=1
               #echo "Error Unable to locate file $FNAME on dvd $DVDNUM" #>> ${ECHO_OUT}
               xterm -bg NavyBlue -fg White +sb -fa 'Arial Bold' -fs 32 -geometry 26x5+200+200 -e prompt.sh "  Error File Not Found" "  Please Try Again" 2 #dont want this xterm to receive events as is timed
            fi
         fi   
      fi
   else    
      sudo /usr/bin/eject /dev/scd0 #eject dvd drive
      xterm -xrm "xterm*allowSendEvents: true" -bg NavyBlue -fg White +sb -fs 60 -fa 'Arial Bold' -fs 48 -geometry 26x5+200+200 -e prompt.sh "  Please Insert DVD ${DVDNUM}" "  Then Press Play"
      mount /cdrom
   fi
elif [[ $FNAME == dvdrom ]] ; then
   mount /cdrom
fi

echo $NOERR

FNAMELC=$(echo $FNAME | tr "[:upper:]" "[:lower:]")

if [ $ERRFLAG -eq 0 ] ; then

# Get aspect ratio
   ASPECT=`mysql -u root -e 'USE mythconverg; SELECT data FROM settings WHERE value = "TVVidModeForceAspect" and hostname = "mythtv";' -BN`
   ASPECT=${ASPECT:0:6}

#setup video alignment
   if [[ ${ASPECT} == "1.7777" ]] ; then #centre alignment if on TV
      ALIGN=50 #override
      AC3=0
   else
      AC3=1 #only do ac3 on projector
   fi
   sed "s/.*video.output.vertical_position:.*/video.output.vertical_position:${ALIGN}/g" ${XINE_CONFIG} > ${XINE_CONFIG}.tmp && mv -f ${XINE_CONFIG}.tmp ${XINE_CONFIG}

# Setup for ac3 on/off
   #use this to set ac3 based on myth setting, else is on for proj off for TV.
   #AC3=$(mysql -u root -e 'USE mythconverg; SELECT data FROM settings WHERE value = "AC3PassThru" and hostname = "mythtv";' -BN)
   if [ $AC3 -eq 0 ] ; then
      sed "s/audio.output.speaker_arrangement:.*/#audio.output.speaker_arrangement:Stereo 2.0/g" ${XINE_CONFIG} > ${XINE_CONFIG}.tmp && mv -f ${XINE_CONFIG}.tmp ${XINE_CONFIG}
   else
      sed "s/#audio.output.speaker_arrangement:.*/audio.output.speaker_arrangement:Pass Through/g" ${XINE_CONFIG} > ${XINE_CONFIG}.tmp && mv -f ${XINE_CONFIG}.tmp ${XINE_CONFIG}
      MPLAY_AUD="${MPLAY_AUD} -ac hwac3,"
   fi

   
# play video file
   if [[ $FNAMELC == dvdrom ]] ; then
      if [ -e "/cdrom/VIDEO_TS/VIDEO_TS.IFO" ] ; then
         # disabled xine calcs as can just use video.output.vertical_position:100 in /home/mythtv/.xine/config
         #YOffset "dvd://1" NEWYSIZE
         #if [ ${NEWYSIZE} -gt 0 ] ; then
         #   XINE_DVD_FILT="-phq -B --geometry ${XSIZE}x${NEWYSIZE} --post tvtime:method=Greedy2Frame,enable=1,chroma_filter=1,use_progressive_frames=yes --post unsharp:luma_amount=1.00 --post denoise3d:luma=4"      
         #fi   
         DVDCMD=($XINE $XINE_DVD --auto-scan dvd)
      elif [ -e "/cdrom/mpegav/avseq01.dat" ] ; then
         DVDCMD=($XINE $XINE_DVD --auto-scan vcd) #vcd://
      else
#         DVDCMD=($MPLAY -monitoraspect $ASPECT $MPLAY_AUD $MPLAY_VID /cdrom/*)
         DVDCMD=($XINE $XINE_VID /cdrom/*)
      fi
   else
      if [[ $FNAMELC == *.ifo ]] ; then
         DVDCMD=($XINE $XINE_DVD "${FNAME%/*}")
      elif [[ $FNAMELC == *.dat ]] ; then
         DVDCMD=($XINE $XINE_DVD "${FNAME%/*}")
      elif [[ $FNAMELC == *.iso ]] ; then
         DVDCMD=($XINE $XINE_DVD "dvd:$FNAME")
      elif [[ $FNAMELC == *.vcd ]] ; then
         DVDCMD=($XINE $XINE_DVD "vcd:$FNAME")
      else
#         YOffset "$FNAME" NEWYSIZE
#         if [ ${NEWYSIZE} -gt 0 ] ; then
#            MPLAY_VID="$MPLAY_VID -screenh ${NEWYSIZE}"
#            ASPECT=$(echo "scale=4; ${XSIZE} / ${NEWYSIZE}" | bc)
#         fi   
#         DVDCMD=($MPLAY -monitoraspect $ASPECT $MPLAY_AUD $MPLAY_VID "$FNAME")
         DVDCMD=($XINE $XINE_VID "$FNAME")
      fi
   fi   

   echo fname=\"$FNAME\", diskid=$2, aspect=$ASPECT, ac3=$AC3, align=$ALIGN >> ${ECHO_OUT}
   echo "${DVDCMD[@]}" >> ${ECHO_OUT}
   "${DVDCMD[@]}"
   echo "---------------ok" #>> ${ECHO_OUT}
else
   echo "---------------error" #>> ${ECHO_OUT}
fi

if [[ $1 == dvdrom ]] ; then
   sudo /usr/bin/eject /dev/scd0  #add /usr/bin/eject to sudo file. need to be root else cd may get stuck
fi



Code:
#!/bin/bash
# Written by HappyTalk April 2006
# /usr/local/bin/prompt_dvdnum.sh
# get 4 digit id number from user

DVDNUMFILE="/home/mythtv/.DVDINFO"

if [ ! -e "$DVDNUMFILE" ] ; then
   #echo Initialise DVD Number
   DVDINFO=940001
   echo ${DVDINFO} > $DVDNUMFILE # and save it
else 
   DVDINFO=$(< ${DVDNUMFILE}) #read DVDNUM < ${DVDNUMFILE}
fi

CAT=${DVDINFO:1:1}
DVDNUM=${DVDINFO:2:4}

# DVDNUM=$(printf %04d $DVDNUM) # add leading zeros
echo "Cat:$CAT - Insert DVD: $DVDNUM"
echo "Or enter new cat/dvdnum"
echo
read DVDINFO

if [[ ${DVDINFO} != "" ]] ; then
   if [ ${#DVDINFO} -gt 1 ] ; then #if only 1 digit just alter cat
      DVDNUM=${DVDINFO:1:4}
   fi   
   CAT=${DVDINFO:0:1}
   
   echo 9${CAT}${DVDNUM} > $DVDNUMFILE # and save it
fi


Code:
#!/bin/bash
# Written by HappyTalk April 2006
# /usr/local/bin/prompt.sh
echo
echo "$1"
echo
if [ -n "$3" ] ; then
   echo "$2"
   sleep $3
else
   read -n 1 -p "$2"
fi



I also changed some of the xml files thus:

/usr/share/mythtv/util_menu.xml
chnaged to add add-dvd option to easily add disks from standard setup menu
Code:
<mythmenu name="UTIL">

   <button>
     <type>SETUP_MENU</type>
     <text>Setup</text>
     <action>MENU main_settings.xml</action>
   </button>

   <button>
      <type>SETUP_KEYS</type>
      <text>Edit Keys</text>
      <action>PLUGIN mythcontrols</action>
      <depends>mythcontrols</depends>   
   </button>

   <button>
     <type>VIDEO_MANAGER</type>
     <text>Add DVD</text>
     <action>EXEC /usr/local/bin/add_dvd.sh</action>
     <depends>mythvideo</depends>
   </button>

   <button>
     <type>VIDEO_MANAGER</type>
     <text>Video Manager</text>
<!--     <action>JUMP Video Manager</action>  -->
     <depends>mythvideo</depends>
   </button>

   <button>
      <type>MUSIC_PLAYLIST</type>
      <text>Music Tools</text>
      <action>PLUGIN mythmusic</action>
      <depends>mythmusic</depends>   
   </button>

</mythmenu>


/usr/share/mythtv/optical_menu.xml
Code:
<mythmenu name="OPTICAL_DISK">

   <button>
      <type>DVD_PLAY</type>
      <text>Play DVD</text>
      <action>JUMP Play DVD</action>
      <depends>mythdvd</depends>
   </button>

   <button>
      <type>DVD</type>
      <text>Eject DVD</text>
      <action>EXEC sudo /usr/bin/eject /dev/sr0</action>
   </button>

   <button>
      <type>VCD_PLAY</type>
      <text>Play VCD</text>
      <action>JUMP Play VCD</action>
      <depends>mythdvd</depends>
   </button>

   <button>
      <type>DVD_RIP</type>
      <text>Import DVD</text>
      <action>JUMP Rip DVD</action>
      <depends>mythdvd</depends>
   </button>

   <button>
      <type>MUSIC_RIP</type>
      <text>Import CD</text>
      <action>JUMP Rip CD</action>
      <depends>mythmusic</depends>
   </button>

</mythmenu>


Lastly run this database script in webmin or other to add some default entries to database that I use (you dont have to do this). They wipe previous entries in the same table so back up your database first before doing any of this.

This sets up the categories mentioned earlier. These are the basic ones I use so they act as a main root for the different types of video, that first number in the add_dvd prompt corresponds to these.
Code:
DROP TABLE IF EXISTS `videocategory`;
CREATE TABLE `videocategory` (
  `intid` int(10) unsigned NOT NULL auto_increment,
  `category` varchar(128) NOT NULL default '',
  PRIMARY KEY  (`intid`)
) TYPE=MyISAM;

--
-- Dumping data for table `videocategory`
--

INSERT INTO `videocategory` VALUES (1,'Comedy');
INSERT INTO `videocategory` VALUES (2,'Documentary');
INSERT INTO `videocategory` VALUES (3,'Drama');
INSERT INTO `videocategory` VALUES (4,'Movie');
INSERT INTO `videocategory` VALUES (5,'Music');
INSERT INTO `videocategory` VALUES (6,'SciFi');
INSERT INTO `videocategory` VALUES (7,'Karaoke');


This sets up the file types that will be searched for. The script reads these in and ONLY searches for these video types on disks, so if you have others you may need to add them. Regular DVD Videos's are always found
Code:
DROP TABLE IF EXISTS `videotypes`;
CREATE TABLE `videotypes` (
  `intid` int(10) unsigned NOT NULL auto_increment,
  `extension` varchar(128) NOT NULL default '',
  `playcommand` varchar(255) NOT NULL default '',
  `f_ignore` tinyint(1) default NULL,
  `use_default` tinyint(1) default NULL,
  PRIMARY KEY  (`intid`)
) TYPE=MyISAM;

--
-- Dumping data for table `videotypes`
--

INSERT INTO `videotypes` VALUES (1,'mpg','',0,1);
INSERT INTO `videotypes` VALUES (2,'avi','',0,1);
INSERT INTO `videotypes` VALUES (3,'wmv','',0,1);
INSERT INTO `videotypes` VALUES (4,'mov','',0,1);
INSERT INTO `videotypes` VALUES (5,'rm','',0,1);
INSERT INTO `videotypes` VALUES (6,'asf','',0,1);
INSERT INTO `videotypes` VALUES (7,'mp4','',0,1);
INSERT INTO `videotypes` VALUES (8,'mpeg','',0,1);
INSERT INTO `videotypes` VALUES (9,'ogm','',0,1);
INSERT INTO `videotypes` VALUES (10,'iso','',0,1);


Last edited by HappyTalk on Wed Jul 19, 2006 2:27 am, edited 1 time in total.


Top
 Profile  
 
 Post subject:
PostPosted: Tue Jul 18, 2006 5:05 am 
Offline
Joined: Sat Jan 28, 2006 11:29 am
Posts: 83
CONTINUED... (these are not required, just added for completeness to show what I did)

Here's some sample database entries from the start of my database. Obviously they won't actually play as you don't have the disk and the cover entries don't exist (regrab em with getimdb script if you like) but they act as an example. NOTE I also modified the imdb.pl script to use actors and other stuff in place of countries, so one of the fields is larger. so backup db first as mentioned
Code:
DROP TABLE IF EXISTS `videometadata`;
CREATE TABLE `videometadata` (
  `intid` int(10) unsigned NOT NULL auto_increment,
  `title` varchar(128) NOT NULL default '',
  `director` varchar(128) NOT NULL default '',
  `plot` text,
  `rating` varchar(255) NOT NULL default '',
  `inetref` varchar(32) NOT NULL default '',
  `year` int(10) unsigned NOT NULL default '0',
  `userrating` float NOT NULL default '0',
  `length` int(10) unsigned NOT NULL default '0',
  `showlevel` int(10) unsigned NOT NULL default '0',
  `filename` text NOT NULL,
  `coverfile` text NOT NULL,
  `childid` int(11) NOT NULL default '-1',
  `browse` tinyint(1) NOT NULL default '1',
  `playcommand` varchar(255) default NULL,
  `category` int(10) unsigned NOT NULL default '0',
  PRIMARY KEY  (`intid`),
  KEY `director` (`director`),
  KEY `title` (`title`),
  KEY `title_2` (`title`)
) TYPE=MyISAM;

--
-- Dumping data for table `videometadata`
--

INSERT INTO `videometadata` VALUES (1,'Twelve Monkeys','Terry Gilliam','A convict, sent back in time to stop a devastating plague, is sent too far back and is hospitalized as insane.  (USA)','Joseph Melito,Bruce Willis,Jon Seda,Michael Chance,Vernon Campbell,H. Michael Walls,Bob Adrian,Simon Jones,Carol Florence,Bill Raymond,Ernest Abuba,Irma St. Paule,Madeleine Stowe,Joey Perillo,Bruce Kirkpatrick','0114746',1995,8,129,1,'/myth/video/library/Movie/12 Monkeys (1995).avi','/myth/video/.covers/0114746.jpg',-1,1,'playvideo.sh \"/cdrom/12 Monkeys (1995).avi\" 0001',4);
INSERT INTO `videometadata` VALUES (2,'Thir13en Ghosts','Steve Beck','When Cyrus Kriticos, a very rich collector of unique things dies, he leaves it all to his nephew and his family. All including his house, his fortune, and his malicious collection of ghosts!  (USA,Canada)','Tony Shalhoub,Embeth Davidtz,Matthew Lillard,Shannon Elizabeth,Alec Roberts,JR Bourne,Rah Digga,F. Murray Abraham,Matthew Harrison,Jacob Rupp,Mike Crestejo,Aubrey Culp,Charles Andre,Mikhael Speidel,Daniel Wesley','0245674',2001,5,91,1,'/myth/video/library/Movie/13 Ghosts (2001).avi','/myth/video/.covers/0245674.jpg',-1,1,'playvideo.sh \"/cdrom/13 Ghosts (2001).avi\" 0001',4);
INSERT INTO `videometadata` VALUES (3,'2001: A Space Odyssey','Stanley Kubrick','Mankind finds a mysterious, obviously artificial, artifact buried on the moon and, with the intelligent computer HAL, sets off on a quest.  (UK,USA)','Keir Dullea,Gary Lockwood,William Sylvester,Daniel Richter,Leonard Rossiter,Margaret Tyzack,Robert Beatty,Sean Sullivan,Douglas Rain,Frank Miller,Bill Weston,Ed Bishop,Glenn Beck,Alan Gifford,Ann Gillis','0062622',1968,8.3,0,1,'/myth/video/library/Movie/2001 - A Space Odyssey (1968).avi','/myth/video/.covers/0062622.jpg',-1,1,'playvideo.sh \"/cdrom/2001 - A Space Odyssey (1968).avi\" 0001',4);
INSERT INTO `videometadata` VALUES (4,'51st State','Ronny Yu','An American master chemist plans to score big on a once in a lifetime drug deal. All does not go as planned and he is soon entangled in a web of deceit.  (UK,Canada)','Samuel L. Jackson,Nigel Whitmey,Robert Jezek,Emily Mortimer,Meat Loaf,Jake Abraham,Mac McDonald,Aaron Swartz,David Webber,Michael J. Reynolds,Sonny Muslim,Barbara Barnes,Junix Nocian,Robert Carlyle,Paul Barber','0227984',2001,6.1,92,1,'/myth/video/library/Movie/51St State (2001).avi','/myth/video/.covers/0227984.jpg',-1,1,'playvideo.sh \"/cdrom/51St State (2001).avi\" 0001',4);
INSERT INTO `videometadata` VALUES (5,'A Clockwork Orange','Stanley Kubrick','In a futuristic Britain, a gang of teenagers go on the rampage every night, beating and raping helpless victims...\n  (UK)','Malcolm McDowell,Patrick Magee,Michael Bates,Warren Clarke,John Clive,Adrienne Corri,Carl Duering,Paul Farrell,Clive Francis,Michael Gover,Miriam Karlin,James Marcus,Aubrey Morris,Godfrey Quigley,Sheila Raynor','0066921',1971,8.4,136,1,'/myth/video/library/Movie/A Clockwork Orange (1971).avi','/myth/video/.covers/0066921.jpg',-1,1,'playvideo.sh \"/cdrom/A Clockwork Orange (1971).avi\" 0001',4);
INSERT INTO `videometadata` VALUES (6,'About a Boy','Chris Weitz','Based on Nick Hornby\'s best-selling novel, About A Boy is the story of a cynical, immature young man who is taught how to act like a grown-up by a little boy  (UK,USA,France,Germany)','Hugh Grant,Nicholas Hoult,Toni Collette,Rachel Weisz,Sharon Small,Madison Cook,Jordan Cook,Nicholas Hutchison,Ryan Speechley,Joseph Speechley,Natalia Tena,Laura Kennington,Tanika Swaby,Peter McNicholl,Christopher Webster','0276751',2002,7.5,101,1,'/myth/video/library/Movie/About A Boy (2002).avi','/myth/video/.covers/0276751.jpg',-1,1,'playvideo.sh \"/cdrom/About A Boy (2002).avi\" 0001',4);
INSERT INTO `videometadata` VALUES (7,'Ali','Michael Mann','A biography of sports legend, Muhammad Ali, from his early days to his days in the ring.  (USA)','Will Smith,Jamie Foxx,Jon Voight,Mario Van Peebles,Ron Silver,Jeffrey Wright,Mykelti Williamson,Jada Pinkett Smith,Nona Gaye,Michael Michele,Joe Morton,Bruce McGill,Paul Rodriguez,Barry Shabaka Henley,Giancarlo Esposito','0248667',2001,6.3,159,1,'/myth/video/library/Movie/Ali (2001)-CD1.avi','/myth/video/.covers/0248667.jpg',8,1,'playvideo.sh \"/cdrom/Ali (2001)-CD1.avi\" 0002',4);
INSERT INTO `videometadata` VALUES (8,'Ali','Michael Mann','A biography of sports legend, Muhammad Ali, from his early days to his days in the ring.  (USA)','Will Smith,Jamie Foxx,Jon Voight,Mario Van Peebles,Ron Silver,Jeffrey Wright,Mykelti Williamson,Jada Pinkett Smith,Nona Gaye,Michael Michele,Joe Morton,Bruce McGill,Paul Rodriguez,Barry Shabaka Henley,Giancarlo Esposito','0248667',2001,6.3,159,1,'/myth/video/library/Movie/Ali (2001)-CD2.avi','/myth/video/.covers/0248667.jpg',-1,0,'playvideo.sh \"/cdrom/Ali (2001)-CD2.avi\" 0002',4);


I very slightly modified imdb.pl, the script that grabs the imdb info changes are marked with a xxxx. This makes it use countries field for first 4 actors instead and a few other changes I deemed necessary
Code:
#!/usr/bin/perl -w
# /usr/share/mythtv/mythvideo/scripts/imdb.pl
#
# This perl script is intended to perform movie data lookups based on
# the popular www.imdb.com website
#
# For more information on MythVideo's external movie lookup mechanism, see
# the README file in this directory.
#
# Author: Tim Harvey (tharvey AT alumni.calpoly DOT edu)
# Modified: Andrei Rjeousski
# v1.1
# - Added amazon.com covers and improved handling for imdb posters
# v1.2
#     - when searching amazon, try searching for main movie name and if nothing is found, search for informal name
#     - better handling for amazon posters, see if movie title is a substring in the search results returned by amazon
#     - fixed redirects for some movies on impawards

use LWP::Simple;      # libwww-perl providing simple HTML get actions
use HTML::Entities;
use URI::Escape;
use XML::Simple;


use vars qw($opt_h $opt_r $opt_d $opt_i $opt_v $opt_D $opt_M $opt_P);
use Getopt::Std;

$title = "IMDB Query";
$version = "v1.2";
$author = "Tim Harvey, Andrei Rjeousski";

# display usage
sub usage {
   print "usage: $0 -hdrviMPD [parameters]\n";
   print "       -h           help\n";
   print "       -d           debug\n";
   print "       -r           dump raw query result data only\n";
   print "       -v           display version\n";
   print "       -i           display info\n";
   print "\n";
   print "       -M [options] <query>    get movie list\n";
   print "               some known options are:\n";
   print "                  type=[fuzy]         looser search\n";
   print "                  from_year=[int]     limit matches to year\n";
   print "                  to_year=[int]       limit matches to year\n";
   print "                  sort=[smart]        ??\n";
   print "                  tv=[no|both|only]   limits between tv and movies\n";
   print "               Note: multiple options must be separated by ';'\n";
   print "       -P <movieid>  get movie poster\n";
   print "       -D <movieid>  get movie data\n";
   exit(-1);
}

# display 1-line of info that describes the version of the program
sub version {
   print "$title ($version) by $author\n"
}

# display 1-line of info that can describe the type of query used
sub info {
   print "Performs queries using the www.imdb.com website.\n";
}

# display detailed help
sub help {
   version();
   info();
   usage();
}

# returns text within 'data' between 'beg' and 'end' matching strings
sub parseBetween {
   my ($data, $beg, $end)=@_; # grab parameters

   my $ldata = lc($data);
   my $start = index($ldata, lc($beg)) + length($beg);
   my $finish = index($ldata, lc($end), $start);
   if ($start != (length($beg) -1) && $finish != -1) {
      my $result = substr($data, $start, $finish - $start);
      # return w/ decoded numeric character references
      # (see http://www.w3.org/TR/html4/charset.html#h-5.3.1)
      decode_entities($result);
      return $result;
   }
   return "";
}

# get Movie Data
sub getMovieData {
   my ($movieid)=@_; # grab movieid parameter
   if (defined $opt_d) { printf("# looking for movie id: '%s'\n", $movieid);}

   # get the search results  page
   my $request = "http://www.imdb.com/title/tt" . $movieid . "/";
   if (defined $opt_d) { printf("# request: '%s'\n", $request); }
   my $response = get $request;
   if (defined $opt_r) { printf("%s", $response); }

   # parse title and year
   my $title = parseBetween($response, "<title>", "</title>");
   $title =~ m#(.+) \((\d+).*\)#;  # Note some years have a /II after them?
   $title = $1;
   my $year = $2;

   # parse director
   my $director = parseBetween($response, ">Directed by</b>", "/a><br>");
   $director = parseBetween($director, "/\">", "<");

   # parse writer
   # (Note: this takes the 'first' writer, may want to include others)
   my $writer = parseBetween($response, ">Writing credits</b>", "</table>");
   $writer = parseBetween($writer, "/\">", "</");

   # parse plot
   my $plot = parseBetween($response, ">Plot Outline:</b> ", "<a href=\"");
   if (!$plot) {
      $plot = parseBetween($response, ">Plot Summary:</b> ", "<a href=\"");
   }

   # parse user rating
   my $userrating = parseBetween($response, ">User Rating:</b>", "> (");
   $userrating = parseBetween($userrating, "<b>", "/");

   # parse MPAA rating
   my $ratingcountry = "USA";
   my $movierating = parseBetween($response, ">MPAA</a>:</b> ", "<br>");
   if (!$movierating) {
       $movierating = parseBetween($response, ">Certification:</b>", "<br>");
       $movierating = parseBetween($movierating, "certificates=$ratingcountry",
                                   "/a>");
       $movierating = parseBetween($movierating, ">", "<");
   }

   # parse movie length
   my $runtime = parseBetween($response, ">Runtime:</b>\n", " min");

   # parse cast
   #  Note: full cast would be from url:
   #    www.imdb.com/title/<movieid>/fullcredits
   my @actors;
   my $cast = "";
   my $cast4 = ""; #xxx new var to hold just 1st four actors
   my $count = 0;
   my $data = parseBetween($response, "Cast overview, first billed only:",
                               "/table>");
   if ($data) {
      my $beg = "/\">";
      my $end = "</a>";
      my $start = index($data, $beg);
      my $finish = index($data, $end, $start);
      my $actor;
      while ($start != -1) {
         $start += length($beg);
         $actor = substr($data, $start, $finish - $start);
         # add to array
         $actors[$count++] = $actor;

         # advance data to next movie
         $data = substr($data, - (length($data) - $finish));
         $start = index($data, $beg);
         $finish = index($data, $end, $start + 1);
      }
      $cast = join(',', @actors);
      $cast4 = join(',', @actors[0..3]); #xxx add up to first 4 actors to cast4 (change the 3 if you want more)
   }
   
   
   # parse genres
   my @genres;
   my $lgenres = "";
      $count = 0;
   $data = parseBetween($response, "<b class=\"ch\">Genre:</b>","<a href=\"/rg/title-tease/keywords/title/tt$movieid/keywords\">(more)</a>");
   if ($data) {
      my $beg = "/\">";
      my $end = "</a>";
      my $start = index($data, $beg);
      my $finish = index($data, $end, $start);
      my $genre;
      while ($start != -1) {
         $start += length($beg);
         $genre = substr($data, $start, $finish - $start);
         # add to array
         $genres[$count++] = $genre;

         # advance data to next movie
         $data = substr($data, - (length($data) - $finish));
         $start = index($data, $beg);
         $finish = index($data, $end, $start + 1);
      }
      $lgenres = join(',', @genres);
   }
   
   # parse countries
   my @countries;
   my $lcountries = "";
   $count = 0;
   $data = parseBetween($response, "<b class=\"ch\">Country:</b>","<br>");
   if ($data) {
      my $beg = "/\">";
      my $end = "</a>";
      my $start = index($data, $beg);
      my $finish = index($data, $end, $start);
      my $country;
      while ($start != -1) {
         $start += length($beg);
         $country = substr($data, $start, $finish - $start);
         # add to array
         $countries[$count++] = $country;

         # advance data to next movie
         $data = substr($data, - (length($data) - $finish));
         $start = index($data, $beg);
         $finish = index($data, $end, $start + 1);
      }
      $lcountries = join(',', @countries);
   }

   # output fields (these field names must match what MythVideo is looking for)
   print "Title:$title\n";
   print "Year:$year\n";
   print "Director:$director\n";
   print "Plot:$plot ($lcountries)\n"; #xxx print "Plot:$plot\n";
   print "UserRating:$userrating\n";
   print "MovieRating:$cast\n"; #xxx print "MovieRating:$movierating\n";
   print "Runtime:$runtime\n";
   print "Writers: $writer\n";
   print "Cast: $cast\n";
   print "Genres: $lgenres\n";
   print "Countries: $cast4\n"; #xxx print "Countries: $lcountries\n";
}

# dump Movie Poster
sub getMoviePoster {
   my ($movieid)=@_; # grab movieid parameter
   if (defined $opt_d) { printf("# looking for movie id: '%s'\n", $movieid);}

   # get the search results  page
   my $request = "http://www.imdb.com/title/tt" . $movieid . "/posters";
   if (defined $opt_d) { printf("# request: '%s'\n", $request); }
   my $response = get $request;
   if (defined $opt_r) { printf("%s", $response); }

   my $uri = "";

   # look for references to impawards.com posters - they are high quality
   my $site = "http://www.impawards.com";
   my $impsite = parseBetween($response, "<a href=\"".$site, "\">".$site);

   # jersey girl fix
   $impsite = parseBetween($response, "<a href=\"http://impawards.com","\">http://impawards.com") if ($impsite eq "");

   if ($impsite) {
      $impsite = $site . $impsite;

      if (defined $opt_d) { print "# Searching for poster at: ".$impsite."\n"; }
      my $impres = get $impsite;
      if (defined $opt_d) { printf("# got %i bytes\n", length($impres)); }
      if (defined $opt_r) { printf("%s", $impres); }     

   # making sure it isnt redirect
   $uri = parseBetween($impres, "0;URL=..", "\">");
   if ($uri ne "") {
      if (defined $opt_d) { printf("# processing redirect to %s\n",$uri); }
      # this was redirect
                $impsite = $site . $uri;
                $impres = get $impsite;
   }

     
      # do stuff normally   
      $uri = parseBetween($impres, "<img SRC=\"posters/", "\" ALT");
      # uri here is relative... patch it up to make a valid uri
      if (!($uri =~ /http:(.*)/ )) {
         my $path = substr($impsite, 0, rindex($impsite, '/') + 1);
         $uri = $path."posters/".$uri;
      }
      if (defined $opt_d) { print "# found ipmawards poster: $uri\n"; }
   }

   # if the impawards site attempt didn't give a filename grab it from imdb
   if ($uri eq "") {
       if (defined $opt_d) { print "# looking for imdb posters\n"; }
       my $host = "http://posters.imdb.com/posters/";

       $uri = parseBetween($response, $host, "\"><td><td><a href=\"");
       if ($uri ne "") {
           $uri = $host.$uri;
       } else {
          if (defined $opt_d) { print "# no poster found\n"; }
       }
   }
   
   # now we couldnt even find lowres poster from IMDB, lets try looking for dvd
   # cover on amazon.com   

   my @movie_titles;
   my $found_low_res = 0;
   my $k = 0;
   
   # no poster found, take lowres image from imdb
   if ($uri eq "") {
       if (defined $opt_d) { print "# looking for lowres imdb posters\n"; }
       my $host = "http://www.imdb.com/title/tt" . $movieid . "/";
       $response = get $host;

       $uri = parseBetween($response, "alt=\"cover\" src=\"http://ia.imdb.com/media/imdb/", "\"");
       
      if (defined $opt_d) { print "# starting to look for movie title\n"; }
     
      # get main title
      if (defined $opt_d) { print "# Getting possible movie titles:\n"; }
      $movie_titles[$k++] = parseBetween($response, "<title>", "<\/title>");
      if (defined $opt_d) { print "# Title: ".$movie_titles[$k-1]."\n"; }

      # now we get all other possible movie titles and store them in the titles array
      while($response =~ m/>([^>^\(]*)([ ]{0,1}\([^\)]*\)[^\(^\)]*[ ]{0,1}){0,1}\(informal title\)/g) {
         $movie_titles[$k++] = $1;
         chomp($movie_titles[$k-1]);
         $movie_titles[$k-1] =~ s/^\s+//;
         $movie_titles[$k-1] =~ s/\s+$//;
         if (defined $opt_d) { print "# Title: ".$movie_titles[$k-1]."\n"; }
      }
       
       if ($uri ne "" ) {
           $uri = "http://ia.imdb.com/media/imdb/".$uri;
           $found_low_res = 1;
       } else {
          if (defined $opt_d) { print "# no poster found\n"; }
       }
   }
   
   # now we couldnt even find lowres poster from IMDB, lets try looking for dvd
   # cover on amazon.com
   if ($uri eq "" or $found_low_res) {
      if (defined $opt_d) { print "# starting to look for poster on Amazon.com\n"; }

      my $titleid = 0;
      my $found = 0;
      my $ama_uri = "";
      my $xml_parser = XML::Simple->new();
     
         
      do {
         # get rid of the year
         $movie_titles[$titleid] =~ s/ ?\([^\)]+\) ?//g;
         $movie_titles[$titleid] =~ /(.*), The$/i;
         if ($1) { $movie_titles[$titleid] = $1; }

         $movie_titles[$titleid] =~ s/[\"\']//g; # if we give amazon quotes they give them back
     
         if (defined $opt_d) { print "# Searching for: $movie_titles[$titleid]\n"; }

         # Encode the movie title to be save
         my $safe_movie_title = $movie_titles[$titleid];
         $safe_movie_title =~ s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;     
         # request XML info from amazon
         my $xml_uri = "http://xml.amazon.com/onca/xml3?t=000&dev-t=000&KeywordSearch=".$safe_movie_title."&mode=dvd&type=lite&page=1&f=xml";
         if (defined $opt_d) { print "# Amazon request string is: $xml_uri\n";}

         # get the response
         $response = get $xml_uri;
         if (defined $opt_r) { printf("%s", $response); }
     
         # parse the response
         my $xml_doc = $xml_parser->XMLin($response);

         # if we only got one result, fake it as array
         if (ref($xml_doc->{Details}) ne 'ARRAY') {
            my @tmpArray = ($xml_doc->{Details});
            $xml_doc->{Details} = \@tmpArray;
         }

         $k = 0;
         do {
            if (ref($xml_doc->{Details}->[$k]) eq 'HASH') {
               my $tmp_movie_title = $xml_doc->{Details}->[$k]->{ProductName};
               $tmp_movie_title =~ s/[\"\']//g;
               if (defined $opt_d) { print "# Amazon: comparing (" . $tmp_movie_title . ") to (" . $movie_titles[$titleid] . ")\n"; }
               if ($tmp_movie_title =~ /.*$movie_titles[$titleid].*/) {
                  if (defined $opt_d) { print "# Amazon: found poster " . $xml_doc->{Details}->[$k]->{ImageUrlLarge} . "\n"; }
                  $ama_uri = $xml_doc->{Details}->[$k]->{ImageUrlLarge};
                  $found = 1;
               }
            }

           $k++;
        } until ($found || $k == 5);
        #only search through first 5 matches

         $titleid++;
      } until ($found || $titleid > $#movie_titles);
     
      my $image = get $ama_uri if (defined($ama_uri) && $ama_uri ne "");
      if ($ama_uri ne "" && length($image) eq "807") {
         if (defined $opt_d) { printf("# this image is blank\n"); }
         $ama_uri = "";
      }
     
      if (!defined($ama_uri)) {
         $ama_uri = "";
      }
   
      if ($ama_uri ne "") {
   $uri = $ama_uri;
      }
   }

   print "$uri\n";
}

# dump Movie list:  1 entry per line, each line as 'movieid:Movie Title'
sub getMovieList {
   my ($filename, $options)=@_; # grab parameters

   # If we wanted to inspect the file for any reason we can do that now

   #
   # Convert filename into a query string
   # (use same rules that Metadata::guesTitle does)
   my $query = $filename;
   $query = uri_unescape($query);  # in case it was escaped
   # Strip off the file extension
   if (rindex($query, '.') != -1) {
      $query = substr($query, 0, rindex($query, '.'));
   }
   # Strip off anything following '(' - people use this for general comments
   if (rindex($query, '(') != -1) {
      $query = substr($query, 0, rindex($query, '('));
   }
   # Strip off anything following '[' - people use this for general comments
   if (rindex($query, '[') != -1) {
      $query = substr($query, 0, rindex($query, '['));
   }

   # IMDB searches do better if any trailing ,The is left off
   $query =~ /(.*), The$/i;
   if ($1) { $query = $1; }
   
   # prepare the url
   $query = uri_escape($query);
   if (!$options) { $options = "" ;}
   if (defined $opt_d) {
      printf("# query: '%s', options: '%s'\n", $query, $options);
   }
   
   # get the search results  page
   #    some known IMDB options are: 
   #         type=[fuzy]         looser search
   #         from_year=[int]     limit matches to year (broken at imdb)
   #         to_year=[int]       limit matches to year (broken at imdb)
   #         sort=[smart]        ??
   #         tv=[no|both|only]   limits between tv and movies (broken at imdb)
   #$options = "tt=on;nm=on;mx=20";  # not exactly clear what these options do
   my $request = "http://www.imdb.com/find?q=$query;$options";
   if (defined $opt_d) { printf("# request: '%s'\n", $request); }
   my $response = get $request;
   if (defined $opt_r) {
      print $response;
      exit(0);
   }
   
   # check to see if we got a results page or a movie page
   #    looking for 'add=<movieid>" target=' which only exists
   #    in a movie description page
   my $movienum = parseBetween($response, "add=", "\" target=");
   if ($movienum) {
       if (defined $opt_d) { printf("# redirected to movie page\n"); }
       my $movietitle = parseBetween($response, "<title>", "</title>");
       $movietitle =~ m#(.+) \((\d+)\)#;
       $movietitle = $1;
       print "$movienum:$movietitle\n";
       exit(0);
   }

   # extract possible matches
   #    possible matches are grouped in several catagories: 
   #        exact, partial, and approximate
   my $popular_results = parseBetween($response, "<b>Popular Titles</b>",
                                              "</ol>");
   my $exact_matches = parseBetween($response, "<b>Titles (Exact Matches)</b>",
                                              "</ol>");
   my $partial_matches = parseBetween($response, "<b>Titles (Partial Matches)</b>",
                                              "</ol>");
#   my $approx_matches = parseBetween($response, "<b>Approximate Matches</b>",
#                                               "</ol>");
   # parse movie list from matches
   my $beg = "<li>";
   my $end = "</li>";
   my $count = 0;
   my @movies;

#   my $data = $exact_matches.$partial_matches;
   my $data = $popular_results.$exact_matches;
   # resort to partial matches if no exact
   if ($data eq "") { $data = $partial_matches; }
   # resort to approximate matches if no exact or partial
#   if ($data eq "") { $data = $approx_matches; }
   if ($data eq "") {
      if (defined $opt_d) { printf("# no results\n"); }
      return;
   }
   my $start = index($data, $beg);
   my $finish = index($data, $end, $start);
   my $year;
   my $type;
   my $title;
   while ($start != -1 && $start < length($data)) {
      $start += length($beg);
      my $entry = substr($data, $start, $finish - $start);
      $start = index($data, $beg, $finish + 1);
      $finish = index($data, $end, $start);

      my $title = "";
      my $year = "";
      my $type = "";
      my $movienum = "";

      my $link_end = "</a>";
      $fl_end = index($entry, $link_end);
      $fl_end += length($link_end);
      my $lhs = substr($entry, 0, $fl_end);
      my $rhs = substr($entry, $fl_end);

      if ($lhs =~ m/<a href="\/title\/tt(\d+)\/.*\">(.+)<\/a>/i) {
          $movienum = $1;
          $title = $2;
      } else {
           if (defined $opt_d) {
               print("Unrecognized entry format\n");
           }
           next;
      }

      if ($rhs =~ m/\((\d+)\) \((.+)\)/) {
          $year = $1;
          $type = $2;
      } elsif ($rhs =~ m/\((\d+)\)/) {
          $year = $1;
      }

      my $skip = 0;

      # fix broken 'tv=no' option
      if ($options =~ /tv=no/) {
         if ($type eq "TV") {
            if (defined $opt_d) {printf("# skipping TV program: %s\n", $title);}
            $skip = 1;
         }
      }
      if ($options =~ /tv=only/) {
         if ($type eq "") {
            if (defined $opt_d) {printf("# skipping Movie: %s\n", $title);}
            $skip = 1;
         }
      }
      # fix broken 'from_year=' option
      if ($options =~ /from_year=(\d+)/) {
         if ($year < $1) {
            if (defined $opt_d) {printf("# skipping b/c of yr: %s\n", $title);}
            $skip = 1;
         }
      }
      # fix broken 'to_year=' option
      if ($options =~ /to_year=(\d+)/) {
         if ($year > $1) {
            if (defined $opt_d) {printf("# skipping b/c of yr: %s\n", $title);}
            $skip = 1;
         }
      }

      # option to strip out videos (I think that's what '(V)' means anyway?)
      if ($options =~ /video=no/) {
         if ($type eq "V") {
            if (defined $opt_d) {
                printf("# skipping Video program: %s\n", $title);
            }
            $skip = 1;
         }
      }
   
      # (always) strip out video game's (why does IMDB give these anyway?)
      if ($type eq "VG") {
         if (defined $opt_d) {printf("# skipping videogame: %s\n", $title);}
         $skip = 1;
      }

      # add to array
      if (!$skip) {
          my $moviename = $title;
          if ($year ne "") {
              $moviename .= " ($year)";
          }

#         $movies[$count++] = $movienum . ":" . $title;
         $movies[$count++] = $movienum . ":" . $moviename;
      }
   }

   # display array of values
   for $movie (@movies) { print "$movie\n"; }
}

#
# Main Program
#

# parse command line arguments
getopts('ohrdivDMP');

# print out info
if (defined $opt_v) { version(); exit 1; }
if (defined $opt_i) { info(); exit 1; }

# print out usage if needed
if (defined $opt_h || $#ARGV<0) { help(); }

if (defined $opt_D) {
   # take movieid from cmdline arg
   $movieid = shift || die "Usage : $0 -D <movieid>\n";
   getMovieData($movieid);
}

elsif (defined $opt_P) {
   # take movieid from cmdline arg
   $movieid = shift || die "Usage : $0 -P <movieid>\n";
   getMoviePoster($movieid);
}

elsif (defined $opt_M) {
   # take query from cmdline arg
   $options = shift || die "Usage : $0 -M [options] <query>\n";
   $query = shift;
   if (!$query) {
      $query = $options;
      $options = "";
   }
   getMovieList($query, $options);
}



ANYWAY If anyone ploughs through this and gets it all working, well done. It took me over a month solid to write and hone these. I've coded for yonks at all levels on windoze but this is my first forray into linux. I know it may seem mad to do all this in bash, but I did it to learn bash/linux. Maybe this may go someway to explaining why I was so mad when mythvideo was trashed in 0.19 to make it really slow, and try to ignore the database, obviously nullifying the original authors design intentions. In 0.19 why even bother using a database you clearly don't want to. As stated earlier I'll try to create a proper installer script and make it more generic/simpler sometime (maybe) but don't hold yer breath. If anyone else cares to, that'd be greatly appreciated...


Top
 Profile  
 

Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 2 posts ] 


All times are UTC - 6 hours




Who is online

Users browsing this forum: No registered users and 1 guest


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
cron
Powered by phpBB® Forum Software © phpBB Group

Theme Created By ceyhansuyu