Personal Video Database Scripting Manual
Obligatory callback functions: »
function GetScriptVersion : String;

You must return here a string containing version of the script. Any versioning format is acceptable, but you are advised to use the following format: major.minor.release.build
function GetScriptName : String;

This function should return a short name of the script. You are advised to put the language of the script in brackets in the beginning of the name like this: [EN] Test
function GetScriptDesc : String;

Return a long description here. You are advised to put the language of the script in brackets in the beginning of the name like this: [EN] Long Test
function GetBaseURL : AnsiString;

Web import scripts should return the base URL of the resource they are getting information from. For example: if you retrieve data from IMDB, you will need to return http://www.imdb.com. This URL will be used to detect if a record already has a link to the right page on this resource, so that search is not needed.
function GetScriptLang : Cardinal;

Return the language identifier of your script (resource). A list of all possible language identifiers is available here: http://msdn.microsoft.com/en-us/library/ms776294%28VS.85%29.aspx (you only need to pass the “primary language identifier”). For example: return $07 for German language.
function GetScriptType : Byte;

Return the type of your script here.

Possible return values are:
0 movie information script
1 people information script
2 poster download
3 screenshots download
4 covers download
function GetCurrentMode : Byte;

This function is used by the main application to determine if the script has already started parsing field information or is still in process of determining the right URL for a record.

Possible return values are:
0 script has not yet started filling information fields or awaits search results
> 0 script is filling information fields
function GetDownloadURL : AnsiString;

This function should return URL that should be downloaded by the main application and then passed to the script’s ParsePage function as text.

+ Example

If your script just need to find a movie/person and download one page with information you will need to write code like this:
Result := SEARCH_STR

If you need to download and parse more than one page I recommend to define extra variables or an array of URLs that need to be downloaded. Code for 2 information pages will look like this:
 if CreditsURL = '' then
  Result := SEARCH_STR
 else
  Result := SecondPageURL;

You can also use the mode variable as an extra flag. This code is for 3 pages using mode variable:
 if (Mode > 1) AND  (PosterURL <> '') then
  Result := PosterURL
 else
 if CreditsURL <> '' then
  Result := CreditsURL
 else
  Result := SEARCH_STR;



If you download poster in a movie information script or a photo in a person information script than make sure URL to an image is passed after all other pages are retrieved!
function ParsePage(HTML : String; URL : AnsiString) : Cardinal;

This function receives the text of the download web page passed to the main application in the GetDownloadURL function.

Parameters:
HTML contains the text of the page
URL contains the address of the page


Possible return values are:
0 an error acquired while processing data
1 script has finished gathering data
2 a list of search results is available
3 a list of image search results is available
4 another URL needs to be downloaded


+ Example
The following actions have to be made in this function:
a. Determine what information does this page contain (search results, movie/person information, etc.) b. Set the mode variable (if script state changes from "searching" to "found") c. Parse HTML and set information fields d. Return an appropriate result

a. Determine what information does this page contain
It's pretty simple: You need to find a unique marker in HTML for each page type and do some parsing according to what you have found on this page. Ex.:
if Pos('<title>Movie</title>', HTML) > 0 then begin

b. Set the mode variable
Mode := 1;

c. Parse HTML and set information fields
ParseMovie(URL, HTML); //This is a helper procedure to make the code better readable.

d. Return an appropriate result
Result := 1; //script has finished its job

The part of the code that determines the type of the web-page and does the rest of the actions should look like this:
if Pos('<title>Movie</title>', HTML) > 0 then begin
 Mode := 1;
//>0 – found field data
 ParseMovie(URL, HTML); //This is a helper procedure to make the code better
 Result := 1; //script has finished its job
end;

I recommend you to create a helper procedure to parse each page type. Ex.:
procedure ParseSearchResults(HTML : String); //parse search results
procedure ParseMovie(HTML : String); //parse main movie information
procedure ParseCredits(HTML : String); //parse movie credits

The whole ParsePage function should look like this:
function ParsePage(HTML : WideString; URL : String) : Cardinalbegin
 if Pos('<title>Search results</title>', HTML) > 0 then begin
  ParseSearchResults(HTML);
  Result := 2;
//search results retrieved
end else
 if Pos('Nothing found', HTML) > 0 then
  Result := 0
//error (movie not found)
else
 if (Pos('<title>Movie</title>', HTML) > 0) then begin
  Mode := 1;
//>0 – found field data
  ParseMovie(URL, HTML);
  Result := 1;
//script has finished its job
end else
  Result := 0;
//error (unknown page retrieved)
end;
Optional callback functions: « »
function GetRatingName : String;

You can tell the main application the name to be used for additional rating field (ratings from scripts are assigned to the additional rating field by default) by returning it in this function.
function GetCodePage : Cardinal;

Returns encoding to be used for downloaded data. All possible values are listed here: http://msdn.microsoft.com/en-us/library/dd317756%28VS.85%29.aspx
procedure GetLoginInfo(out URL : AnsiString; out Params : AnsiString);

This procedure is used to tell the main application to login into a web resource before downloading any other pages.

Parameters:
URL receives the address of the login page
Params receives parameters that will be passed to the login page using POST method
function GetDownloadMethod : Byte;

Defines method to be used to pass parameters in the last URL returned in GetDownloadURL function.

Possible return values are:
0 GET
1 POST
function GetPrefixMode : Byte;

For searches the application can format titles in a specific way before passing as a parameter to the search URL. Here, you can define how prefixes should be handled.

Possible return values are:
0 do nothing
1 move prefixes to the end of the title
2 place prefixes at the beginning of the title
3 remove prefixes from the title
[not yet implemented] function GetScriptAbout : String;

Return a short information message for an about dialog when accessed from application’s preferences.
function GetReferrer : String;

Return an address to be used as referrer when downloading the next web page.
function ProcException(Exception : String; Msg : String): AnsiString;

By implementing this function you can react on exceptions that acquire while downloading a web page.

Parameters:
Exception name of the exception
Msg error message
function GetCoverType : Smallint;

Relevant to cover download scripts only. When a cover image is retrieved the application must know if it is a front cover or disc image. For this purpose this function is called. If you do not implement the GetCoverType function the main application will interpret all images as front covers.

Possible return values are:
0 front cover
1 disc image
Functions used to fill data fields: « »
procedure AddSearchResult(Title1, Title2, Year, URL, PreviewURL : String);

Adds a search result. You do not need to provide information for all the variables. Most important is to assign at least Title1 or Title2 and URL. If you do not have information to assign to a certain variable just pass ''.
Example: AddSearchResult('Terminator', '', '', 'http://www.web-site.com/terminator.html', ''); //passes Title and URL


Parameters:
Title1 title or name
Title2 original title or translated name
Year movie release year
URL address containing record information
PreviewURL address of an image for a preview
[deprecated] procedure AddFieldValue(AField : Integer; AValue : String);

Fill a certain standard field with a value.

Parameters:
AField field identifier
AValue value for the field


Possible values for AField variable:
Movies People
0 url 0 url
1 title 1 name
2 original title 2 translated name
3 also known as 3 alternative names
4 year 4 date of birth
5 genre 5 place of birth
6 category 6 genre
7 country 7 biography
8 studio 8 date of death
9 mpaa    
10 additional rating    
11 tags    
12 tagline    
13 description    
14 duration    
15 features    
procedure AddImageURL(const AImageType : Integer; AValue : String);

Makes the main application download an image from an URL defined in AValue variable and assign the image to the record as a certain image type defined in AImageType variable.

Parameters:
AImageType type of the image
AValue address of the image


Possible values for AImageType variable:
0 poster
1 screenshot
2 front cover
3 disc image
4 photo
procedure AddFieldValueXML(AField : String; AValue : String);

Fill a certain field with a value. The field is identified by a string identifier.

Parameters:
AField field identifier
AValue value for the field


Possible values for AField variable: See Field Identifiers
procedure AddCustomFieldValueByNumber(CustomNumber : Integer; AValue : String);

Fill a certain custom field with a value. The field is identified its number.

Parameters:
CustomNumber field number
AValue value for the field
procedure AddCustomFieldValueByName(CustomName : String; AValue : String);

Fill a certain custom field with a value. The field is identified its name.

Parameters:
CustomName field name
AValue value for the field
procedure AddMoviePerson(Name, TransName, Role, URL : String; const AType : Byte);

Adds movie credits (actor, director, etc.).

Parameters:
Name name of the person
TransName translated name of the person
Role role of the person (if applicable)
URL web address of the person (if available)
AType credits type


Possible values for AType variable:
0 actor
1 director
2 writer
3 composer
4 producer
procedure AddPersonMovie(Title, OrigTitle, Role, Year, URL : String; AType : Byte);

Adds a movie to person's filmography.

Parameters:
Title movie title
OrigTitle original movie title
Role role of the person in the movie (if applicable)
Year release year of the movie
URL web address of the movie (if available)
AType credits type


Possible values for AType variable:
0 actor
1 director
2 writer
3 composer
4 producer
procedure AddAward(Event, Award, Category, Recipient, Year : String; const Won : Boolean);

Adds an award to a record.

Parameters:
Event name of the event
Award award name
Category award category
Recipient for movie records this variable should contain the name of a specific person who won the award and for people records the variable should contain the title of a movie for which the person won the award
Year release year of a movie (only applicable when adding award to a person record)
Won set to true if the recipient won the award and to false otherwise
procedure AddAwardEx(Event, Award, Category, RecipientVal1, RecipientVal2, Year : String; const Won : Boolean);

Adds an award to a record. Here you can define both title and original title of a movie as recipient or name and translated name for a person.

Parameters:
Event name of the event
Award award name
Category award category
RecipientVal1 for movie records this variable should contain the name of a specific person who won the award and for people records the variable should contain the title of a movie for which the person won the award
RecipientVal2 for movie records this variable should contain the translated name of a specific person who won the award and for people records the variable should contain the original title of a movie for which the person won the award
Year release year of a movie (only applicable when adding award to a person record)
Won set to true if the recipient won the award and to false otherwise
procedure AddConnection(Title, OrigTitle, Category, URL, Year : String);

Adds a movie connection.

Parameters:
Title movie title
OrigTitle original movie title
Category category connection
URL web address of the movie (if available)
Year release year of the movie
procedure AddEpisode(Title, OrigTitle, Description, URL, Year, Season, Episode : String);

Adds an episode to a series.

Parameters:
Title episode title
OrigTitle original episode title
Description episode description
URL web address of the episode (if available)
Year release year of the episode
Season season number (as string)
Episode episode number (as string)
[deprecated] function GetFieldValue(AField : Integer) : String;

Use this function to retrieve a field value from a record.

Parameters:
AField field identifier
function GetFieldValueXML(AField : String) : String;

Use this function to retrieve a field value from a record.

Parameters:
AField field identifier


Possible values for AField variable: See Field Identifiers
function GetCustomFieldValueByNumber(CustomNumber : Integer) : String;

Use this function to retrieve a custom field value from a record by accessing the field using its number.

Parameters:
CustomNumber number of a custom field
function GetCustomFieldValueByName(CustomName : String) : String;

Use this function to retrieve a custom field value from a record by accessing the field using its name.

Parameters:
CustomName name of a custom field
[deprecated] function GetSeriesFieldValue(AField : Integer) : String;

Use this function to retrieve a field value from a series record of an episode.

Parameters:
AField field identifier
function GetSeriesFieldValueXML(AField : String) : String;

Use this function to retrieve a field value from a series record of an episode.

Parameters:
AField field identifier


Possible values for AField variable: See Field Identifiers
function GetSeriesCustomFieldValueByNumber(CustomNumber : Integer) : String;

Use this function to retrieve a custom field value from a series record of an episode by accessing the field using its number.

Parameters:
CustomNumber number of a custom field
function GetSeriesCustomFieldValueByName(CustomName : String) : String;

Use this function to retrieve a custom field value from a series record of an episode by accessing the field using its name.

Parameters:
CustomName name of a custom field
String functions: « »
function Pos(Substr : String; Str : String): Integer;

Finds position of a substring in a string. The search is not case sensitive.

Parameters:
Substr string to search for
Str where to search


