-
Notifications
You must be signed in to change notification settings - Fork 4
/
osdb.lua
291 lines (255 loc) · 8.2 KB
/
osdb.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
if mp == nil then
print('Must be run inside MPV')
end
local rpc = require 'xmlrpc.http'
local os = require 'os'
local io = require 'io'
local http = require 'socket.http'
local zlib = require 'zlib'
local ltn12 = require 'ltn12'
local msg = require 'mp.msg'
local utils = require 'mp.utils'
require 'mp.options'
-- Read options from {mpv_config_dir}/lua-settings/osdb.conf
local options = {
tempFolder = '/tmp',
autoLoadSubtitles = false,
numSubtitles = 10,
language = 'eng',
autoFlagSubtitles = false,
useHashSearch = true,
useFilenameSearch = true,
osdDelayLong = 30,
osdDelayShort = -1,
user = '',
password = ''
}
read_options(options, 'osdb')
-- This is for performing RPC calls to OpenSubtitles
local osdb = {}
osdb.API = 'http://api.opensubtitles.org/xml-rpc'
osdb.USERAGENT = 'osdb-mpv v1'
function osdb.rpc(...)
local args = {...}
for i, item in pairs(args) do
args[i] = osdb.xml_escape(item)
end
local ok, res = rpc.call(osdb.API, table.unpack(args))
if not ok then
error('Request failed.')
elseif res.status ~= '200 OK' then
error('Request failed: ' .. res.status)
end
return res
end
function osdb.login(user, password)
local res = osdb.rpc('LogIn', user, password, 'en', osdb.USERAGENT)
osdb.token = res.token
end
function osdb.logout()
assert(osdb.token)
osdb.rpc('LogOut', osdb.token)
end
function osdb.query(search_query, nsubtitles)
assert(osdb.token)
local limit = {limit = nsubtitles}
local res = osdb.rpc('SearchSubtitles', osdb.token, search_query, limit)
if res.data == false then
error('No subtitles found in OSDb')
end
return res.data
end
function osdb.report(subdata)
assert(osdb.token)
assert(subdata)
osdb.rpc('ReportWrongMovieHash', osdb.token, subdata.IDSubMovieFile)
end
function osdb.xml_escape(val)
if type(val) == 'string' then
return val:gsub('%&', '&'):gsub('%<', '<'):gsub('%>', '>')
elseif type(val) == 'table' then
local conv = {}
for k, v in pairs(val) do
conv[k] = osdb.xml_escape(v)
end
return conv
else
return val
end
end
-- Movie hash function for OSDB, courtesy of
-- http://trac.opensubtitles.org/projects/opensubtitles/wiki/HashSourceCodes
function movieHash(fileName)
local fil = io.open(fileName, "rb")
if fil == nil then
error("Can't open file")
end
local lo,hi=0,0
for i=1,8192 do
local a,b,c,d = fil:read(4):byte(1,4)
lo = lo + a + b*256 + c*65536 + d*16777216
a,b,c,d = fil:read(4):byte(1,4)
hi = hi + a + b*256 + c*65536 + d*16777216
while lo>=4294967296 do
lo = lo-4294967296
hi = hi+1
end
while hi>=4294967296 do
hi = hi-4294967296
end
end
local size = fil:seek("end", -65536) + 65536
for i=1,8192 do
local a,b,c,d = fil:read(4):byte(1,4)
lo = lo + a + b*256 + c*65536 + d*16777216
a,b,c,d = fil:read(4):byte(1,4)
hi = hi + a + b*256 + c*65536 + d*16777216
while lo>=4294967296 do
lo = lo-4294967296
hi = hi+1
end
while hi>=4294967296 do
hi = hi-4294967296
end
end
lo = lo + size
while lo>=4294967296 do
lo = lo-4294967296
hi = hi+1
end
while hi>=4294967296 do
hi = hi-4294967296
end
fil:close()
return string.format("%08x%08x", hi,lo), size
end
function download(subtitle)
assert(subtitle.SubDownloadLink and subtitle.SubFileName)
local inflate = zlib.inflate()
local decompress = function(chunk)
if chunk ~= '' and chunk ~= nil then
return inflate(chunk)
else
return chunk
end
end
local subfile = string.format(options.tempFolder..'/%s', subtitle.SubFileName)
http.request {
url = subtitle.SubDownloadLink,
sink = ltn12.sink.chain(
decompress,
ltn12.sink.file(io.open(subfile, 'wb'))
)
}
return subfile
end
-- Subtitle list cache
local subtitles = {}
function subtitles.set(self, list)
self.count = #list
self.list = list
self.current = nil
self.idx = nil
for _, sub in pairs(list) do
sub.download = download
end
end
function subtitles.next(self)
self.idx = next(self.list, self.idx)
self.current = self.list[self.idx]
end
function fetch_list()
local srcfile = mp.get_property('path')
assert(srcfile ~= nil)
mp.osd_message("Searching for subtitles...", options.osdDelayLong)
local searchQuery = {}
if options.useHashSearch then
local ok, mhash, fsize = pcall(movieHash, srcfile)
if ok then
table.insert(searchQuery,
{
moviehash = mhash,
moviebytesize = fsize,
sublanguageid = options.language
})
else
msg.warn("Movie hash couldn't be computed")
end
end
if options.useFilenameSearch then
local _, basename = utils.split_path(srcfile)
table.insert(searchQuery,
{
query = basename,
sublanguageid = options.language
})
end
osdb.login(options.user, options.password)
subtitles:set(osdb.query(searchQuery, options.numSubtitles))
if subtitles.count == 0 then
mp.osd_message("No subtitles found", options.osdDelayShort)
end
osdb.logout()
end
function rotate_subtitles()
if subtitles.count == 0 then
-- Refresh the subtitle list
fetch_list()
end
-- Remove previous subtitle track, if possible
if subtitles.current ~= nil and subtitles.current._sid ~= nil then
mp.commandv('sub_remove', subtitles.current._sid)
if options.autoFlagSubtitles then
flag_subtitle()
end
end
-- Move to the next subtitle
subtitles:next()
-- If at the end of the list (or no subtitles found), don't do anything
if subtitles.current == nil then
return
end
-- Load current subtitle
mp.osd_message(string.format(
"[%d/%d] Downloading subtitle…\n%s",
subtitles.idx, subtitles.count, subtitles.current.SubFileName
), options.osdDelayLong)
local filename = subtitles.current:download()
mp.commandv('sub_add', filename)
mp.osd_message(string.format(
"[%d/%d] Using subtitle (matched by %s)\n%s",
subtitles.idx, subtitles.count,
subtitles.current.MatchedBy, subtitles.current.SubFileName
), options.osdDelayShort)
-- Remember which track it is
subtitles.current._sid = mp.get_property('sid')
end
function flag_subtitle()
if subtitles.current ~= nil and subtitles.current.MatchedBy == 'moviehash' then
osdb.login(options.user, options.password)
mp.osd_message("Subtitle suggestion reported as incorrect",
options.osdDelayShort)
osdb.report(subtitles.current)
osdb.logout()
end
end
function catch(callback, ...)
xpcall(
callback,
function(err)
msg.warn(debug.traceback())
msg.fatal(err)
mp.osd_message("Error: " .. err, options.osdDelayShort)
end,
...
)
end
mp.add_key_binding('Ctrl+r', 'osdb_report', function() catch(flag_subtitle) end)
mp.add_key_binding('Ctrl+f', 'osdb_find_subtitles', function() catch(rotate_subtitles) end)
mp.register_event('file-loaded', function (event)
-- Reset the cache
subtitles:set({})
if options.autoLoadSubtitles then
catch(rotate_subtitles)
end
end)