-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathtrakt.lua
2902 lines (2579 loc) · 103 KB
/
trakt.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--[==========================================================================[
trakt.lua: Trakt.tv Interface for VLC
--[==========================================================================[
TraktForVLC, to link VLC watching to trakt.tv updating
Copyright (C) 2017-2018 Raphaël Beamonte <[email protected]>
$Id$
This file is part of TraktForVLC. TraktForVLC 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,
version 2.
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
or see <http://www.gnu.org/licenses/>.
--]==========================================================================]
-- TraktForVLC version
local __version__ = '0.0.0a0.dev0'
-- The location of the helper`
local path_to_helper
------------------------------------------------------------------------------
-- Local modules
------------------------------------------------------------------------------
-- The variable that will store the ospath module
local ospath = {}
-- The variable that will store the requests module
local requests = {}
-- The variable that will store the timers module
local timers = {}
-- The variable that will store the trakt module
local trakt = {}
-- The variable that will store the file module
local file = {}
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- LOAD DEPENDENCIES --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- To work with JSON data
local json = require('dkjson')
-- To do math operations
local math = require('math')
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- OSPATH MODULE TO PERFORM OPERATIONS ON PATHS --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Variables
------------------------------------------------------------------------------
-- The default separator for the current file system
ospath.sep = package.config:sub(1,1)
------------------------------------------------------------------------------
-- Function to return the path to the current lua script, this will not work
-- on all cases as some instances of VLC only return the script's name
------------------------------------------------------------------------------
function ospath.this()
return debug.getinfo(2, "S").source:sub(2)
end
------------------------------------------------------------------------------
-- Function to check if a path exists
------------------------------------------------------------------------------
function ospath.exists(path)
if type(path) ~= "string" then return false end
local ok, err, code = os.rename(path, path)
if not ok then
if code == 13 then
return true
end
end
return ok, err
end
------------------------------------------------------------------------------
-- Function to check if a path is a file
------------------------------------------------------------------------------
function ospath.isfile(path)
if type(path) ~= "string" then return false end
if not ospath.exists(path) then return false end
local f = io.open(path)
if f then
local ff = f:read(1)
f:close()
if not ff then
return false
end
return true
end
return false
end
------------------------------------------------------------------------------
-- Function to check if a path is a directory
------------------------------------------------------------------------------
function ospath.isdir(path)
return (ospath.exists(path) and not ospath.isfile(path))
end
------------------------------------------------------------------------------
-- Function to get the directory name from a path
------------------------------------------------------------------------------
function ospath.dirname(path)
local d = path:match("^(.*)" .. ospath.sep .. "[^" .. ospath.sep .. "]*$")
if not d or d == '' then
return path
end
return d
end
------------------------------------------------------------------------------
-- Function to get the base name from a path
------------------------------------------------------------------------------
function ospath.basename(path)
local b = path:match("^.*" .. ospath.sep ..
"([^" .. ospath.sep .. "]*)" ..
ospath.sep .. "?$")
if not b or b == '' then
return path
end
return b
end
------------------------------------------------------------------------------
-- Function to join multiple elements using the file system's separator
------------------------------------------------------------------------------
function ospath.join(...)
local arg
if type(...) == 'table' then
arg = ...
else
arg = {...}
end
local path
for _, p in pairs(arg) do
if not path or p.sub(1, 1) == ospath.sep then
path = p
else
if string.sub(path, -string.len(ospath.sep)) ~= ospath.sep then
path = path .. ospath.sep
end
path = path .. p
end
end
return path
end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- FUNCTIONS THAT ARE PROVIDING UTILITIES FOR THE REST OF THIS INTERFACE --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Sleeps for a given duration (in microseconds)
-- @param microseconds The duration in microseconds
------------------------------------------------------------------------------
local
function usleep(microseconds)
vlc.misc.mwait(vlc.misc.mdate() + microseconds)
end
------------------------------------------------------------------------------
-- Sleeps for a given duration (in seconds)
-- @param seconds The duration in seconds
------------------------------------------------------------------------------
local
function sleep(seconds)
usleep(seconds * 1000000)
end
------------------------------------------------------------------------------
-- Repeat a function every delay for a duration
-- @param delay The delay (in microseconds)
-- @param duration The duration (in microseconds)
-- @param func The function to execute
------------------------------------------------------------------------------
local
function ucallrepeat(delay, duration, func)
local repeat_until = vlc.misc.mdate() + duration
while vlc.misc.mdate() < repeat_until do
local ret = func()
if ret ~= nil then return ret end
vlc.misc.mwait(vlc.misc.mdate() + delay)
end
end
------------------------------------------------------------------------------
-- Repeat a function every delay for a duration
-- @param delay The delay (in seconds)
-- @param duration The duration (in seconds)
-- @param func The function to execute
------------------------------------------------------------------------------
local
function callrepeat(delay, duration, func)
return ucallrepeat(delay * 1000000, duration * 1000000, func)
end
------------------------------------------------------------------------------
-- Dumps the object passed as argument recursively and returns a string that
-- can then be printed.
-- @param o The object to dump
-- @param lvl The current level of indentation
------------------------------------------------------------------------------
local dump_func_path = {}
local
function dump(o,lvl)
local lvl = lvl or 0
local indent = ''
for i=1,lvl do indent = indent .. '\t' end
if type(o) == 'table' then
local s = '{\n'
for k,v in pairs(o) do
if type(k) == 'function' then
if not dump_func_path[k] then
finf = debug.getinfo(k)
dump_func_path[k] = string.gsub(
finf['source'], "(.*/)(.*)", "%2") ..
':' .. finf['linedefined']
end
k = '"' .. dump_func_path[k] .. '"'
elseif type(k) ~= 'number' then
k = '"' .. k .. '"'
end
s = s .. indent .. '\t[' .. k .. '] = ' ..
dump(v, lvl+1) .. ',\n'
end
return s .. indent .. '}'
elseif type(o) == 'string' then
return '"' .. o .. '"'
else
return tostring(o)
end
end
-- Taken from https://stackoverflow.com/questions/20325332/how-to-check-if-
-- two-tablesobjects-have-the-same-value-in-lua
------------------------------------------------------------------------------
-- Performs a deep comparison that can be applied on tables
-- @param o1 The first object to compare
-- @param o2 The second object to compare
-- @param ignore_mt Whether or not to ignore the built-in equal method
------------------------------------------------------------------------------
local
function equals(o1, o2, ignore_mt)
if o1 == o2 then return true end
local o1Type = type(o1)
local o2Type = type(o2)
if o1Type ~= o2Type then return false end
if o1Type ~= 'table' then return false end
if not ignore_mt then
local mt1 = getmetatable(o1)
if mt1 and mt1.__eq then
--compare using built in method
return o1 == o2
end
end
local keySet = {}
for key1, value1 in pairs(o1) do
local value2 = o2[key1]
if value2 == nil or equals(value1, value2, ignore_mt) == false then
return false
end
keySet[key1] = true
end
for key2, _ in pairs(o2) do
if not keySet[key2] then return false end
end
return true
end
-- Taken from http://trac.opensubtitles.org/projects/opensubtitles/wiki/
-- HashSourceCodes#Lua
------------------------------------------------------------------------------
-- Allows to get the hash that can then be used on opensubtitles to perform a
-- research for the file information
-- @param fileName The path to the filename for which to compute the hash
------------------------------------------------------------------------------
local
function movieHash(fileName)
local fil, err = io.open(fileName, 'rb')
if not fil then
vlc.msg.debug('Error opening file \'' .. fileName .. '\': ' ..
err .. '; media hash will not be resolved.')
return
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
-- Taken from https://stackoverflow.com/questions/11163748/open-web-browser-
-- using-lua-in-a-vlc-extension
------------------------------------------------------------------------------
-- Open an URL in the client browser
-- @param url The URL to open
------------------------------------------------------------------------------
local open_cmd
local
function open_url(url)
if not open_cmd then
if package.config:sub(1,1) == '\\' then -- windows
open_cmd = function(url)
-- Should work on anything since (and including) win'95
os.execute(string.format('start "%s"', url))
end
-- the only systems left should understand uname...
elseif (io.popen("uname -s"):read'*a') == "Darwin" then -- OSX/Darwin ? (I can not test.)
open_cmd = function(url)
-- I cannot test, but this should work on modern Macs.
os.execute(string.format('open "%s"', url))
end
else -- that ought to only leave Linux
open_cmd = function(url)
-- should work on X-based distros.
os.execute(string.format('xdg-open "%s"', url))
end
end
end
open_cmd(url)
end
------------------------------------------------------------------------------
-- Function to get the path to the helper if not provided
------------------------------------------------------------------------------
function get_helper()
local search_in = {}
local trakt_helper
-- Check first if we don't have any configuration value telling us where
-- the helper is located
local cfg_location = {}
-- Or as an environment variable
if os.getenv('TRAKT_HELPER') and os.getenv('TRAKT_HELPER') ~= '' then
table.insert(cfg_location, os.getenv('TRAKT_HELPER'))
end
-- Or, most common way, in the module's configuration
if trakt.config and
trakt.config.helper and
trakt.config.helper.location and
trakt.config.helper.location ~= '' then
table.insert(cfg_location, trakt.config.helper.location)
end
-- If we have any of those indication, try to use it
for _, v in pairs(cfg_location) do
if v then
if v == '~' or string.sub(v, 1, 2) == '~/' then
v = ospath.join(vlc.config.homedir(),
string.sub(v, 3))
elseif os.getenv('PWD') and (
(ospath.sep == '/' and
string.sub(v, 1, 1) ~= '/') or
(ospath.sep == '\\' and
not string.match(v, '^[a-zA-Z]:\\'))) then
v = ospath.join(os.getenv('PWD'), v)
end
if not ospath.exists(v) then
vlc.msg.err('File not found: ' .. v)
return
elseif ospath.isdir(v) then
table.insert(search_in, v)
break
else
trakt_helper = v
break
end
end
end
-- Else, fall back on searching manually, first in VLC's
-- config directory for any local install, else on the
-- lua directory if we got enough information to do it
if not trakt_helper then
for _, dir in ipairs(vlc.config.datadir_list('')) do
table.insert(search_in, dir)
end
local files = {
'trakt_helper',
'trakt_helper.exe',
'trakt_helper.py',
}
for _, d in pairs(search_in) do
for _, f in pairs(files) do
fp = ospath.join(d, f)
if ospath.isfile(fp) then
return fp
end
end
end
end
return trakt_helper
end
------------------------------------------------------------------------------
-- Function to facilitate the calls to perform to the helper
-- @param args The command line arguments to be sent to the helper
------------------------------------------------------------------------------
local
function call_helper(args, discard_stderr)
if trakt.config.helper.mode ~= 'service' then
-- Add the helper path to the beginning of the args
table.insert(args, 1, path_to_helper)
end
-- Escape the arguments
for k, v in pairs(args) do
v = v:gsub('\\"', '\\\\\\"')
v = v:gsub('"', '\\"')
v = '"' .. v .. '"'
args[k] = v
end
-- Concatenate them to generate the command
local command = table.concat(args, ' ')
vlc.msg.dbg('(call_helper) Executing command: ' .. command)
local response
local exit_code
if trakt.config.helper.mode == 'service' then
local maxtry = 1
local try = 0
while try < maxtry do
try = try + 1
local sent = -2
local fd = vlc.net.connect_tcp(trakt.config.helper.service.host,
trakt.config.helper.service.port)
if fd then
sent = vlc.net.send(fd, command .. '\n')
end
if not fd then
vlc.msg.err('Unable to connect to helper on ' ..
trakt.config.helper.service.host .. ':' ..
trakt.config.helper.service.port)
elseif sent < 0 then
vlc.msg.err('Unable to send request to helper on ' ..
trakt.config.helper.service.host .. ':' ..
trakt.config.helper.service.port)
vlc.net.close(fd)
else
local pollfds = {
[fd] = vlc.net.POLLIN,
}
vlc.net.poll(pollfds)
response = ""
local buf = vlc.net.recv(fd, 2048)
-- Get the rest of the message
while buf and #buf > 0 do
vlc.msg.dbg('Reading buffer; content = ' .. buf)
response = response .. buf
vlc.net.poll(pollfds)
buf = vlc.net.recv(fd, 2048)
end
-- Close the connection
vlc.net.close(fd)
-- Try and get the exit code
vlc.msg.dbg('Received data before parsing = ' .. response)
exit_code, response = response:match('^Exit: (-?[0-9]+)\n(.*)')
if exit_code ~= nil then
vlc.msg.dbg('Parsed EXIT_CODE = ' .. exit_code)
vlc.msg.dbg('Parsed RESPONSE = ' .. response)
exit_code = tonumber(exit_code)
break
end
end
end
if not response then
vlc.msg.err('Unable to get command output')
return nil
end
elseif ospath.sep == '\\' then
vlc.msg.err('Only the service mode is available on Windows. ' ..
'Standalone mode pops up a window every few ' ..
'seconds... Who would have thought \'Windows\' ' ..
'was so literal?! ;(')
return nil
else
if not discard_stderr then
command = command .. ' 2>&1'
end
-- Run the command, and get the output
local fpipe = assert(io.popen(command, 'r'))
response = assert(fpipe:read('*a'))
local closed, exit_reason, exit_code = fpipe:close()
-- Lua 5.1 do not manage properly exit codes when using io.popen,
-- so if we are using Lua 5.1, or if the exit code is 'nil', we
-- will skip that step of checking the exit code. In any case,
-- if there was an issue, the json parsing will fail and we will
-- be able to catch that error
if _VERSION == 'Lua 5.1' then
exit_code = nil
end
end
if exit_code ~= nil and exit_code ~= 0 then
-- We got a problem...
vlc.msg.err('(call_helper) Command: ' .. command)
vlc.msg.err('(call_helper) Command exited with code ' .. tostring(exit_code))
vlc.msg.err('(call_helper) Command output: ' .. response)
return nil
end
vlc.msg.dbg('(call_helper) Received response: ' .. tostring(response))
-- Decode the JSON returned as response, and check for errors
local obj, pos, err = json.decode(response)
if err then
vlc.msg.err('(call_helper) Command: ' .. command)
vlc.msg.err('(call_helper) Unable to parse json')
vlc.msg.err('(call_helper) Command output: ' .. response)
return nil
end
-- Return the response object
return obj
end
------------------------------------------------------------------------------
-- Function to merge a number of intervals provided in the parameter, in order
-- to get the lowest number of internals that cover the same area as all the
-- previous intervals
------------------------------------------------------------------------------
local
function merge_intervals(data)
-- Sort the data
table.sort(
data,
function(a, b)
return (a.from < b.from or
(a.from == b.from and a.to < b.to))
end
)
-- Prepare local variables
local merged = {}
local current = nil
-- Go through the intervals to merge them together
for k, intv in pairs(data) do
if current and intv.from <= current.to then
current.to = math.max(intv.to, current.to)
else
if current then
table.insert(merged, current)
end
current = intv
end
end
-- If we have a current data, merge it
if current then
table.insert(merged, current)
end
-- Return the merged intervals
return merged
end
------------------------------------------------------------------------------
-- Function that sums the data represented in form of intervals; the sum
-- represents the total area covered by the entirety of the intervals
------------------------------------------------------------------------------
local
function sum_intervals(data)
local sum = 0
for k, intv in pairs(data) do
sum = sum + (intv.to - intv.from)
end
return sum
end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- FUNCTIONS PROVIDING TIMER FACILITIES --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Variables
------------------------------------------------------------------------------
-- The table containing the registered timers
timers._registered = {}
------------------------------------------------------------------------------
-- To register a timer
-- @param func The function to run
-- @param delay The delay to run that function
------------------------------------------------------------------------------
function timers.register(func, delay, expire)
-- If delay is nil, unregister the timer
if delay == nil then
timers._registered[func] = nil
return
end
timers._registered[func] = {
['delay'] = delay,
['last'] = -1,
['expire'] = expire,
}
end
------------------------------------------------------------------------------
-- To run the timers that need to be run, will return the list of timers with
-- 'true' or 'false' as value whether or not they have been run
------------------------------------------------------------------------------
function timers.run()
ran_timers = {}
cur_time = vlc.misc.mdate()
for f, d in pairs(timers._registered) do
-- If the timer expired, remove it
if d['expire'] and d['expire'] < cur_time then
timers._registered[f] = nil
-- If we haven't passed the delay to run the timer, don't run it
elseif d['last'] + d['delay'] > cur_time then
ran_timers[f] = false
-- Else, we can run the timer and update the information
else
f()
timers._registered[f]['last'] = cur_time
ran_timers[f] = true
end
end
return ran_timers
end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- FUNCTIONS PROVIDING HTTP REQUESTS FACILITIES --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- To perform a HTTP request
-- @param method The method to use for the request
-- @param url The URL to perform the request to
-- @param headers The headers to define for the request
-- @param body The body of the request
-- @param getbody Whether or not to return the body of the response
------------------------------------------------------------------------------
function requests.http_request(...)
--------------------------------------------------------------------------
-- Parse the arguments to allow either positional args or named args
local method, url, headers, body, getbody
if type(...) == 'table' then
local args = ...
method = args.method or args[1]
url = args.url or args[2]
headers = args.headers or args[3]
body = args.body or args[4]
else
method, url, headers, body, getbody = ...
end
--------------------------------------------------------------------------
-- Perform checks on the arguments
if not method then
error({message='No method provided'})
end
method = string.upper(method)
if not url then
error({message='No URL provided for ' .. method .. ' request'})
end
headers = headers or {}
headers['User-Agent'] = 'TraktForVLC ' .. __version__ ..
'/VLC ' .. vlc.misc.version()
--------------------------------------------------------------------------
-- Function logic
-- Prepare the arguments to call the helper
args = {
'requests',
method,
url,
}
if headers then
table.insert(args, '--headers')
table.insert(args, json.encode(headers))
end
if body then
table.insert(args, '--data')
table.insert(args, json.encode(body))
end
-- Return the response object
return call_helper(args)
end
------------------------------------------------------------------------------
-- To perform a HTTP GET request
-- @param url The URL to perform the request to
-- @param headers The headers to define for the request
------------------------------------------------------------------------------
function requests.get(...)
-- Parse the arguments to allow either positional args or named args
local url, headers
if type(...) == 'table' then
local args = ...
url = assert(args.url or args[1])
headers = assert(args.headers or args[2])
else
url, headers = ...
end
-- Function logic
return requests.http_request{
method='GET',
url=url,
headers=headers,
}
end
------------------------------------------------------------------------------
-- To perform a HTTP POST request
-- @param url The URL to perform the request to
-- @param headers The headers to define for the request
------------------------------------------------------------------------------
function requests.post(...)
-- Parse the arguments to allow either positional args or named args
local url, headers, body
if type(...) == 'table' then
local args = ...
url = assert(args.url or args[1])
headers = assert(args.headers or args[2])
body = assert(args.body or args[3])
else
url, headers, body = ...
end
-- Function logic
return requests.http_request{
method='POST',
url=url,
headers=headers,
body=body,
}
end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- FUNCTIONS TO MANAGE THE CONFIGURATION FILE OF THE INTERFACE --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Variables
------------------------------------------------------------------------------
-- Variable to store the path to the configuration file
local config_file = ospath.join(vlc.config.configdir(), 'trakt_config.json')
-- Variable to store the path to the cache file
local cache_file = ospath.join(vlc.config.configdir(), 'trakt_cache.json')
-- Last cache save time
local last_cache_save = -1
------------------------------------------------------------------------------
-- Returns the JSON data read from the file at filepath
-- @param filepath The path to the file to read the data from
-- @param default The default data returned if there is an error
------------------------------------------------------------------------------
function file.get_json(filepath, default)
local data = {}
local file = io.open(filepath, 'r')
if file then
data = json.decode(file:read('*a'))
file:close()
if type(data) == 'table' then
return data
else
vlc.msg.err('(file.get_json) JSON file not in the right format')
end
else
vlc.msg.info('No JSON file found at ' .. filepath)
end
return default
end
------------------------------------------------------------------------------
-- Writes the JSON passed as argument to the file at filepath
-- @param filepath The path to the file to write the data to
-- @param data The table containing the JSON data to write
------------------------------------------------------------------------------
function file.save_json(filepath, data)
local file = io.open(filepath, 'w')
if file then
local jsondata = json.encode(data, { indent = true })
vlc.msg.dbg('Writing to ' .. filepath .. ': ' .. dump(jsondata))
file:write(jsondata)
file:close()
else
error('Error opening the file ' .. filepath .. ' to save')
end
end
------------------------------------------------------------------------------
-- Returns the configuration read from the configuration file
------------------------------------------------------------------------------
local
function get_config()
local lconfig = file.get_json(config_file, {})
-- =======================================================================
-- The version of TraktForVLC that generated the configuration file
-- (present for retrocompatibility purposes)
if not lconfig.config_version then
lconfig.config_version = __version__
end
-- =======================================================================
-- Configuration relative to the media cache used by TraktForVLC
if not lconfig.cache then
lconfig.cache = {}
end
-- The delays for operations performed on the media cache
if not lconfig.cache.delay then
lconfig.cache.delay = {}
end
-- Delay (in seconds) between save operations on the cache
if not lconfig.cache.delay.save then
lconfig.cache.delay.save = 30 -- 30 seconds
end
-- Delay (in seconds) between cleanup operations on the cache
if not lconfig.cache.delay.cleanup then
lconfig.cache.delay.cleanup = 60 -- 60 seconds
end
-- Time (in seconds) after which an unused entry in the cache expires
if not lconfig.cache.delay.expire then
lconfig.cache.delay.expire = 2592000 -- 30 days
end
-- =======================================================================
-- Configuration relative to media resolution and scrobbling
if not lconfig.media then
lconfig.media = {}
end
-- -----------------------------------------------------------------------
-- Configuration relative to media resolution
if not lconfig.media.info then
lconfig.media.info = {}
end
-- Maximum number of times we will try to resolve the current watched
-- item through IMDB
if not lconfig.media.info.max_try then
lconfig.media.info.max_try = 10
end
-- Delay factor (in seconds) between try attempts; if try_delay_factor
-- is f and attempt is n, next try will be after n*f seconds
if not lconfig.media.info.try_delay_factor then
lconfig.media.info.try_delay_factor = 30 -- 30 seconds
end
-- -----------------------------------------------------------------------
-- Configuration relative to media watching status
if not lconfig.media.start then
lconfig.media.start = {}
end
-- Time after which a media will be marked as being watched on trakt.tv
if not lconfig.media.start.time then
lconfig.media.start.time = 30 -- 30 seconds
end
-- Percentage of the media watched after which the media will be marked
-- as being watched on trakt.tv
if not lconfig.media.start.percent then
lconfig.media.start.percent = .25 -- 0.25%
end
-- Whether or not to mark movies as being watched
if not lconfig.media.start.movie then
lconfig.media.start.movie = true
end
-- Whether or not to mark episodes as being watched
if not lconfig.media.start.episode then
lconfig.media.start.episode = true
end
-- -----------------------------------------------------------------------
-- Configuration relative to media scrobbling
if not lconfig.media.stop then
lconfig.media.stop = {}
end
-- The minimum watched percent for a media to be scrobbled as seen on
-- trakt.tv; i.e. you must have watched at least that percentage of
-- the media, for it to be scrobbled
if not lconfig.media.stop.watched_percent then
lconfig.media.stop.watched_percent = 50 -- 50%
end
-- The minimum percentage of the media duration at which you must
-- currently be for the media to be scrobbled as seen (if the media
-- has a duration of 100mn, and you configured the percent as 90,
-- you must at least be at the 90th minute of the media)
if not lconfig.media.stop.percent then
lconfig.media.stop.percent = 90 -- 90%
end
-- Whether or not to scrobble movies as watched
if not lconfig.media.stop.movie then
lconfig.media.stop.movie = true
end