Return values:
Returns 0 if the substring was not found or position of the first occurrence of the substring otherwise.
function PosFrom(const SubStr, Str : String; FromIndex : Integer) : Integer;

Finds position of a substring in a string starting from a certain point. The search is not case sensitive.

Parameters:
Substr string to search for
Str where to search
FromIndex where to start searching


Return values:
Returns 0 if the substring was not found or position of the first occurrence of the substring otherwise.
function LastPos(const SubStr, Str : String) : Integer;

Finds position of a substring in a string starting from the end of the string. The search is not case sensitive.

Parameters:
Substr string to search for
Str where to search


Return values:
Returns 0 if the substring was not found or position of the last occurrence of the substring otherwise.
function PrevPos(const SubStr, Str : String; APos : Integer) : Integer;

Finds position of a substring in a string starting from a certain point and going back to the beginning of the string. The search is not case sensitive.

Parameters:
Substr string to search for
Str where to search
APos where to start searching


Return values:
Returns 0 if the substring was not found or position of the first occurrence of the substring before APos otherwise.
function RemoveTags(AText : String; doLineBreaks : Boolean) : String;

Removes all parts of the text between "<>" characters from the original string.

Parameters:
AText text where tags are to be removed
doLineBreaks set to true if you want the <br> tag to be replaced with carriage return character


Return values:
Returns the string without tags.
function ExplodeString(AText : String; var Items : TWideArray; Delimiters : String) : Integer;

Splits a string into multiple values using custom delimiters and puts each value into an array (all delimiters are removed).

Parameters:
AText string that needs to be split
[in] Items array where all the values will be contained
Delimiters a string containing allowed delimiters, one character each, without separator


Return values:
Returns number of produced values
function UpperCase(S : String) : String;

Switches all lowercase case characters in a string with their upper case equivalents.
function LowerCase(S : String) : String;

Switches all upper case characters in a string with their lower case equivalents.
function Copy(S : String; Index, Count : Integer) : String;

Returns a substring of a string.

Parameters:
S string from which a substring should be extracted
Index starting index of the substring
Count number of characters to extract


Return values:
Returns the resulting substring
procedure Delete(var S : String; Index, Count : Integer);

Removes a part of a string.

Parameters:
[in] S string from which to delete characters
Index where to start deletion
Count number of characters to remove
procedure Insert(Source : String; var Dest : String; Index : Integer);

Inserts a string into another string.

Parameters:
Source what to insert
[in] Dest destination string
Index where to insert the string
function Length(S : String) : Integer;

Counts the number of characters in a given string.
function Trim(S : String) : String;

Removes leading and trailing invisible characters like spaces or line breaks from a string.
function CompareText(S1, S2 : String) : Integer;

Compares two strings. The comparison is not case sensitive.

Return values:
Returns 0 if both strings are equal, a value greater than zero if S1 > S2 and a value smaller than zero if S1 < S2.
function CompareStr(S1, S2 : String) : Integer;

Compares two strings. The comparison is case sensitive.

Return values:
Returns 0 if both strings are equal, a value greater than zero if S1 > S2 and a value smaller than zero if S1 < S2.
function StringReplace(S, OldPattern, NewPattern : String; ReplaceAll : Boolean; IgnoreCase : Boolean; WholeWord : Boolean) : String;

Replaces all occurrences of a substring with another substring.

Parameters:
S text where the replacement should take place
OldPattern substring to replace
NewPattern substring to replace with
ReplaceAll if set to false only the first occurrence will be replaced
IgnoreCase if set to false the search for OldPattern will be case sensitive
WholeWord search only for whole words


Return values:
Returns the resulting substring
function StrToInt(const S : String) : Integer;

Converts a string that represents an integer (decimal or hex notation) to a number.
function IntToStr(const Value : Integer) : String;

Converts an integer number to a string.
function StrToFloat(const S : String) : Extended;

Converts a given string to a floating-point value.
function FloatToStr(const Value : Extended) : String;

Converts a floating point value to a string.
function HTMLValues(const HTML : String; ABegin, AEnd, ItemBegin, ItemEnd : String; ValDelim : String; var Pos : Integer) : String;

