Commit 5bf56453 authored by Jean-Baptiste Kempf's avatar Jean-Baptiste Kempf

lua: Update VLSub to 0.9.13

(cherry picked from commit cbce4489c7d788483ef4a2fb1b6708c0df765aa8)
(cherry picked from commit 4b07f72828f93289b70365dfa9d729f4d4a2dff2)
Signed-off-by: default avatarJean-Baptiste Kempf <jb@videolan.org>
parent 529932ce
--[[
VLSub Extension for VLC media player 1.1 and 2.0
Copyright 2013 Guillaume Le Maout
Authors: Guillaume Le Maout
Contact: http://addons.videolan.org/messages/?action=newmessage&username=exebetche
Bug report: http://addons.videolan.org/content/show.php/?content=148752
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
VLSub Extension for VLC media player 1.1 and 2.0
Copyright 2013 Guillaume Le Maout
Authors: Guillaume Le Maout
Contact:
http://addons.videolan.org/messages/?action=newmessage&username=exebetche
Bug report: http://addons.videolan.org/content/show.php/?content=148752
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
--[[ Global var ]]--
-- You can set here your default language by replacing nil with your language code (see below)
-- Example:
-- You can set here your default language by replacing nil with
-- your language code (see below).Example:
-- language = "fre",
-- language = "ger",
-- language = "eng",
......@@ -43,14 +44,18 @@ local options = {
eng = 'English',
cze = 'Czech',
dan = 'Danish',
dut = 'Nederlands',
fre = 'Français',
ell = 'Greek',
baq = 'Basque',
pob = 'Brazilian Portuguese',
por = 'Portuguese (Portugal)',
rum = 'Romanian',
slo = 'Slovak',
spa = 'Spanish',
swe = 'Swedish',
ukr = 'Ukrainian'
ukr = 'Ukrainian',
hun = 'Hungarian'
},
translation = {
int_all = 'All',
......@@ -86,28 +91,64 @@ local options = {
int_vlsub_work_dir = 'VLSub working directory',
int_os_username = 'Username',
int_os_password = 'Password',
int_help_mess = " Download subtittles from <a href='http://www.opensubtitles.org/'>opensubtitles.org</a> and display them while watching a video.<br>"..
" <br>"..
" <b><u>Usage:</u></b><br>"..
" <br>"..
" VLSub is meant to be used while your watching the video, so start it first (if nothing is playing you will get a link to download the subtitles in your browser).<br>"..
" <br>"..
" Choose the language for your subtitles and click on the button corresponding to one of the two research method provided by VLSub:<br>"..
" <br>"..
" <b>Method 1: Search by hash</b><br>"..
" It is recommended to try this method first, because it performs a research based on the video file print, so you can find subtitles synchronized with your video.<br>"..
" <br>"..
" <b>Method 2: Search by name</b><br>"..
" If you have no luck with the first method, just check the title is correct before clicking. If you search subtitles for a serie, you can also provide a season and episode number.<br>"..
" <br>"..
" <b>Downloading Subtitles</b><br>"..
" Select one subtitle in the list and click on 'Download'.<br>"..
" It will be put in the same directory that your video, with the same name (different extension)"..
" so Vlc will load them automatically the next time you'll start the video.<br>"..
" <br>"..
" <b>/!\\ Beware :</b> Existing subtitles are overwrited without asking confirmation, so put them elsewhere if thet're important.<br>"..
" <br>"..
" Find more Vlc extensions at <a href='http://addons.videolan.org'>addons.videolan.org</a>.",
int_help_mess =[[
Download subtitles from
<a href='http://www.opensubtitles.org/'>
opensubtitles.org
</a> and display them while watching a video.<br>
<br>
<b><u>Usage:</u></b><br>
<br>
Start your video. If you use Vlsub witout playing a video
you will get a link to download the subtitles in your browser
but the subtitles won't be saved and loaded automatically.<br>
<br>
Choose the language for your subtitles and click on the
button corresponding to one of the two research methods
provided by VLSub:<br>
<br>
<b>Method 1: Search by hash</b><br>
It is recommended to try this method first, because it
performs a research based on the video file print, so you
can find subtitles synchronized with your video.<br>
<br>
<b>Method 2: Search by name</b><br>
If you have no luck with the first method, just check the
title is correct before clicking. If you search subtitles
for a series, you can also provide a season and episode
number.<br>
<br>
<b>Downloading Subtitles</b><br>
Select one subtitle in the list and click on 'Download'.<br>
It will be put in the same directory that your video, with
the same name (different extension)
so VLC will load them automatically the next time you'll
start the video.<br>
<br>
<b>/!\\ Beware :</b> Existing subtitles are overwritten
without asking confirmation, so put them elsewhere if
they're important.<br>
<br>
Find more VLC extensions at
<a href='http://addons.videolan.org'>addons.videolan.org</a>.
]],
int_no_support_mess = [[
<strong>VLSub is not working with Vlc 2.1.x on
any platform</strong>
because the lua "net" module needed to interact
with opensubtitles has been
removed in this release for the extensions.
<br>
<strong>Works with Vlc 2.2 on mac and linux.</strong>
<br>
<strong>On windows you have to install an older version
of Vlc (2.0.8 for example)</strong>
to use Vlsub:
<br>
<a target="_blank" rel="nofollow"
href="http://download.videolan.org/pub/videolan/vlc/2.0.8/">
http://download.videolan.org/pub/videolan/vlc/2.0.8/</a><br>
]],
action_login = 'Logging in',
action_logout = 'Logging out',
......@@ -132,10 +173,13 @@ local options = {
mess_no_res = 'No result',
mess_res = 'result(s)',
mess_loaded = 'Subtitles loaded',
mess_not_load = 'Unable to load subtitles',
mess_downloading = 'Downloading subtitle',
mess_dowload_link = 'Download link',
mess_err_conf_access ='Can\'t fount a suitable path to save config, please set it manually',
mess_err_wrong_path ='the path contains illegal character, please correct it'
mess_err_conf_access ='Can\'t find a suitable path to save'..
'config, please set it manually',
mess_err_wrong_path ='the path contains illegal character, '..
'please correct it'
}
}
......@@ -278,12 +322,12 @@ local dlg = nil
local input_table = {} -- General widget id reference
local select_conf = {} -- Drop down widget / option table association
--[[ Vlc extension stuff ]]--
--[[ VLC extension stuff ]]--
function descriptor()
return {
title = "VLsub 0.9.10",
version = "0.9.10",
title = "VLsub 0.9.13",
version = "0.9.13",
author = "exebetche",
url = 'http://www.opensubtitles.org/',
shortdesc = "Download Subtitles";
......@@ -295,7 +339,10 @@ end
function activate()
vlc.msg.dbg("[VLsub] Welcome")
check_config()
if not check_config() then
vlc.msg.err("[VLsub] Unsupported VLC version")
return false
end
if vlc.input.item() then
openSub.getFileInfo()
......@@ -306,7 +353,7 @@ function activate()
end
function close()
deactivate()
vlc.deactivate()
end
function deactivate()
......@@ -318,7 +365,6 @@ function deactivate()
if openSub.session.token and openSub.session.token ~= "" then
openSub.request("LogOut")
end
vlc.deactivate()
end
function menu()
......@@ -344,24 +390,39 @@ end
function interface_main()
dlg:add_label(lang["int_default_lang"]..':', 1, 1, 1, 1)
input_table['language'] = dlg:add_dropdown(2, 1, 2, 1)
dlg:add_button(lang["int_search_hash"], searchHash, 4, 1, 1, 1)
dlg:add_button(lang["int_search_hash"],
searchHash, 4, 1, 1, 1)
dlg:add_label(lang["int_title"]..':', 1, 2, 1, 1)
input_table['title'] = dlg:add_text_input(openSub.movie.title or "", 2, 2, 2, 1)
dlg:add_button(lang["int_search_name"], searchIMBD, 4, 2, 1, 1)
input_table['title'] = dlg:add_text_input(
openSub.movie.title or "", 2, 2, 2, 1)
dlg:add_button(lang["int_search_name"],
searchIMBD, 4, 2, 1, 1)
dlg:add_label(lang["int_season"]..':', 1, 3, 1, 1)
input_table['seasonNumber'] = dlg:add_text_input(openSub.movie.seasonNumber or "", 2, 3, 2, 1)
input_table['seasonNumber'] = dlg:add_text_input(
openSub.movie.seasonNumber or "", 2, 3, 2, 1)
dlg:add_label(lang["int_episode"]..':', 1, 4, 1, 1)
input_table['episodeNumber'] = dlg:add_text_input(openSub.movie.episodeNumber or "", 2, 4, 2, 1)
input_table['episodeNumber'] = dlg:add_text_input(
openSub.movie.episodeNumber or "", 2, 4, 2, 1)
input_table['mainlist'] = dlg:add_list(1, 5, 4, 1)
input_table['message'] = nil
input_table['message'] = dlg:add_label(' ', 1, 6, 4, 1)
dlg:add_button(lang["int_show_help"], show_help, 1, 7, 1, 1)
dlg:add_button(' '..lang["int_show_conf"]..' ', show_conf, 2, 7, 1, 1)
dlg:add_button(lang["int_dowload_sel"], download_subtitles, 3, 7, 1, 1)
dlg:add_button(lang["int_close"], deactivate, 4, 7, 1, 1)
dlg:add_button(
lang["int_show_help"], show_help, 1, 7, 1, 1)
dlg:add_button(
' '..lang["int_show_conf"]..' ', show_conf, 2, 7, 1, 1)
dlg:add_button(
lang["int_dowload_sel"], download_subtitles, 3, 7, 1, 1)
dlg:add_button(
lang["int_close"], deactivate, 4, 7, 1, 1)
assoc_select_conf(
'language',
'language',
openSub.conf.languages,
2,
lang["int_all"])
assoc_select_conf('language', 'language', openSub.conf.languages, 2, lang["int_all"])
display_subtitles()
end
......@@ -372,78 +433,135 @@ function set_interface_main()
openSub.getFileInfo()
openSub.getMovieInfo()
input_table['title']:set_text(openSub.movie.title or "")
input_table['episodeNumber']:set_text(openSub.movie.episodeNumber or "")
input_table['seasonNumber']:set_text(openSub.movie.seasonNumber or "")
input_table['title']:set_text(
openSub.movie.title or "")
input_table['episodeNumber']:set_text(
openSub.movie.episodeNumber or "")
input_table['seasonNumber']:set_text(
openSub.movie.seasonNumber or "")
end
function interface_config()
input_table['intLangLab'] = dlg:add_label(lang["int_int_lang"]..':', 1, 1, 1, 1)
input_table['intLangBut'] = dlg:add_button(lang["int_search_transl"], get_available_translations, 2, 1, 1, 1)
input_table['intLangLab'] = dlg:add_label(
lang["int_int_lang"]..':', 1, 1, 1, 1)
input_table['intLangBut'] = dlg:add_button(
lang["int_search_transl"],
get_available_translations, 2, 1, 1, 1)
input_table['intLang'] = dlg:add_dropdown(3, 1, 1, 1)
dlg:add_label(lang["int_default_lang"]..':', 1, 2, 2, 1)
dlg:add_label(
lang["int_default_lang"]..':', 1, 2, 2, 1)
input_table['default_language'] = dlg:add_dropdown(3, 2, 1, 1)
dlg:add_label(lang["int_dowload_behav"]..':', 1, 3, 2, 1)
dlg:add_label(
lang["int_dowload_behav"]..':', 1, 3, 2, 1)
input_table['downloadBehaviour'] = dlg:add_dropdown(3, 3, 1, 1)
dlg:add_label(lang["int_display_code"]..':', 1, 4, 0, 1)
dlg:add_label(
lang["int_display_code"]..':', 1, 4, 0, 1)
input_table['langExt'] = dlg:add_dropdown(3, 4, 1, 1)
dlg:add_label(lang["int_remove_tag"]..':', 1, 5, 0, 1)
dlg:add_label(
lang["int_remove_tag"]..':', 1, 5, 0, 1)
input_table['removeTag'] = dlg:add_dropdown(3, 5, 1, 1)
if openSub.conf.dirPath then
if openSub.conf.os == "win" then
dlg :add_label("<a href='file:///"..openSub.conf.dirPath.."'>"..lang["int_vlsub_work_dir"].."</a>", 1, 6, 2, 1)
dlg:add_label(
"<a href='file:///"..openSub.conf.dirPath.."'>"..
lang["int_vlsub_work_dir"].."</a>", 1, 6, 2, 1)
else
dlg :add_label("<a href='"..openSub.conf.dirPath.."'>"..lang["int_vlsub_work_dir"].."</a>", 1, 6, 2, 1)
dlg:add_label(
"<a href='"..openSub.conf.dirPath.."'>"..
lang["int_vlsub_work_dir"].."</a>", 1, 6, 2, 1)
end
else
dlg :add_label(lang["int_vlsub_work_dir"], 1, 6, 2, 1)
dlg :add_label(
lang["int_vlsub_work_dir"], 1, 6, 2, 1)
end
input_table['dir_path'] = dlg:add_text_input(openSub.conf.dirPath, 2, 6, 2, 1)
input_table['dir_path'] = dlg:add_text_input(
openSub.conf.dirPath, 2, 6, 2, 1)
dlg:add_label(lang["int_os_username"]..':', 1, 7, 0, 1)
input_table['os_username'] = dlg:add_text_input(openSub.option.os_username or "", 2, 7, 2, 1)
dlg:add_label(lang["int_os_password"]..':', 1, 8, 0, 1)
input_table['os_password'] = dlg:add_text_input(openSub.option.os_password or "", 2, 8, 2, 1)
dlg:add_label(
lang["int_os_username"]..':', 1, 7, 0, 1)
input_table['os_username'] = dlg:add_text_input(
type(openSub.option.os_username) == "string"
and openSub.option.os_username or "", 2, 7, 2, 1)
dlg:add_label(
lang["int_os_password"]..':', 1, 8, 0, 1)
input_table['os_password'] = dlg:add_text_input(
type(openSub.option.os_password) == "string"
and openSub.option.os_password or "", 2, 8, 2, 1)
input_table['message'] = nil
input_table['message'] = dlg:add_label(' ', 1, 9, 3, 1)
dlg:add_button(lang["int_cancel"], show_main, 2, 10, 1, 1)
dlg:add_button(lang["int_save"], apply_config, 3, 10, 1, 1)
input_table['langExt']:add_value(lang["int_bool_"..tostring(openSub.option.langExt)], 1)
input_table['langExt']:add_value(lang["int_bool_"..tostring(not openSub.option.langExt)], 2)
input_table['removeTag']:add_value(lang["int_bool_"..tostring(openSub.option.removeTag)], 1)
input_table['removeTag']:add_value(lang["int_bool_"..tostring(not openSub.option.removeTag)], 2)
assoc_select_conf('intLang', 'intLang', openSub.conf.translations_avail, 2)
assoc_select_conf('default_language', 'language', openSub.conf.languages, 2, lang["int_all"])
assoc_select_conf('downloadBehaviour', 'downloadBehaviour', openSub.conf.downloadBehaviours, 1)
dlg:add_button(
lang["int_cancel"],
show_main, 2, 10, 1, 1)
dlg:add_button(
lang["int_save"],
apply_config, 3, 10, 1, 1)
input_table['langExt']:add_value(
lang["int_bool_"..tostring(openSub.option.langExt)], 1)
input_table['langExt']:add_value(
lang["int_bool_"..tostring(not openSub.option.langExt)], 2)
input_table['removeTag']:add_value(
lang["int_bool_"..tostring(openSub.option.removeTag)], 1)
input_table['removeTag']:add_value(
lang["int_bool_"..tostring(not openSub.option.removeTag)], 2)
assoc_select_conf(
'intLang',
'intLang',
openSub.conf.translations_avail,
2)
assoc_select_conf(
'default_language',
'language',
openSub.conf.languages,
2,
lang["int_all"])
assoc_select_conf(
'downloadBehaviour',
'downloadBehaviour',
openSub.conf.downloadBehaviours,
1)
end
function interface_help()
local help_html = lang["int_help_mess"]
input_table['help'] = dlg:add_html(help_html, 1, 1, 4, 1)
dlg:add_label(string.rep ("&nbsp;", 100), 1, 2, 3, 1)
dlg:add_button(lang["int_ok"], show_main, 4, 2, 1, 1)
input_table['help'] = dlg:add_html(
help_html, 1, 1, 4, 1)
dlg:add_label(
string.rep ("&nbsp;", 100), 1, 2, 3, 1)
dlg:add_button(
lang["int_ok"], show_main, 4, 2, 1, 1)
end
function interface_no_support()
local no_support_html = lang["int_no_support_mess"]
input_table['no_support'] = dlg:add_html(
no_support_html, 1, 1, 4, 1)
dlg:add_label(
string.rep ("&nbsp;", 100), 1, 2, 3, 1)
end
function trigger_menu(dlg_id)
if dlg_id == 1 then
close_dlg()
dlg = vlc.dialog(openSub.conf.useragent)
dlg = vlc.dialog(
openSub.conf.useragent)
interface_main()
elseif dlg_id == 2 then
close_dlg()
dlg = vlc.dialog(openSub.conf.useragent..': '..lang["int_configuration"])
dlg = vlc.dialog(
openSub.conf.useragent..': '..lang["int_configuration"])
interface_config()
elseif dlg_id == 3 then
close_dlg()
dlg = vlc.dialog(openSub.conf.useragent..': '..lang["int_help"])
dlg = vlc.dialog(
openSub.conf.useragent..': '..lang["int_help"])
interface_help()
end
collectgarbage() --~ !important
......@@ -478,8 +596,13 @@ end
--[[ Drop down / config association]]--
function assoc_select_conf(select_id, option, conf, ind, default)
-- Helper for i/o interaction betwenn drop down and option list (lang...)
select_conf[select_id] = {cf = conf, opt = option, dflt = default, ind = ind}
-- Helper for i/o interaction between drop down and option list
select_conf[select_id] = {
cf = conf,
opt = option,
dflt = default,
ind = ind
}
set_default_option(select_id)
display_select(select_id)
end
......@@ -503,7 +626,7 @@ function set_default_option(select_id)
end
function display_select(select_id)
-- Display the drop down values with an optionnal default value at the top
-- Display the drop down values with an optional default value at the top
local conf = select_conf[select_id].cf
local opt = select_conf[select_id].opt
local option = openSub.option[opt]
......@@ -563,9 +686,11 @@ function check_config()
-- Check if config file path is stored in vlc config
local other_dirs = {}
for path in vlc.config.get("sub-autodetect-path"):gmatch("[^,]+") do
for path in
vlc.config.get("sub-autodetect-path"):gmatch("[^,]+") do
if path:match(".*"..sub_dir.."$") then
openSub.conf.dirPath = path:gsub("%s*(.*)"..sub_dir.."%s*$", "%1")
openSub.conf.dirPath = path:gsub(
"%s*(.*)"..sub_dir.."%s*$", "%1")
config_saved = true
end
table.insert(other_dirs, path)
......@@ -586,12 +711,15 @@ function check_config()
-- check if the config already exist
if file_exist(userdatadir..dirPath..filePath) then
-- in vlc.config.userdatadir()
openSub.conf.dirPath = userdatadir..dirPath
config_saved = true
elseif file_exist(datadir..dirPath..filePath) then
-- in vlc.config.datadir()
openSub.conf.dirPath = datadir..dirPath
config_saved = true
else
-- if not found determine an accessible path
local extension_path = slash..path_generic[1]
..slash..path_generic[2]
......@@ -637,7 +765,8 @@ function check_config()
if config_saved
and file_exist(openSub.conf.filePath) then
vlc.msg.dbg("[VLSub] Loading config file: "..openSub.conf.filePath)
vlc.msg.dbg(
"[VLSub] Loading config file: "..openSub.conf.filePath)
load_config()
else
vlc.msg.dbg("[VLSub] No config file")
......@@ -648,16 +777,24 @@ function check_config()
end
end
-- Check presence of a translation file in "%vlsub_directory%/locale"
-- Check presence of a translation file
-- in "%vlsub_directory%/locale"
-- Add translation files to available translation list
local file_list = list_dir(openSub.conf.localePath)
local translations_avail = openSub.conf.translations_avail
if file_list then
for i, file_name in ipairs(file_list) do
local lg = string.gsub(file_name, "^(%w%w%w).xml$", "%1")
if lg and not translations_avail[lg] then
table.insert(translations_avail, {lg, trsl_names[lg]})
local lg = string.gsub(
file_name,
"^(%w%w%w).xml$",
"%1")
if lg
and not openSub.option.translations_avail[lg] then
table.insert(translations_avail, {
lg,
trsl_names[lg]
})
end
end
end
......@@ -666,25 +803,37 @@ function check_config()
if openSub.option.intLang ~= "eng"
and not openSub.conf.translated
then
local transl_file_path = openSub.conf.localePath..slash..openSub.option.intLang..".xml"
local transl_file_path = openSub.conf.localePath..
slash..openSub.option.intLang..".xml"
if file_exist(transl_file_path) then
vlc.msg.dbg("[VLSub] Loadin translation from file: " .. transl_file_path)
vlc.msg.dbg(
"[VLSub] Loading translation from file: "..
transl_file_path)
load_transl(transl_file_path)
end
end
else
vlc.msg.dbg("[VLSub] Unable fount a suitable path to save config, please set it manually")
vlc.msg.dbg("[VLSub] Unable to find a suitable path"..
"to save config, please set it manually")
end
lang = nil
lang = options.translation -- just a shortcut
lang = options.translation -- just a short cut
if not vlc.net or not vlc.net.poll then
dlg = vlc.dialog(
openSub.conf.useragent..': '..lang["mess_error"])
interface_no_support()
dlg:show()
return false
end
SetDownloadBehaviours()
if not openSub.conf.dirPath then
setError(lang["mess_err_conf_access"])
end
-- Set table list of available traduction from assoc. array
-- Set table list of available translations from assoc. array
-- so it is sortable
for k, l in pairs(openSub.option.translations_avail) do
......@@ -695,6 +844,7 @@ function check_config()
end
end
collectgarbage()
return true
end
function load_config()
......@@ -760,7 +910,9 @@ function getenv_lang()
openSub.option.language = lang_os_to_iso[os_lang]
end
else -- Windows
local lang_w = string.match(os.setlocale("", "collate"), "^[^_]+")
local lang_w = string.match(
os.setlocale("", "collate"),
"^[^_]+")
for i, v in ipairs(openSub.conf.languages) do
if v[2] == lang_w then
openSub.option.language = v[1]
......@@ -774,6 +926,7 @@ function apply_config()
local lg_sel = input_table['intLang']:get_value()
local sel_val
local opt
local sel_cf
if lg_sel and lg_sel ~= 1
and openSub.conf.translations_avail[lg_sel] then
......@@ -783,14 +936,16 @@ function apply_config()
end
for select_id, v in pairs(select_conf) do
if input_table[select_id] and select_conf[select_id] then
if input_table[select_id]
and select_conf[select_id] then
sel_val = input_table[select_id]:get_value()
opt = select_conf[select_id].opt
sel_cf = select_conf[select_id]
opt = sel_cf.opt
if sel_val == 0 then
openSub.option[opt] = nil
else
openSub.option[opt] = select_conf[select_id].cf[sel_val][1]
openSub.option[opt] = sel_cf.cf[sel_val][1]
end
set_default_option(select_id)
......@@ -820,7 +975,10 @@ function apply_config()
or not dir_path then
local other_dirs = {}
for path in vlc.config.get("sub-autodetect-path"):gmatch("[^,]+") do
for path in
vlc.config.get(
"sub-autodetect-path"):gmatch("[^,]+"
) do
path = trim(path)
if path ~= (openSub.conf.dirPath or "")..sub_dir then
table.insert(other_dirs, path)
......@@ -835,16 +993,27 @@ function apply_config()
mkdir_p(dir_path)
end
openSub.conf.filePath = openSub.conf.dirPath..slash.."vlsub_conf.xml"
openSub.conf.localePath = openSub.conf.dirPath..slash.."locale"
openSub.conf.filePath = openSub.conf.dirPath..
slash.."vlsub_conf.xml"
openSub.conf.localePath = openSub.conf.dirPath..
slash.."locale"
else
openSub.conf.filePath = nil
openSub.conf.localePath = nil
end
vlc.config.set("sub-autodetect-path", table.concat(other_dirs, ", "))
vlc.config.set(
"sub-autodetect-path",
table.concat(other_dirs, ", "))
else
dir_path_err = true
setError(lang["mess_err_wrong_path"].."<br><b>"..string.gsub(dir_path, "[^%:%w%p%s§¤]+", "<span style='color:#B23'>%1</span>").."</b>")
setError(lang["mess_err_wrong_path"]..
"<br><b>"..
string.gsub(
dir_path,
"[^%:%w%p%s§¤]+",
"<span style='color:#B23'>%1</span>"
)..
"</b>")
end
end
......@@ -864,10 +1033,13 @@ function save_config()
-- Dump local config into config file
if openSub.conf.dirPath
and openSub.conf.filePath then
vlc.msg.dbg("[VLSub] Saving config file: " .. openSub.conf.filePath)
vlc.msg.dbg(
"[VLSub] Saving config file: "..
openSub.conf.filePath)
if file_touch(openSub.conf.filePath) then
local tmpFile = assert(io.open(openSub.conf.filePath, "wb"))
local tmpFile = assert(
io.open(openSub.conf.filePath, "wb"))
local resp = dump_xml(openSub.option)
tmpFile:write(resp)
tmpFile:flush()
......@@ -879,7 +1051,8 @@ function save_config()
collectgarbage()
return true
else
vlc.msg.dbg("[VLSub] Unable fount a suitable path to save config, please set it manually")
vlc.msg.dbg("[VLSub] Unable fount a suitable path "..
"to save config, please set it manually")
setError(lang["mess_err_conf_access"])
return false
end
......@@ -889,31 +1062,39 @@ function SetDownloadBehaviours()
openSub.conf.downloadBehaviours = nil
openSub.conf.downloadBehaviours = {
{'save', lang["int_dowload_save"]},
{'load', lang["int_dowload_load"]},
{'manual', lang["int_dowload_manual"]}
}
end
function get_available_translations()
-- Get all available translation files from the internet
-- (drop previous direct download from github repo because of problem with github https CA certficate on OS X an XP)
-- (drop previous direct download from github repo
-- causing error with github https CA certficate on OS X an XP)
-- https://github.com/exebetche/vlsub/tree/master/locale
local translations_url = "http://addons.videolan.org/CONTENT/content-files/148752-vlsub_translations.xml"
local translations_url = "http://addons.videolan.org/CONTENT/"..
"content-files/148752-vlsub_translations.xml"
if input_table['intLangBut']:get_text() == lang["int_search_transl"] then
if input_table['intLangBut']:get_text() == lang["int_search_transl"]
then
openSub.actionLabel = lang["int_searching_transl"]
local translations_content, lol = get(translations_url)
local translations_avail = openSub.option.translations_avail
all_trsl = parse_xml(translations_content)
local lg, trsl
for lg, trsl in pairs(all_trsl) do
if lg ~= options.intLang[1] and not openSub.option.translations_avail[lg] then
openSub.option.translations_avail[lg] = trsl_names[lg] or ""
table.insert(openSub.conf.translations_avail, {lg, trsl_names[lg]})
input_table['intLang']:add_value(trsl_names[lg], #openSub.conf.translations_avail)
if lg ~= options.intLang[1]
and not translations_avail[lg] then
translations_avail[lg] = trsl_names[lg] or ""
table.insert(openSub.conf.translations_avail, {
lg,
trsl_names[lg]
})
input_table['intLang']:add_value(
trsl_names[lg],
#openSub.conf.translations_avail)
end
end
......@@ -933,9 +1114,12 @@ function set_translation(lg)
else
-- If translation file exists in /locale directory load it
if openSub.conf.localePath
and file_exist(openSub.conf.localePath..slash..lg..".xml") then
local transl_file_path = openSub.conf.localePath..slash..lg..".xml"
vlc.msg.dbg("[VLSub] Loading translation from file: " .. transl_file_path)
and file_exist(openSub.conf.localePath..
slash..lg..".xml") then
local transl_file_path = openSub.conf.localePath..
slash..lg..".xml"
vlc.msg.dbg("[VLSub] Loading translation from file: "..
transl_file_path)
load_transl(transl_file_path)
apply_translation()
else
......@@ -1022,11 +1206,14 @@ openSub = {
response = parse_xmlrpc(responseStr)
if response then
if response.status == "200 OK" then
return openSub.methods[methodName].callback(response)
return openSub.methods[methodName]
.callback(response)
elseif response.status == "406 No session" then
openSub.request("LogIn")
elseif response then
setError("code '"..response.status.."' ("..status..")")
setError("code '"..
response.status..
"' ("..status..")")
return false
end
else
......@@ -1104,7 +1291,8 @@ openSub = {
methodName = "SearchSubtitles",
params = function()
openSub.actionLabel = lang["action_search"]
setMessage(openSub.actionLabel..": "..progressBarContent(0))
setMessage(openSub.actionLabel..": "..
progressBarContent(0))
return {
{ value={ string=openSub.session.token } },
......@@ -1115,11 +1303,13 @@ openSub = {
struct={
member={
{ name="sublanguageid", value={
string=openSub.movie.sublanguageid } },
string=openSub.movie.sublanguageid }
},
{ name="moviehash", value={
string=openSub.file.hash } },
{ name="moviebytesize", value={
double=openSub.file.bytesize } } }}}}}}}
double=openSub.file.bytesize } }
}}}}}}}
}
end,
callback = function(resp)
......@@ -1130,7 +1320,8 @@ openSub = {
methodName = "SearchSubtitles",
params = function()
openSub.actionLabel = lang["action_search"]
setMessage(openSub.actionLabel..": "..progressBarContent(0))
setMessage(openSub.actionLabel..": "..
progressBarContent(0))
local member = {
{ name="sublanguageid", value={
......@@ -1192,16 +1383,26 @@ openSub = {
file.path = string.match(file.path, "^/(%a:/.+)$") or file.path
-- For file in archive
local archive_path, name_in_archive = string.match(file.path, '^([^!]+)!/([^!/]*)$')
local archive_path, name_in_archive = string.match(
file.path, '^([^!]+)!/([^!/]*)$')
if archive_path and archive_path ~= "" then
file.path = string.gsub(archive_path, '\063', '%%')
file.path = string.gsub(
archive_path,
'\063',
'%%')
file.path = vlc.strings.decode_uri(file.path)
file.completeName = string.gsub(name_in_archive, '\063', '%%')
file.completeName = vlc.strings.decode_uri(file.completeName)
file.completeName = string.gsub(
name_in_archive,
'\063',
'%%')
file.completeName = vlc.strings.decode_uri(
file.completeName)
file.is_archive = true
else -- "classic" input
file.path = vlc.strings.decode_uri(file.path)
file.dir, file.completeName = string.match(file.path, '^(.+/)([^/]*)$')
file.dir, file.completeName = string.match(
file.path,
'^(.+/)([^/]*)$')
local file_stat = vlc.net.stat(file.path)
if file_stat
......@@ -1212,14 +1413,20 @@ openSub = {
file.is_archive = false
end
file.name, file.ext = string.match(file.completeName, '^([^/]-)%.?([^%.]*)$')
file.name, file.ext = string.match(
file.completeName,
'^([^/]-)%.?([^%.]*)$')
if file.ext == "part" then
file.name, file.ext = string.match(file.name, '^([^/]+)%.([^%.]+)$')
file.name, file.ext = string.match(
file.name,
'^([^/]+)%.([^%.]+)$')
end
file.hasInput = true;
file.cleanName = string.gsub(file.name, "[%._]", " ")
file.cleanName = string.gsub(
file.name,
"[%._]", " ")
vlc.msg.dbg("[VLSub] file info "..(dump_xml(file)))
end
collectgarbage()
......@@ -1233,10 +1440,14 @@ openSub = {
return false
end
local showName, seasonNumber, episodeNumber = string.match(openSub.file.cleanName, "(.+)[sS](%d%d)[eE](%d%d).*")
local showName, seasonNumber, episodeNumber = string.match(
openSub.file.cleanName,
"(.+)[sS](%d%d)[eE](%d%d).*")
if not showName then
showName, seasonNumber, episodeNumber = string.match(openSub.file.cleanName, "(.+)(%d)[xX](%d%d).*")
showName, seasonNumber, episodeNumber = string.match(
openSub.file.cleanName,
"(.+)(%d)[xX](%d%d).*")
end
if showName then
......@@ -1253,7 +1464,8 @@ openSub = {
getMovieHash = function()
-- Calculate movie hash
openSub.actionLabel = lang["action_hash"]
setMessage(openSub.actionLabel..": "..progressBarContent(0))
setMessage(openSub.actionLabel..": "..
progressBarContent(0))
local item = openSub.getInputItem()
......@@ -1394,8 +1606,10 @@ end
function searchIMBD()
openSub.movie.title = trim(input_table["title"]:get_text())
openSub.movie.seasonNumber = tonumber(input_table["seasonNumber"]:get_text())
openSub.movie.episodeNumber = tonumber(input_table["episodeNumber"]:get_text())
openSub.movie.seasonNumber = tonumber(
input_table["seasonNumber"]:get_text())
openSub.movie.episodeNumber = tonumber(
input_table["episodeNumber"]:get_text())
local sel = input_table["language"]:get_value()
if sel == 0 then
......@@ -1417,7 +1631,8 @@ function display_subtitles()
if openSub.itemStore == "0" then
mainlist:add_value(lang["mess_no_res"], 1)
setMessage("<b>"..lang["mess_complete"]..":</b> "..lang["mess_no_res"])
setMessage("<b>"..lang["mess_complete"]..":</b> "..
lang["mess_no_res"])
elseif openSub.itemStore then
for i, item in ipairs(openSub.itemStore) do
mainlist:add_value(
......@@ -1425,7 +1640,8 @@ function display_subtitles()
" ["..item.SubLanguageID.."]"..
" ("..item.SubSumCD.." CD)", i)
end
setMessage("<b>"..lang["mess_complete"]..":</b> "..#(openSub.itemStore).." "..lang["mess_res"])
setMessage("<b>"..lang["mess_complete"]..":</b> "..
#(openSub.itemStore).." "..lang["mess_res"])
end
end
......@@ -1451,21 +1667,17 @@ function download_subtitles()
local item = openSub.itemStore[index]
if openSub.option.downloadBehaviour == 'manual' then
if openSub.option.downloadBehaviour == 'manual'
or not subfileName then
local link = "<span style='color:#181'>"
link = link.."<b>"..lang["mess_dowload_link"]..":</b>"
link = link.."</span> &nbsp;"
link = link.."</span> &nbsp;<a href='"..item.ZipDownloadLink.."'>"
link = link.."</span> &nbsp;<a href='"..
item.ZipDownloadLink.."'>"
link = link..item.MovieReleaseName.."</a>"
setMessage(link)
return false
elseif openSub.option.downloadBehaviour == 'load' then
if add_sub("zip://"..item.ZipDownloadLink.."!/"..item.SubFileName) then
setMessage(success_tag(lang["mess_loaded"]))
end
return false
end
local message = ""
......@@ -1484,7 +1696,7 @@ function download_subtitles()
elseif openSub.conf.dirPath then
tmp_dir = openSub.conf.dirPath
message = "<br> "..error_tag(lang["mess_save_fail"].." &nbsp;"..
message = "<br>"..error_tag(lang["mess_save_fail"].." &nbsp;"..
"<a href='"..vlc.strings.make_uri(openSub.conf.dirPath).."'>"..
lang["mess_click_link"].."</a>")
else
......@@ -1508,8 +1720,10 @@ function download_subtitles()
if not file_touch(target) then
if openSub.conf.dirPath then
target = openSub.conf.dirPath..slash..subfileName
message = "<br> "..error_tag(lang["mess_save_fail"].." &nbsp;"..
"<a href='"..vlc.strings.make_uri(openSub.conf.dirPath).."'>"..
message = "<br>"..
error_tag(lang["mess_save_fail"].." &nbsp;"..
"<a href='"..vlc.strings.make_uri(
openSub.conf.dirPath).."'>"..
lang["mess_click_link"].."</a>")
else
setError(lang["mess_save_fail"].." &nbsp;"..
......@@ -1542,18 +1756,13 @@ function download_subtitles()
vlc.msg.err("[VLsub] Unable to remove temp: "..tmpFileName)
end
subfileURI = vlc.strings.make_uri(target)
if not subfileURI then
subfileURI = make_uri(target, true)
end
-- load subtitles
if add_sub(subfileURI) then
if add_sub(target) then
message = success_tag(lang["mess_loaded"]) .. message
else
message = error_tag(lang["mess_not_load"]) .. message
end
setMessage(message)
end
......@@ -1567,7 +1776,7 @@ function dump_zip(url, dir, subfileName)
return false
end
local tmpFileName = dir..slash..subfileName..".gz"
local tmpFileName = dir..subfileName..".gz"
if not file_touch(tmpFileName) then
return false
end
......@@ -1578,13 +1787,15 @@ function dump_zip(url, dir, subfileName)
tmpFile:close()
tmpFile = nil
collectgarbage()
return "zip://"..make_uri(tmpFileName, true).."!/"..subfileName, tmpFileName
return "zip://"..make_uri(tmpFileName)
.."!/"..subfileName, tmpFileName
end
function add_sub(subfileURI)
function add_sub(subPath)
if vlc.item or vlc.input.item() then
vlc.msg.dbg("[VLsub] Adding subtitle :" .. subfileURI)
return vlc.input.add_subtitle(subfileURI)
subPath = decode_uri(subPath)
vlc.msg.dbg("[VLsub] Adding subtitle :" .. subPath)
return vlc.input.add_subtitle(subPath)
end
return false
end
......@@ -1592,7 +1803,8 @@ end
--[[ Interface helpers]]--
function progressBarContent(pct)
local accomplished = math.ceil(openSub.option.progressBarSize*pct/100)
local accomplished = math.ceil(
openSub.option.progressBarSize*pct/100)
local left = openSub.option.progressBarSize - accomplished
local content = "<span style='background-color:#181;color:#181;'>"..
string.rep ("-", accomplished).."</span>"..
......@@ -1655,49 +1867,73 @@ function http_req(host, port, request)
vlc.net.send(fd, request)
vlc.net.poll(pollfds)
local response = vlc.net.recv(fd, 1024)
local headerStr, body = string.match(response, "(.-\r?\n)\r?\n(.*)")
local header = parse_header(headerStr)
local contentLength = tonumber(header["Content-Length"])
local TransferEncoding = header["Transfer-Encoding"]
local status = tonumber(header["statuscode"])
local bodyLenght = string.len(body)
local chunk = vlc.net.recv(fd, 2048)
local response = ""
local headerStr, header, body
local contentLength, status
local pct = 0
--~ if status ~= 200 then return status end
while contentLength and bodyLenght < contentLength do
vlc.net.poll(pollfds)
response = vlc.net.recv(fd, 1024)
if response then
body = body..response
else
vlc.net.close(fd)
return false
while chunk do
response = response..chunk
if not header then
headerStr, body = response:match("(.-\r?\n)\r?\n(.*)")
if headerStr then
response = body
header = parse_header(headerStr)
contentLength = tonumber(header["Content-Length"])
status = tonumber(header["statuscode"])
end
end
bodyLenght = string.len(body)
if contentLength then
bodyLenght = #response
pct = bodyLenght / contentLength * 100
setMessage(openSub.actionLabel..": "..progressBarContent(pct))
if bodyLenght >= contentLength then
break
end
end
vlc.net.poll(pollfds)
chunk = vlc.net.recv(fd, 1024)
end
vlc.net.close(fd)
return status, body
if status == 301
and header["Location"] then
local host, path = parse_url(trim(header["Location"]))
request = request
:gsub("^([^%s]+ )([^%s]+)", "%1"..path)
:gsub("(Host: )([^\n]*)", "%1"..host)
return http_req(host, port, request)
end
return status, response
end
function parse_header(data)
local header = {}
for name, s, val in string.gfind(data, "([^%s:]+)(:?)%s([^\n]+)\r?\n") do
if s == "" then header['statuscode'] = tonumber(string.sub (val, 1 , 3))
else header[name] = val end
for name, s, val in string.gmatch(
data,
"([^%s:]+)(:?)%s([^\n]+)\r?\n")
do
if s == "" then
header['statuscode'] = tonumber(string.sub(val, 1 , 3))
else
header[name] = val
end
end
return header
end
function parse_url(url)
local url_parsed = vlc.net.url_parse(url)
return url_parsed["host"], url_parsed["path"], url_parsed["option"]
return url_parsed["host"],
url_parsed["path"],
url_parsed["option"]
end
--[[ XML utils]]--
......@@ -1709,10 +1945,12 @@ function parse_xml(data)
local level = 0
local op, tag, p, empty, val
table.insert(stack, tree)
local resolve_xml = vlc.strings.resolve_xml_special_chars
for op, tag, p, empty, val in string.gmatch(
data,
"[%s\r\n\t]*<(%/?)([%w:_]+)(.-)(%/?)>[%s\r\n\t]*([^<]*)[%s\r\n\t]*"
"[%s\r\n\t]*<(%/?)([%w:_]+)(.-)(%/?)>"..
"[%s\r\n\t]*([^<]*)[%s\r\n\t]*"
) do
if op=="/" then
if level>0 then
......@@ -1742,7 +1980,7 @@ function parse_xml(data)
if type(stack[level][tag]) == "nil" then
stack[level][tag] = {}
end
stack[level][tag] = vlc.strings.resolve_xml_special_chars(val)
stack[level][tag] = resolve_xml(val)
table.insert(stack, {})
end
if empty ~= "" then
......@@ -1764,6 +2002,7 @@ function parse_xmlrpc(data)
local tmpTag = ""
local level = 0
local op, tag, p, empty, val
local resolve_xml = vlc.strings.resolve_xml_special_chars
table.insert(stack, tree)
for op, tag, p, empty, val in string.gmatch(
......@@ -1779,7 +2018,7 @@ function parse_xmlrpc(data)
end
elseif tag == "name" then
level = level + 1
if val~= "" then tmpTag = vlc.strings.resolve_xml_special_chars(val) end
if val~= "" then tmpTag = resolve_xml(val) end
if type(stack[level][tmpTag]) == "nil" then
stack[level][tmpTag] = {}
......@@ -1805,7 +2044,7 @@ function parse_xmlrpc(data)
table.insert(stack[level], tmp)
table.insert(stack, tmp)
elseif val ~= "" then
stack[level][tmpTag] = vlc.strings.resolve_xml_special_chars(val)
stack[level][tmpTag] = resolve_xml(val)
end
end
collectgarbage()
......@@ -1816,6 +2055,7 @@ function dump_xml(data)
local level = 0
local stack = {}
local dump = ""
local convert_xml = vlc.strings.convert_xml_special_chars
local function parse(data, stack)
local data_index = {}
......@@ -1835,17 +2075,23 @@ function dump_xml(data)
k = tb[1]
v = tb[2]
if type(k)=="string" then
dump = dump.."\r\n"..string.rep (" ", level).."<"..k..">"
dump = dump.."\r\n"..string.rep(
" ",
level)..
"<"..k..">"
table.insert(stack, k)
level = level + 1
elseif type(k)=="number" and k ~= 1 then
dump = dump.."\r\n"..string.rep (" ", level-1).."<"..stack[level]..">"
dump = dump.."\r\n"..string.rep(
" ",
level-1)..
"<"..stack[level]..">"
end
if type(v)=="table" then
parse(v, stack)
elseif type(v)=="string" then
dump = dump..(vlc.strings.convert_xml_special_chars(v) or v)
dump = dump..(convert_xml(v) or v)
elseif type(v)=="number" then
dump = dump..v
else
......@@ -1854,7 +2100,10 @@ function dump_xml(data)
if type(k)=="string" then
if type(v)=="table" then
dump = dump.."\r\n"..string.rep (" ", level-1).."</"..k..">"
dump = dump.."\r\n"..string.rep(
" ",
level-1)..
"</"..k..">"
else
dump = dump.."</"..k..">"
end
......@@ -1863,7 +2112,10 @@ function dump_xml(data)
elseif type(k)=="number" and k ~= #data then
if type(v)=="table" then
dump = dump.."\r\n"..string.rep (" ", level-1).."</"..stack[level]..">"
dump = dump.."\r\n"..string.rep(
" ",
level-1)..
"</"..stack[level]..">"
else
dump = dump.."</"..stack[level]..">"
end
......@@ -1877,23 +2129,23 @@ end
--[[ Misc utils]]--
function make_uri(str, encode)
local windowdrive = string.match(str, "^(%a:%).+$")
if encode then
function make_uri(str)
str = str:gsub("\\", "/")
local windowdrive = string.match(str, "^(%a:).+$")
local encode_uri = vlc.strings.encode_uri_component
local encodedPath = ""
for w in string.gmatch(str, "/([^/]+)") do
encodedPath = encodedPath.."/"..vlc.strings.encode_uri_component(w)
end
str = encodedPath
encodedPath = encodedPath.."/"..encode_uri(w)
end
if windowdrive then
return "file:///"..windowdrive..str
return "file:///"..windowdrive..encodedPath
else
return "file://"..str
return "file://"..encodedPath
end
end
function file_touch(name) -- test writetability
function file_touch(name) -- test write ability
if not name or trim(name) == ""
then return false end
......@@ -1921,7 +2173,7 @@ end
function is_dir(path)
if not path or trim(path) == ""
then return false end
-- Remove slash at the or it won't work on Windows
-- Remove slash at the end or it won't work on Windows
path = string.gsub(path, "^(.-)[\\/]?$", "%1")
local f, _, code = io.open(path, "rb")
......@@ -1973,8 +2225,13 @@ function mkdir_p(path)
end
end
function decode_uri(str)
vlc.msg.err(slash)
return str:gsub("/", slash)
end
function is_window_path(path)
return string.match(path, "^(%a:%).+$")
return string.match(path, "^(%a:.+)$")
end
function is_win_safe(path)
......@@ -1992,9 +2249,3 @@ end
function remove_tag(str)
return string.gsub(str, "{[^}]+}", "")
end
function sleep(sec)
local t = vlc.misc.mdate()
vlc.misc.mwait(t + sec*1000*1000)
end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment