-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
822 lines (683 loc) · 22.5 KB
/
main.py
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
# -*- coding: utf-8 -*-
# License: GPL v.3 https://www.gnu.org/copyleft/gpl.html
"""
Guifibaix Mediateca plugin
"""
# Python 2 compatibility, remove when unneeded
from __future__ import unicode_literals
from future import standard_library
standard_library.install_aliases()
import sys
import os
from urllib.parse import urlencode, parse_qsl, quote
import xbmcgui
import xbmcplugin
import xbmcaddon
def u(text):
if type(text)==type(u''): return text
if type(text)==type(b''): return text.decode('utf8')
return type('u')(text)
def b(text):
if type(text)==type(b''): return text
if type(text)==type(u''): return text.encode('utf8')
return type('u')(text).encode('utf8')
def _(text, *args, **kwds):
# TODO: translate
return u(text).format(*args, **kwds)
# Get the plugin url in plugin:// notation.
_url = sys.argv[0]
# Get the plugin handle as an integer number.
_handle = int(sys.argv[1])
addon = xbmcaddon.Addon()
addonID = addon.getAddonInfo('id')
addonFolder = u(xbmc.translatePath('special://home/addons/'+addonID))
addonUserDataFolder = u(xbmc.translatePath("special://profile/addon_data/"+addonID))
icon = os.path.join(addonFolder, "icon.png")
urlMain = addon.getSetting('baseurl') # mediateca base url
# https://kodi.wiki/view/Artwork_types
artwork_tags = [
'thumb',
'poster',
'banner',
'fanart',
'clearart',
'clearlogo',
'landscape',
'icon',
]
# https://codedocs.xyz/xbmc/xbmc/group__python__xbmcgui__listitem.html#ga0b71166869bda87ad744942888fb5f14
video_info_tags = [
'genre',
'country',
'year',
'episode',
'season',
'sortepisode',
'sortseason',
'episodeguide',
'showlink',
'top250',
'setid',
'tracknumber',
'rating',
'userrating',
'watched',
'playcount',
'overlay',
'cast',
'castandrole',
'director',
'mpaa',
'plot',
'plotoutline',
'title',
'originaltitle',
'sorttitle',
'duration',
'studio',
'tagline',
'writer',
'tvshowtitle',
'premiered',
'status',
'set',
'setoverview',
'tag',
'imdbnumber',
'code',
'aired',
'credits',
'lastplayed',
'album',
'artist',
'votes',
'path',
'trailer',
'dateadded',
'mediatype',
'dbid',
]
def notify(message):
"GUI notification"
xbmc.executebuiltin(b(u('XBMC.Notification(Info,'+message+',2000,'+icon+')')))
def error(message):
"GUI notification"
xbmc.executebuiltin(b(u('XBMC.Notification(Error,'+message+',2000,'+icon+')')))
def fail(message):
error(message)
sys.exit(-1)
from contextlib import contextmanager
@contextmanager
def busy():
xbmc.executebuiltin('ActivateWindow(busydialog)')
try:
yield
finally:
xbmc.executebuiltin('Dialog.Close(busydialog)')
def log(msg, level=xbmc.LOGNOTICE):
log_message = u'{0}: [{2}] {1}'.format(addonID, msg, _handle)
xbmc.log(b(log_message), level)
"""
xbmc.LOGDEBUG = 0
xbmc.LOGERROR = 4
xbmc.LOGFATAL = 6
xbmc.LOGINFO = 1
xbmc.LOGNONE = 7
xbmc.LOGNOTICE = 2
xbmc.LOGSEVERE = 5
xbmc.LOGWARNING = 3
"""
def kodi_link(**params):
"""
Create a URL for calling the plugin recursively from the given set of keyword arguments.
:param params: "argument=value" pairs
:return: plugin call URL
:rtype: str
"""
return '{0}?{1}'.format(_url, urlencode(params))
def kodi_refresh():
xbmc.executebuiltin("Container.Refresh")
def kodi_action(**params):
"Returns a menu entry action string to run a kodi link"
return 'XBMC.RunPlugin({})'.format(kodi_link(**params))
def kodi_menu_item(label, callback, **kwds):
return label, kodi_action(action=callback.__name__, **kwds)
def apiurl(unsafe):
"Constructs an url to the Mediateca Api"
return urlMain+quote(b(unsafe))
def requestUsername(username=None):
keyboard = xbmc.Keyboard(username or '', _('GuifiBaix user name'))
keyboard.doModal()
if keyboard.isConfirmed() and u(keyboard.getText()):
return u(keyboard.getText())
def requestPassword():
password = ''
keyboard = xbmc.Keyboard('', _("GuifiBaix Password"), True)
keyboard.setHiddenInput(True)
keyboard.doModal()
if keyboard.isConfirmed() and keyboard.getText():
password = keyboard.getText()
return password and u(password)
def retrieveOrAskAuth():
username = addon.getSetting('username')
password = addon.getSetting('password')
if not username or not password:
username = requestUsername(username)
if password:
password = u(password)
if not password:
password = requestPassword()
addon.setSetting('username', username)
addon.setSetting('password', password)
return username, password
class MediatecaApi(object):
def __init__(self):
self._token = None
def _api_noauth(self, url, **kwds):
import requests
fullurl = urlMain + '/api/rest/' + url
try:
response = requests.post(fullurl, **kwds)
except requests.ConnectionError as e:
fail(_("No se puede connectar con la Mediateca"))
try:
result = response.json()
except Exception as e:
log(_("Non JSON api response:\n{}", response.text))
fail(_("Invalid API response: {}", e))
for k in result:
if 'Error' in k and result[k]:
log(_("API Prototocol Error accessing {}: {}", fullurl, result[k]))
fail(_("API Protocol Error"))
return result
def __enter__(self):
"Creates an autentication token"
username, password = retrieveOrAskAuth()
response = self._api_noauth('User/login/', data=dict(
user = username,
passwd = password,
))
if response['errors']:
fail(_("Login error: {}", '\n'.join(response['errors'])))
self._token = response['response']['Token']
return self
def __exit__(self, e_typ, e_val, trcbak):
response = self._api_noauth('User/logout', headers=dict(
Authorization = 'Bearer ' + self._token
))
if response['errors']:
fail(_("Logout error: {}", '\n'.join(response['errors'])))
def __call__(self, url, *args):
url = '/'.join([url] + [u(a) for a in args])
response = self._api_noauth(url,
headers=dict(
Authorization = 'Bearer '+self._token
) if self._token else {},
)
if response.get('errors'):
fail(_('API Error: {}', response['errors'][0]))
if 'response' not in response or 'data' not in response['response']:
import json
log(_('Unexpected API response:\n{}', json.dumps(response)))
fail(_('Unexpected API response: {}'))
return response['response']['data']
def api(url, *args):
with MediatecaApi() as mediateca:
return mediateca(url, *args)
categories = [
dict(
title=_("Episodios Pendientes"),
action='pending_list',
thumb='DefaultInProgressShows.png',
fanart=icon,
plot=_(
"Todos los nuevos episodios de las series que sigues."
"\n"
"\n"
"Para seguir una serie, "
"usa el menu contextual con una pulsación larga."
),
),
dict(
title=_("Series"),
action='series_list',
thumb='DefaultTVShows.png',
fanart=icon,
plot="Todas las series disponibles",
),
dict(
title=_("Películas"),
action='movie_list',
thumb='DefaultMovies.png',
fanart=icon,
plot=_("Todas las películas disponibles"),
),
]
def listing(title, items, item_processor, content='videos', sortings=[xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE]):
"""Defines a listing view depending on the parameters:
- title: view header (pluginCategory)
- items: items retrieved from the api to be processed
- item_processor: a function which turns api items into a dict with the
the movie info keys, artwork keys and those extra one:
- label: the shown text
- menus: a list of text, action tuples
- playable: false to make it not playable
- isfolder
- target: the target url of the item
- content: how the skin should interpret the list:
- files, songs, artists, albums, movies, tvshows, episodes, musicvideos, videos, images, games
- See: https://codedocs.xyz/xbmc/xbmc/group__python__xbmcplugin.html#gaa30572d1e5d9d589e1cd3bfc1e2318d6
- sortings: list of enabled sortings the user can choose:
- empty means user cannot change the provided order
- Available values: https://codedocs.xyz/xbmc/xbmc/group__python__xbmcplugin.html#ga85b3bff796fd644fb28f87b136025f40
"""
# Debuging help if we missed some attribute
items and log(_("{}, attribs from api: {}",
item_processor.__name__,
', '.join(sorted(items[0]))))
# Location step
xbmcplugin.setPluginCategory(_handle, title)
# Inform the skin of the kind of media
xbmcplugin.setContent(_handle, content)
nitems = len(items)
for item in items:
processed = item_processor(item)
if not processed: continue
isFolder = processed.pop('isfolder', True)
url = processed.pop('target')
li = buildItem(processed)
xbmcplugin.addDirectoryItem(_handle, url, li, isFolder=isFolder, totalItems=nitems)
for sorting in sortings:
xbmcplugin.addSortMethod(_handle, sorting)
# Finish creating a virtual folder.
xbmcplugin.endOfDirectory(_handle)
def buildItem(data):
"""Guiven a dict with all the tags builds a kodi
GUI ListItem to be inserted in a container.
Besides artwork and video info tags,
also receives: label, menus, playable.
isfolder and target should be consumed in 'listing'
before calling this function.
"""
def extract(data, tags):
return {
tag: data.pop(tag)
for tag in tags
if tag in data
}
label = data.pop('label')
artwork = extract(data, artwork_tags)
info = extract(data, video_info_tags)
menus = data.pop('menus',[])
playable = data.pop('playable', False)
if data:
log(_("Unprocessed keys: {}", list(data.keys())))
list_item = xbmcgui.ListItem(label=label)
list_item.setArt(artwork)
list_item.setInfo('video', info)
if playable:
list_item.setProperty('IsPlayable', 'true')
if menus:
list_item.addContextMenuItems(menus)
return list_item
def category_list():
listing(
title = _("Mediateca"),
items = categories,
item_processor = category_item,
content = 'videos',
sortings=[], # sorted as listed
)
def movie_list():
listing(
title = _("Películas"),
items = api('Peliculas/listaCompletaConEstadisticas'),
item_processor = movie_item,
content = 'movies',
sortings = [
xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE,
xbmcplugin.SORT_METHOD_DATEADDED,
xbmcplugin.SORT_METHOD_PLAYCOUNT,
xbmcplugin.SORT_METHOD_VIDEO_YEAR,
xbmcplugin.SORT_METHOD_VIDEO_RATING,
xbmcplugin.SORT_METHOD_MPAA_RATING,
],
)
def series_list():
listing(
title = _("Series"),
items = api('Series/listaCompleta'),
item_processor = serie_item,
content = 'tvshows',
)
def season_list(serie):
seasons = api('Serie/temporadasSerie/', serie)
listing(
title = seasons[0]['Serie'],
items = seasons,
item_processor = season_item,
content = 'seasons',
)
def episode_list(serie, season):
episodes = api('Serie/capitulosSerieconEstadistica/', serie, season)
listing(
title = episodes[0]['Serie'],
items = episodes,
item_processor = episode_item,
content = 'episodes',
sortings=[
xbmcplugin.SORT_METHOD_LABEL,
],
)
def pending_list():
episodes = api('Series/pendingEpisodes/', 0, addon.getSetting('max_pending_episodes'))
listing(
title = _("Pending episodes"),
items = episodes,
item_processor = mixed_episode_item,
content = 'episodes',
sortings=[],
)
def statusString(item):
stateId = item.get("Estado",'0')
stateText = {
"1": _("En emision"),
"2": _("Esperando temporada"),
"3": _("Finalizada"),
"4": _("Cancelada"),
}.get(stateId)
return stateText
def l(item, key):
"turns a comma separated list string into an actual python list"
string = item.get(key)
if not string: return []
result = [x.strip() for x in string.split(',') ]
return result
def lfix(item, key):
"For fields that according specs should take a list but don't"
return ', '.join(l(item,key))
def category_item(category):
" Creates a category list item"
if category.pop('disabled', False): return None
return dict(
category,
label = category['title'],
target = kodi_link(action=category.pop('action')),
)
def common_metadata(data):
return dict(
rating = data['Rating'],
genre = lfix(data, 'Generos'),
year = int(data['Any']),
cast = l(data, 'Reparto'),
director = lfix(data, 'Director'),
studio = lfix(data, 'Productora'),
writer = lfix(data, 'Guion'),
country = lfix(data, 'Pais'),
status = statusString(data),
dateadded = data.get('FechaAnadido'),
imdbnumber = data.get('IMDB_ID'),
)
def commonSeries_metadata(data):
return dict(
common_metadata(data),
season = int(data['Temporadas']),
aired = data.get('PrimeraEmision'),
)
def serie_item(serie):
" Creates a serie list item"
if serie['Retirada'] == '1': return None
if serie['Activo'] != '1': return None
tags = []
if serie.get("Subscribed")=='1': tags.append(_("[La sigues]"))
tags = ' '.join(tags)
if tags: tags+='\n\n'
return dict(
commonSeries_metadata(serie),
label = serie['Serie'],
thumb = apiurl(serie['Poster']),
poster = apiurl(serie['Poster']),
fanart = apiurl(serie['Poster'][:-len('/cover.jpg')]+'/fanart.jpg'),
title = serie['Serie'],
originaltitle = serie['Serie'],
tvshowtitle = serie['Serie'],
mediatype = 'tvshow',
plot = tags + serie['Sipnosis'], # Misspelled in db
menus = [
menu_follow_serie(serie['IdSerie'], wasSet = serie.get('Subscribed')=='1'),
],
target = kodi_link(action='season_list', serie=serie['IdSerie']),
)
def season_item(season):
"Creates a season list item"
if season['Retirada'] == '1': return None
if season['Activo'] != '1': return None
title = _("Temporada {}", season['Temporada'])
tags = []
if season.get("Subscribed")=='1': tags.append(_("[Siguiendo] "))
tags = ' '.join(tags)
if tags: tags+='\n\n'
menus = [
menu_follow_serie(season['IdSerie'], wasSet = season.get("Subscribed")=='1'),
]+ menu_seen_season(season['IdSerie'], season['Temporada'])
return dict(
commonSeries_metadata(season),
label=title,
thumb = apiurl(season['Poster']),
poster = apiurl(season['Poster']),
fanart = apiurl(season['Poster'][:-len('/cover.jpg')]+'/fanart.jpg'),
title = title,
originaltitle = ' - '.join([season['Serie'],title]),
tagline = season['Serie'],
tvshowtitle = season['Serie'],
mediatype = 'season',
plot = tags + season['Sipnosis'], # Misspelled in db
menus = menus,
target = kodi_link(action='episode_list', serie=season['IdSerie'], season=season['Temporada'])
)
def episode_item(episode):
"Creates an episode list item"
if episode['Retirada'] == '1': return None
if episode['Activo'] != '1': return None
tags = []
if episode.get("Subscribed")=='1': tags.append(_("[La sigues]"))
tags = ' '.join(tags)
if tags: tags+='\n\n'
label = _("{Temporada}x{Capitulo} - {Titulo}", **episode)
seen = episode.get("Visto",'0')!='0'
menus = [
menu_follow_serie(episode['IdSerie'], wasSet = episode.get("Subscribed")=='1'),
menu_seen_episode(episode['Identificador'], wasSet = seen),
]+ menu_seen_season(episode['IdSerie'], episode['Temporada'])
return dict(
commonSeries_metadata(episode),
label = label,
thumb = apiurl(episode['Poster']),
poster = apiurl(episode['Fichero'][:-len('.mp4')]+'.jpg'),
fanart = apiurl(episode['Fichero'][:-len('.mp4')]+'.jpg'),
title = label,
originaltitle = episode['Titulo'],
tvshowtitle = episode['Serie'],
mediatype = 'episode',
episode = episode['Capitulo'],
plot = tags + episode['Sipnosis'], # Misspelled in db
playcount = 1 if seen else 0,
lastplayed = '2000-01-01' if seen else '',
path=apiurl(episode['Fichero']),
isfolder = False,
playable = True,
menus = menus,
target = kodi_link(action='play_video', url=apiurl(episode['Fichero'])),
)
def youtube_plugin(url):
if not url: return url
if 'youtube.com' not in url: return url
youtubecode = url.split('|')[0].split('=')[1]
return 'plugin://plugin.video.youtube/play/?video_id=' + youtubecode
def mixed_episode_item(episode):
reused = episode_item(episode)
return reused and dict(
reused,
title = _("{Temporada}x{Capitulo} - {Titulo}", **episode),
label = _("{Serie}\n{Temporada}x{Capitulo} - {Titulo}", **episode),
)
def movie_item(movie):
if movie['Activo'] != '1': return None
if movie['MostrarEnListaCompleta'] != '1':
return None
label = _("[{Any}] {Titulo}", **movie)
seen = movie.get("Visto",'0')!='0'
return dict(
common_metadata(),
label=label,
thumb = apiurl(movie['Poster']),
poster = apiurl(movie['Poster']),
fanart = apiurl(movie['Poster'][:-len('cover.jpg')]+'fanart.jpg'),
title = movie['Titulo'],
originaltitle = movie['Titulo'],
mediatype = 'movie',
plot = movie['Sipnosis'], # Misspelled in db
trailer = youtube_plugin(movie.get("Trailer")),
mpaa = movie['Clasificacion'],
playcount = 1 if seen else 0,
lastplayed = '2000-01-01' if seen else '',
path=apiurl(movie['Fichero']),
menus = [
menu_seen_movie(movie['Identificador'], seen),
],
isfolder = False,
playable = True,
target = kodi_link(action='play_video', url=apiurl(movie['Fichero'])),
)
def menu_follow_serie(serie_id, wasSet):
label = _('Abandonar serie') if wasSet else _('Seguir serie')
action = 'unfollow_serie' if wasSet else 'follow_serie'
return label, kodi_action(
action=action,
serie_id=serie_id,
)
def follow_serie(serie_id):
with busy():
status = api('Alertas/subscribeToSerie/', serie_id)
kodi_refresh()
def unfollow_serie(serie_id):
with busy():
status = api('Alertas/unsubscribeToSerie/', serie_id)
kodi_refresh()
def menu_seen_season(serie_id, season):
return [
kodi_menu_item(
_('Marcar temporada NO vista'),
unmark_season_seen,
serie=serie_id,
season=season,
),
kodi_menu_item(
_('Marcar temporada vista'),
mark_season_seen,
serie=serie_id,
season=season,
),
]
def menu_seen_episode(episode, wasSet):
if wasSet:
return kodi_menu_item(
_('Marcar como NO visto'),
unmark_episode_seen,
episode=episode,
)
return kodi_menu_item(
_('Marcar como visto'),
mark_episode_seen,
episode=episode,
)
def menu_seen_movie(movie, wasSet):
if wasSet:
return kodi_menu_item(
_('Marcar como NO vista'),
unmark_movie_seen,
movie=movie,
)
return kodi_menu_item(
_('Marcar como vista'),
mark_movie_seen,
movie=movie,
)
def mark_season_seen(serie, season):
with busy():
serieCategory = 1
result = api('Estadistica/updateEstadisticaTemporadaUser', serie, season)
kodi_refresh()
def unmark_season_seen(serie, season):
with busy():
serieCategory = 1
result = api('Estadistica/clearEstadisticaTemporadaUser', serie, season)
kodi_refresh()
def mark_episode_seen(episode):
with busy():
serieCategory = 1
result = api('Estadistica/updateEstadisticaUser', episode, serieCategory)
kodi_refresh()
def unmark_episode_seen(episode):
with busy():
serieCategory = 1
result = api('Estadistica/clearEstadisticaUser', episode, serieCategory)
kodi_refresh()
def mark_movie_seen(movie):
with busy():
movieCategory = 2
result = api('Estadistica/updateEstadisticaUser', movie, movieCategory)
kodi_refresh()
def unmark_movie_seen(movie):
with busy():
movieCategory = 2
result = api('Estadistica/clearEstadisticaUser', movie, movieCategory)
kodi_refresh()
def play_video(url):
"""
Play a video by the provided url.
:param url: Fully-qualified video URL
:type url: str
"""
# Create a playable item with a url to play.
play_item = xbmcgui.ListItem(path=url)
# Pass the item to the Kodi player.
xbmcplugin.setResolvedUrl(_handle, True, listitem=play_item)
entrypoints = [
category_list,
series_list,
season_list,
episode_list,
movie_list,
play_video,
pending_list,
follow_serie,
unfollow_serie,
mark_season_seen,
unmark_season_seen,
mark_episode_seen,
unmark_episode_seen,
mark_movie_seen,
unmark_movie_seen,
]
log('\nRunning {}'.format(" ".join(sys.argv)))
def router(paramstring):
"""
Router function that calls other functions
depending on the provided paramstring
:param paramstring: URL encoded plugin paramstring
:type paramstring: str
"""
params = dict(parse_qsl(paramstring))
action = params.pop('action','category_list')
dispatchers = { fun.__name__: fun for fun in entrypoints}
dispatcher = dispatchers.get(action, None)
if not dispatcher:
raise ValueError('Invalid entry point: {0}'.format(action))
dispatcher(**params)
if __name__ == '__main__':
# Params are urlencoded as the second parameter
# 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:])
# vim: et