Gathers all values from a given text into a string using ValDelim as delimiter. The function searches for ABegin first starting from Pos, from this point it gathers values between ItemBegin and ItemEnd until AEnd is found. The last position is returned in Pos variable.

Parameters:
HTML text to process
ABegin substring where the values start (header)
ItemBegin substring that precedes each single value
ItemEnd substring that follow each single value
ValDelim delimiter to use in a resulting string
[in] Pos from which position in text should the search start (will contain the position of AEnd after execution)


Return values:
Returns the resulting delimited string
function HTMLValues2(const HTML : String; ABegin, AEnd, ItemBegin, ItemEnd : String; ValDelim : String; var Pos : Integer) : String;

Gathers all values from a given text into a string using ValDelim as delimiter. The function searches for ABegin first starting from Pos, from this point it gathers values between ItemBegin followed with ">" character and ItemEnd until AEnd is found. The last position is returned in Pos variable.

Parameters:
HTML text to process
ABegin substring where the values start (header)
ItemBegin substring that precedes each single value
ItemEnd substring that follow each single value
ValDelim delimiter to use in a resulting string
[in] Pos from which position in text should the search start (will contain the position of AEnd after execution)


Return values:
Returns the resulting delimited string
function TextBetween(const HTML : String; ABegin, AEnd : String; doLineBreaks : Boolean; var Pos : Integer) : String;

Extracts a part of a give between ABegin and AEnd and removes all tags from the resulting substring.

Parameters:
HTML text from which to extract the substring
ABegin substring that precedes the needed substring
AEnd substring that follows the needed substring
doLineBreaks set to true if you want the <br> tag to be replaced with carriage return character
[in] Pos from which position in text should the search start (will contain the position of AEnd after execution)


Return values:
Returns the resulting substring without tags.
function HTMLToText(const HTML : String) : String;

