-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.py
More file actions
734 lines (617 loc) · 25.9 KB
/
main.py
File metadata and controls
734 lines (617 loc) · 25.9 KB
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
# Copyright (C) 2023, lbnt
#
# 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 3 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, see <https://www.gnu.org/licenses/>.
import os
import sys
from urllib.parse import urlencode, parse_qsl
import json
import datetime
import xbmc
import xbmcgui
import xbmcplugin
from xbmcaddon import Addon
from xbmcvfs import translatePath, mkdir
import requests
import requests_cache
import StorageServer
#import web_pdb;
# Get the plugin url in plugin:// notation.
URL = sys.argv[0]
# Get a plugin handle as an integer number.
HANDLE = int(sys.argv[1])
# Get addon base path
ADDON_PATH = translatePath(Addon().getAddonInfo('path'))
ICONS_DIR = os.path.join(ADDON_PATH, 'resources', 'images', 'icons')
FANART_DIR = os.path.join(ADDON_PATH, 'resources', 'images', 'fanart')
#TMDB url for poster and fanart
TMDB_IMAGE_BASE_URL = "https://image.tmdb.org/t/p/w500"
GENRES = {
28: "Action",
12: "Adventure",
16: "Animation",
35: "Comedy",
80: "Crime",
99: "Documentary",
18: "Drama",
10751: "Family",
14: "Fantasy",
36: "History",
27: "Horror",
10402: "Music",
9648: "Mystery",
10749: "Romance",
878: "Science Fiction",
10770: "TV Movie",
53: "Thriller",
10752: "War",
37: "Western"
}
#global tmdb to local dbid index
tmdb_index = {}
def get_url(**kwargs):
"""
Create a URL for calling the plugin recursively from the given set of keyword arguments.
"""
return '{}?{}'.format(URL, urlencode(kwargs))
def list_folders(folder_list):
"""
Create the list of folders in the Kodi interface.
"""
if folder_list == None:
return
#get the folders!
folders = folder_list['folders']
# Set subtitle
xbmcplugin.setPluginCategory(HANDLE, folder_list['title'])
# Set plugin content
xbmcplugin.setContent(HANDLE, 'movies')
xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_UNSORTED)
# Iterate through folders
for folder in folders:
title = folder["title"]
# Create a list item with a text label.
list_item = xbmcgui.ListItem(label=title)
# Set additional info for the list item using its InfoTag.
info_tag = list_item.getVideoInfoTag()
info_tag.setMediaType('set')
info_tag.setTitle(title)
# Create a URL for a plugin recursive call.
if folder["type"] == "folder_list":
url = get_url(action='list_folders', id=folder["id"])
elif folder["type"] == "movie_list":
url = get_url(action='list_movies', id=folder["id"])
# is_folder = True means that this item opens a sub-list of lower level items.
is_folder = True
# Add our item to the Kodi virtual folder listing.
xbmcplugin.addDirectoryItem(HANDLE, url, list_item, is_folder)
# Finish creating a virtual folder.
xbmcplugin.endOfDirectory(HANDLE)
def build_tmdbid_to_dbid_index():
"""
Get a mapping of TMDB IDs to local database IDs for all movies in the library.
Returns a dictionary where keys are TMDB IDs and values are local database IDs.
"""
#Construct the JSON-RPC query
json_query = {
"jsonrpc": "2.0",
"method": "VideoLibrary.GetMovies",
"params": {
"properties": ["uniqueid"]
},
"id": "libMovies"
}
# Notify user about index building
xbmcgui.Dialog().notification('jlom', 'Building movies index...', xbmcgui.NOTIFICATION_INFO)
# Execute the JSON-RPC query
response = xbmc.executeJSONRPC(json.dumps(json_query))
# Parse the response
result = json.loads(response)
"""Build a dict {tmdb: movieid}."""
nbmissingids = 0
index = {}
for movie in result.get("result", {}).get("movies", []):
uniqueid = movie.get("uniqueid")
if not isinstance(uniqueid, dict): # uniqueid is missing or not a dict
nbmissingids += 1
continue
tmdbid = uniqueid.get("tmdb")
if tmdbid is None: # tmdb id is missing
nbmissingids += 1
continue
movieid = movie.get("movieid")
if movieid is not None:
index[tmdbid] = movieid
if nbmissingids > 0:
xbmcgui.Dialog().notification('jlom', f'{nbmissingids} movies don\'t have a tmdb id\n and won\'t be found in the lists!', xbmcgui.NOTIFICATION_WARNING, 10000)
return index
def play_media(dbid):
#clear the playlist
xbmc.PlayList(xbmc.PLAYLIST_VIDEO).clear()
#close all dialogs
xbmc.executebuiltin('Dialog.Close(all,true)')
#use videodb path for direct play
path = f'videodb://movies/titles/{dbid}'
#play item
play_item = xbmcgui.ListItem(path=path,offscreen=True)
play_item.setProperty('IsPlayable', "true")
xbmcplugin.setResolvedUrl(HANDLE, True, listitem=play_item)
def get_movie_details(id):
#Construct the JSON-RPC query
json_query = {
"jsonrpc": "2.0",
"method": "VideoLibrary.GetMovieDetails",
"params": {
"movieid": id,
"properties": [
"title",
"genre",
"year",
"rating",
"director",
"trailer",
"tagline",
"plot",
"plotoutline",
"originaltitle",
"lastplayed",
"playcount",
"writer",
"studio",
"mpaa",
"cast",
"country",
"imdbnumber",
"runtime",
"set",
"showlink",
"streamdetails",
"top250",
"votes",
"fanart",
"thumbnail",
"file",
"sorttitle",
"resume",
"setid",
"dateadded",
"tag",
"art",
"userrating",
"ratings",
"premiered",
"uniqueid"
]
},
"id": "1"
}
# Execute the JSON-RPC query
response = xbmc.executeJSONRPC(json.dumps(json_query))
# Parse the response
result = json.loads(response)
return result
def list_movies(movie_list):
"""
Create the list of movies in the Kodi interface.
"""
if movie_list == None:
return
#get the movies!
movies = movie_list["movies"]
ordered_by = movie_list["ordered_by"]
# Read the "hide not in library" setting once for the whole list
hide_not_in_library = Addon().getSettingBool('hide_not_in_library')
# Set subtitle
xbmcplugin.setPluginCategory(HANDLE, movie_list['title'])
# Set plugin content
xbmcplugin.setContent(HANDLE, 'movies')
if ordered_by == "":
xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_NONE) #default
xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_TITLE)
xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_VIDEO_YEAR)
elif ordered_by == "rank":
xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_UNSORTED) #default
xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_VIDEO_YEAR)
xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_TITLE)
elif ordered_by == "year":
xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_VIDEO_YEAR)#default
xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_TITLE)
# Iterate through movies.
for index, movie in enumerate(movies):
#try to find the movie in the local database using the tmdb index
local_id = tmdb_index.get(str(movie['id']))
# Skip movies not in the local library if the setting is enabled
if local_id is None and hide_not_in_library:
continue
# Create a list item with a text label
if ordered_by == "rank":
movie_label = str(index+1) + " - " + movie['title']
else:
movie_label = movie['title']
list_item = xbmcgui.ListItem(label= movie_label)
# Set graphics (thumbnail, fanart, banner, poster, landscape etc.) for the list item.
if movie['poster_path'] != None:
list_item.setArt({'poster': TMDB_IMAGE_BASE_URL+movie['poster_path']})
if movie['backdrop_path'] != None:
list_item.setArt({'fanart': TMDB_IMAGE_BASE_URL+movie['backdrop_path']})
# Set additional info for the list item via InfoTag.
info_tag = list_item.getVideoInfoTag()
info_tag.setMediaType('movie')
info_tag.setTitle(movie['title'])
info_tag.setOriginalTitle(movie['original_title'])
info_tag.setYear(int(movie['release_date'][0:4]) if movie['release_date'] != "" else None)
genres = []
for genre_id in movie.get("genre_ids", []):
genres.append(GENRES.get(genre_id, "Unknown"))
info_tag.setGenres(genres)
info_tag.setPlot(movie['overview'])
#if found, make it playable
if local_id != None :
#get the movie details from the db
movie_details = get_movie_details(local_id).get("result", {}).get("moviedetails", {})
#set info from db
info_tag.setDbId(int(local_id))
info_tag.setPath(f'videodb://movies/titles/{local_id}')
info_tag.setTitle(movie_details.get("title"))
info_tag.setGenres(movie_details.get("genre"))
info_tag.setYear(movie_details.get("year"))
info_tag.setRating(movie_details.get("rating"))
info_tag.setDirectors(movie_details.get("director"))
info_tag.setTrailer(movie_details.get("trailer"))
info_tag.setTagLine(movie_details.get("tagline"))
info_tag.setPlot(movie_details.get("plot"))
info_tag.setPlotOutline(movie_details.get("plotoutline"))
info_tag.setOriginalTitle(movie_details.get("originaltitle"))
info_tag.setLastPlayed(movie_details.get("lastplayed"))
info_tag.setPlaycount(movie_details.get("playcount"))
info_tag.setWriters(movie_details.get("writer"))
info_tag.setStudios(movie_details.get("studio"))
info_tag.setMpaa(movie_details.get("mpaa"))
actors = []
for actor in movie_details.get("cast"):
actors.append(xbmc.Actor(actor.get("name"), actor.get("role"), actor.get("order"), actor.get("thumbnail")))
info_tag.setCast(actors)
info_tag.setCountries(movie_details.get("country"))
info_tag.setIMDBNumber(movie_details.get("imdbnumber"))
info_tag.setDuration(movie_details.get("runtime"))
info_tag.setSet(movie_details.get("set"))
info_tag.setShowLinks(movie_details.get("showlink"))
#stream details
info_tag.setTop250(movie_details.get("top250"))
info_tag.setVotes(int(movie_details.get("votes")))
#fanart and thumbnail
info_tag.setFilenameAndPath(movie_details.get("file"))
info_tag.setSortTitle(movie_details.get("sorttitle"))
info_tag.setResumePoint(movie_details.get("resume").get("position"), movie_details.get("resume").get("total"))
info_tag.setSetId(movie_details.get("setid"))
info_tag.setDateAdded(movie_details.get("dateadded"))
info_tag.setTags(movie_details.get("tag"))
#art
info_tag.setUserRating(movie_details.get("userrating"))
#info_tag.setRatings(...) # todo: implement
info_tag.setPremiered(movie_details.get("premiered"))
info_tag.setUniqueIDs(movie_details.get("uniqueid"))
#difference between available and not available item
list_item.setProperty('IsPlayable', 'true')
if ordered_by == "rank":
info_tag.setTagLine("Ranked %s" % (str(index +1)))
# Direct play url
url = f'videodb://movies/titles/{local_id}'
#if not ...
else:
list_item.setProperty('IsPlayable', 'false')
if ordered_by == "rank":
info_tag.setTagLine("Ranked %s\n" % (str(index +1)) + "Not in your libray")
else:
info_tag.setTagLine("Not in your libray")
#set unique id, useful for other addons
info_tag.setUniqueIDs({'tmdb': str(movie['id'])})
# recursive call to offer to search using global search addon
url = get_url(action='other_action', id=movie['id'], title=movie['original_title'])
# Add the list item to a virtual Kodi folder.
is_folder = False
# Add our item to the Kodi virtual folder listing.
xbmcplugin.addDirectoryItem(HANDLE, url, list_item, is_folder)
# Finish creating a virtual folder.
xbmcplugin.endOfDirectory(HANDLE)
def get_local_list(list_type, list_id):
"""
Get a list from the local filesystem
"""
list_path = os.path.join(ADDON_PATH, 'resources', 'lists', list_type, f"{list_id}.json")
xbmc.log(f'list path: {list_path}',level=xbmc.LOGDEBUG)
try:
with open(list_path, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception as e:
xbmc.log("Error reading local list file", level=xbmc.LOGERROR)
raise
def get_distant_list(list_type, list_id):
"""
Get a list from the configured URL
"""
list_url = Addon().getSettingString('lists_url')
list_url = list_url if list_url.endswith('/') else list_url + '/'
list_url += f"{list_type}/{list_id}.json"
xbmc.log(f'list url: {list_url}',level=xbmc.LOGDEBUG)
try:
response = requests.get(list_url, timeout=5)
#log if response was from cache
from_cache = getattr(response, 'from_cache', False)
xbmc.log(f'GitHub requests cached: {from_cache}',level=xbmc.LOGDEBUG)
except requests.exceptions.RequestException as e:
xbmc.log("Error requesting list url",level=xbmc.LOGERROR)
raise
else:
if response.status_code == 200:
return json.loads(response.text)
else:
return None
def get_list(list_type, list_id):
"""
Get a list, either from the local filesystem or from the configured URL depending on the settings.
"""
if Addon().getSettingBool('lists_source') == True:
return get_local_list(list_type, list_id)
else:
return get_distant_list(list_type, list_id)
def radarr_add_movie(movie_data):
"""
Add a movie to Radarr
"""
# Get Radarr URL and API token from addon settings
radarr_url = Addon().getSettingString('radarr_url')
radarr_token = Addon().getSettingString('radarr_token')
# Build the API endpoint URL
api_url = radarr_url if radarr_url.endswith('/') else radarr_url + '/'
api_url += "api/v3/movie"
# Set request headers with API key
headers = {
'X-Api-Key': radarr_token
}
try:
# Send POST request to Radarr to add the movie
response = requests.post(api_url, headers=headers, json=movie_data, timeout=5)
except requests.exceptions.RequestException as e:
# Log error if request fails
xbmc.log("Error adding movie to Radarr : exception", level=xbmc.LOGERROR)
xbmc.log(f"{e}", level=xbmc.LOGERROR)
return False
else:
# Success: movie added (HTTP 200 or 201)
if response.status_code in [200, 201]:
xbmc.log("Movie added to Radarr")
xbmcgui.Dialog().notification('Radarr', 'Movie added successfully', xbmcgui.NOTIFICATION_INFO)
return True
# Bad request (HTTP 400)
elif response.status_code == 400:
data = response.json()
error_message = data[0].get('errorMessage')
# Movie may already exist
if error_message == "This movie has already been added":
xbmc.log("Movie already exists in Radarr")
xbmcgui.Dialog().notification('Radarr', 'Movie already exists in Radarr', xbmcgui.NOTIFICATION_INFO)
# Other errors
else:
xbmcgui.Dialog().notification('Radarr', 'Failed to add movie to Radarr', xbmcgui.NOTIFICATION_ERROR)
xbmc.log(f"Failed to add movie to Radarr: {error_message}")
return False
else:
xbmcgui.Dialog().notification('Radarr', 'Failed to add movie to Radarr', xbmcgui.NOTIFICATION_ERROR)
xbmc.log(f"Failed to add movie to Radarr: {response.status_code} - {response.text}")
return False
def radarr_add_movie_dialogs(id):
"""
Add a movie to Radarr with user dialogs for folder and quality selection.
"""
# Check Radarr connection before proceeding
if not radarr_check_connection():
xbmcgui.Dialog().notification('Radarr', 'Connection failed', xbmcgui.NOTIFICATION_ERROR)
return
# Ask user to select a root folder for the movie
root_folder_path = radarr_root_folders_dialog()
if root_folder_path is None:
xbmcgui.Dialog().notification('Radarr', 'No root folder selected', xbmcgui.NOTIFICATION_ERROR)
return
# Ask user to select a quality profile for the movie
quality_profile_id = radarr_quality_profiles_dialog()
if quality_profile_id is None:
xbmcgui.Dialog().notification('Radarr', 'No quality profile selected', xbmcgui.NOTIFICATION_ERROR)
return
# Prepare movie data for Radarr API
movie_data = {
'tmdbId': id, # The TMDB ID of the movie
'rootFolderPath': root_folder_path, # Selected root folder path
'qualityProfileId': str(quality_profile_id), # Selected quality profile ID
'monitored': True, # Monitor the movie for downloads
'addOptions': {'searchForMovie': True} # Search for the movie after adding
}
# Send the request to add the movie to Radarr
return radarr_add_movie(movie_data)
def radarr_check_connection():
"""
Check Radarr connection by requesting system status endpoint.
Returns True if connection is successful, False otherwise.
"""
# Get Radarr URL and API token from addon settings
radarr_url = Addon().getSettingString('radarr_url')
radarr_token = Addon().getSettingString('radarr_token')
# Build the API endpoint URL for system status
api_url = radarr_url if radarr_url.endswith('/') else radarr_url + '/'
api_url += "api/v3/system/status"
# Set request headers with API key
headers = {
'X-Api-Key': radarr_token
}
try:
# Send GET request to Radarr system status endpoint
with requests_cache.disabled(): #disable caching for this request
response = requests.get(api_url, headers=headers, timeout=5)
except requests.exceptions.RequestException as e:
# Log error if request fails
xbmc.log("Error requesting Radarr status", level=xbmc.LOGERROR)
return False
else:
# Return True if status code is 200 (OK), otherwise False
if response.status_code == 200:
return True
else:
return False
def radarr_get_root_folders():
"""
Get the list of Radarr root folders from the Radarr API.
Returns a list of root folder objects or None if the request fails.
"""
# Get Radarr URL and API token from addon settings
radarr_url = Addon().getSettingString('radarr_url')
radarr_token = Addon().getSettingString('radarr_token')
# Build the API endpoint URL for root folders
api_url = radarr_url if radarr_url.endswith('/') else radarr_url + '/'
api_url += "api/v3/rootfolder"
# Set request headers with API key
headers = {
'X-Api-Key': radarr_token
}
try:
# Send GET request to Radarr root folders endpoint
with requests_cache.disabled(): #disable caching for this request
response = requests.get(api_url, headers=headers, timeout=5)
except requests.exceptions.RequestException as e:
xbmc.log("Error requesting Radarr root folders", level=xbmc.LOGERROR)
raise
else:
# Return list of root folders if status code is 200 (OK)
if response.status_code == 200:
return json.loads(response.text)
else:
return None
def radarr_root_folders_dialog():
"""
Show a dialog to select a Radarr root folder.
Returns the selected folder path or None if cancelled or error.
"""
# Get root folders from Radarr
root_folders = radarr_get_root_folders()
if root_folders is None:
xbmcgui.Dialog().notification('Radarr', 'Error retrieving root folders', xbmcgui.NOTIFICATION_ERROR)
return None
# Extract folder paths for display
folder_paths = [folder['path'] for folder in root_folders]
dialog = xbmcgui.Dialog()
# Show selection dialog
selected = dialog.select('Select Root Folder', folder_paths)
# Return selected folder path or None if cancelled
if selected == -1:
return None
else:
return root_folders[selected]['path']
def radarr_get_quality_profiles():
"""
Get the list of Radarr quality profiles from the Radarr API.
Returns a list of quality profile objects or None if the request fails.
"""
# Get Radarr URL and API token from addon settings
radarr_url = Addon().getSettingString('radarr_url')
radarr_token = Addon().getSettingString('radarr_token')
# Build the API endpoint URL for quality profiles
api_url = radarr_url if radarr_url.endswith('/') else radarr_url + '/'
api_url += "api/v3/qualityprofile"
# Set request headers with API key
headers = {
'X-Api-Key': radarr_token
}
try:
# Send GET request to Radarr quality profiles endpoint
with requests_cache.disabled(): #disable caching for this request
response = requests.get(api_url, headers=headers, timeout=5)
except requests.exceptions.RequestException as e:
xbmc.log("Error requesting Radarr quality profiles", level=xbmc.LOGERROR)
raise
else:
# Return list of quality profiles if status code is 200 (OK)
if response.status_code == 200:
return json.loads(response.text)
else:
return None
def radarr_quality_profiles_dialog():
"""
Show a dialog to select a Radarr quality profile.
Returns the selected profile ID or None if cancelled or error.
"""
# Get quality profiles from Radarr
profiles = radarr_get_quality_profiles()
if profiles is None:
xbmcgui.Dialog().notification('Radarr', 'Error retrieving quality profiles', xbmcgui.NOTIFICATION_ERROR)
return None
# Extract profile names for display
profile_names = [profile['name'] for profile in profiles]
dialog = xbmcgui.Dialog()
# Show selection dialog
selected = dialog.select('Select Quality Profile', profile_names)
# Return selected profile ID or None if cancelled
if selected == -1:
return None
else:
return profiles[selected]['id']
def router(paramstring):
"""
Router function that calls other functions
depending on the provided paramstring
"""
# Parse a URL-encoded paramstring to the dictionary of
# {<parameter>: <value>} elements
params = dict(parse_qsl(paramstring))
# Check the parameters passed to the plugin
if not params:
# If the plugin is called from Kodi UI without any parameters,
# display the master list
list_folders(get_list("folder_list", "master"))
elif params['action'] == 'list_movies':
# display a list of movies
list_movies(get_list("movie_list", params['id']))
elif params['action'] == 'list_folders':
# display a list of folders
list_folders(get_list("folder_list", params['id']))
elif params['action'] == 'other_action':
# last stage callback
# the movie was not found in the library and we propose other actions
other_actions = ['Search in library']
if Addon().getSettingBool('radarr_enable') == True :
other_actions.append('Add to Radarr')
choice = xbmcgui.Dialog().contextmenu(other_actions)
if choice == 0:
#search in library
xbmc.executebuiltin("RunScript(script.globalsearch,movies=true&searchstring=%s)"%(params['title']))
elif choice == 1:
#add to Radarr
radarr_add_movie_dialogs(params['id'])
else:
# If the provided paramstring does not contain a supported action
# we raise an exception. This helps to catch coding errors,
# e.g. typos in action names.
raise ValueError(f'Invalid paramstring: {paramstring}!')
if __name__ == '__main__':
#logging.basicConfig(level=logging.DEBUG)
#web_pdb.set_trace()
#initialize requests cache
ADDON_USER_DATA_FOLDER = translatePath(Addon().getAddonInfo('profile'))
CACHE_FILE = translatePath(os.path.join(ADDON_USER_DATA_FOLDER, 'requests_cache'))
mkdir(ADDON_USER_DATA_FOLDER) #make sure the folder exists
requests_cache.install_cache( CACHE_FILE, backend='sqlite', expire_after=3600) # Default expiration: 1 hour
# instantiate the cache for the tmdb index
cache = StorageServer.StorageServer("jlom", 1)
# get data from cache or build it if not present
tmdb_index = cache.cacheFunction(build_tmdbid_to_dbid_index)
# Call the router function and pass the plugin call parameters to it.
# We use string slicing to trim the leading '?' from the plugin call paramstring
router(sys.argv[2][1:])