Replaces all escaped HTML characters (like &lt;&gt;&amp;&quot;) with normal characters (like <, >,$, ").
function ConvertEncoding(const HTML : AnsiString; CP : Cardinal) : String;

Decodes a given string from a certain encoding.

Parameters:
HTML text to decode
CP code page to use (referee to this document for a list of a list of code pages: http://msdn.microsoft.com/en-us/library/dd317756%28VS.85%29.aspx)


Return values:
Returns the decoded string.
File functions: « »
function FileExists(const AFileName : String) : Boolean;

Checks if a specified file exists.
function ChangeFileExt(const AFileName : String; const Ext : String) : String;

Changes file extension.

Parameters:
AFileName file name
Ext new extension with preceding point


Return values:
Returns the file name with a new extension.
function FileToString(const AFileName : String) : String;

Loads a specified file and returns it as a single string.
procedure StringToFile(const AFileName : String; const AData : String; const DoAppend : Boolean; const UTF8 : Boolean);

Writes a string to a file.

Parameters:
AFileName target file name
AData string to write
DoAppend set to true if you want to append the string to the end of the file, otherwise the file will be cleared before writing
UTF8 set to true if you want the string to be encoded in UTF8
function GetAppPath : String;

Returns the path where main application files are located.
function GetDBPath : String;

Returns the path of the current database without file name.
Date and Time functions: « »
function CurrentDateTime : Extended;

Returns current date and time.
function DateToStr(Value : Extended) : String;

Converts date to a textual representation using regional settings.
function TimeToStr(Value : Extended) : String;

Converts time to a textual representation using regional settings.
function EncDate(Year, Month, Day : Word): Extended;

Encodes date from given parameters.
function EncTime(Hour, Min, Sec : Word): Extended;

Encodes time from given parameters.
procedure DecdTime(const Time : Extended; var Hour, Min, Sec : Word);

Extracts the hour, minutes, seconds values from a time value.
procedure DecdDate(const Date : Extended; var Year, Month, Day : Word);

Extracts the year, month, day values from a date value.
function StrToDateW(const S : String): Extended;

Converts a textual representation of date into a date value using regional settings.
function StrToTimeW(const S : String): Extended;

Converts a textual representation of time into a time value using regional settings.
Miscellaneous functions: « »
procedure LogMessage(const Msg : String);

Writes a message string to main application's log. (see Debugging scripts)
procedure ShowMessage(const Msg, Head : String);

Shows a message box with OK button.

Parameters:
Msg message text
Head message box title
function MessageBox(const Msg, Head : String; Buttons : Cardinal) : Cardinal;

Shows a message box with specified buttons.

Parameters:
Msg message text
Head message box title
Buttons buttons to show on the message box


Possible values for Buttons parameter:
0 OK
1 OK, Cancel
2 Abort, Retry, Ignore
3 Yes, No, Cancel
4 Yes, No
5 Retry, Cancel


Return values:
Returns the identifier of the clicked button. Possible values are:
1 OK
2 Cancel
3 Abort
4 Retry
5 Ignore
6 Yes
7 No
procedure FileExecute(const AFileName : String; const Params : String);

Opens a specified file with the application associated with its file type or starts another application if an executable file is specified.

Parameters:
AFileName file to open or execute
Params command line parameters to pass with the file
procedure Wait(AMilliseconds : Cardinal);

Pause script execution for a specified number of milliseconds.
Field identifiers: « »
Movie Information Fields
num Movie ID
title Title
origtitle Original Title
aka Also Known As (separated with line break)
year Year
genre Genre (comma separated list)
country Country (comma separated list)
studio Studio (comma separated list)
release Release
mpaa MPAA
location Media Location
category Category (comma separated list)
tagline Tagline (multiline)
description Description (multiline)
count Media Count
type Media Type
rating Rating
imdbrating IMDB Rating
orating Additional Rating
orname Additional Rating Name
rip Quality
length Duration
langs Language (comma separated list)
translation Translation (comma separated list)
resolution Resolution
videocodec Video Codec
videobitrate Video Bitrate
audiocodec Audio Codec (comma separated list)
audiobitrate Audio Bitrate (comma separated list)
audiocount Number of audio streams
sampling Audio stream sampling (comma separated list)
channels Audio stream channels count (comma separated list)
rdate Release Date
budget Budget
money Box Office
aspect Aspect Ratio
size File Size
url URL (separated with space)
path File Path (files separated with |)
comment Comment (multiline)
dateadded Date Added
code Barcode
medialabel Media Label (comma separated list)
loan Is Borrowed (Boolean)
subs Subtitles (comma separated list)
framerate Frame Rate
features Features (multiline)
viewed Seen (Boolean)
bookmark Bookmarked (Boolean)
wish Wish (Boolean)
viewdate View Date
tags Tags (comma separated list)
origlang Original Language
poster Poster
screenshots Screenshots
froncover Front Cover
cdcover Disc Cover


People Information Fields
name Name
transname Translated Name
altnames Alternative Names (comma separated list)
birthday Birthday
birthplace Birthplace
bookmark Bookmarked (Boolean)
bio Biography (multiline)
comment Comment (multiline)
death Date of Death
age Age
url URL (separated with space)
genre Genre (comma separated list)
dateadded Date Added
photo Photo
Debugging the script (check for errors): «  
Before you can tell the script is ready you must test it first. Start PVD with -debug command line parameter, like this: viddb.exe -debug.
When you do this an additional menu item will become visible in "Help" menu called "Log".

In the log you can track following information:
If a script is wrong (contains errors) it will not be loaded into the program, so it cannot be selected from the "Import" menu or visible in Tools -> Preferences -> Plugins.

If an error has acquired while compiling a script, an error message appears in the log with detailed information about the wrong line in the script code and type of an error.
Ex.: [Error] (366:2): Semicolon (';') expected

Sometimes you can find hints produced by script compiler. Those hints tell you of unused variables, lines of code that are superficial etc.
Ex.: [Hint] (368:2): Variable 'TEST' never used

If a script can be compiled but does not work as it should you could use the ShowMessage, LogMessage and StringToFile functions to output variable values or some other useful information,  so you get a better picture of what is really happening in the script.

The last page downloaded is saved into a file called page.html in the program directory while in -debug mode.



Last update: 23.04.2010
Personal Video Database Version 0.9.9.20
Script Engine Plugin 0.2.6.0
Author: Nostradamus
http://www.videodb.info