/mythtv/bindings/python/MythTV/ttvdb/tvdb_ui.py

https://github.com/hobbes1069/mythtv · Python · 124 lines · 113 code · 2 blank · 9 comment · 0 complexity · 305a22b10a8be8dfef8ff90c399d9a38 MD5 · raw file

  1. #!/usr/bin/env python
  2. #encoding:utf-8
  3. #author:dbr/Ben
  4. #project:tvdb_api
  5. #repository:http://github.com/dbr/tvdb_api
  6. #license:Creative Commons GNU GPL v2
  7. # (http://creativecommons.org/licenses/GPL/2.0/)
  8. """Contains included user interfaces for Tvdb show selection.
  9. A UI is a callback. A class, it's __init__ function takes two arguments:
  10. - config, which is the Tvdb config dict, setup in tvdb_api.py
  11. - log, which is Tvdb's logger instance (which uses the logging module). You can
  12. call log.info() log.warning() etc
  13. It must have a method "selectSeries", this is passed a list of dicts, each dict
  14. contains the the keys "name" (human readable show name), and "sid" (the shows
  15. ID as on thetvdb.com). For example:
  16. [{'name': u'Lost', 'sid': u'73739'},
  17. {'name': u'Lost Universe', 'sid': u'73181'}]
  18. The "selectSeries" method must return the appropriate dict, or it can raise
  19. tvdb_userabort (if the selection is aborted), tvdb_shownotfound (if the show
  20. cannot be found).
  21. A simple example callback, which returns a random series:
  22. >>> import random
  23. >>> from tvdb_ui import BaseUI
  24. >>> class RandomUI(BaseUI):
  25. ... def selectSeries(self, allSeries):
  26. ... import random
  27. ... return random.choice(allSeries)
  28. Then to use it..
  29. >>> from tvdb_api import Tvdb
  30. >>> t = Tvdb(custom_ui = RandomUI)
  31. >>> random_matching_series = t['Lost']
  32. >>> type(random_matching_series)
  33. <class 'tvdb_api.Show'>
  34. """
  35. __author__ = "dbr/Ben"
  36. __version__ = "1.2.1"
  37. from tvdb_exceptions import tvdb_userabort
  38. class BaseUI:
  39. """Default non-interactive UI, which auto-selects first results
  40. """
  41. def __init__(self, config, log):
  42. self.config = config
  43. self.log = log
  44. def selectSeries(self, allSeries):
  45. return allSeries[0]
  46. class ConsoleUI(BaseUI):
  47. """Interactively allows the user to select a show from a console based UI
  48. """
  49. def _displaySeries(self, allSeries):
  50. """Helper function, lists series with corresponding ID
  51. """
  52. print "TVDB Search Results:"
  53. for i in range(len(allSeries[:6])): # list first 6 search results
  54. i_show = i + 1 # Start at more human readable number 1 (not 0)
  55. self.log.debug('Showing allSeries[%s] = %s)' % (i_show, allSeries[i]))
  56. print "%s -> %s # http://thetvdb.com/?tab=series&id=%s" % (
  57. i_show,
  58. allSeries[i]['name'].encode("UTF-8","ignore"),
  59. allSeries[i]['sid'].encode("UTF-8","ignore")
  60. )
  61. def selectSeries(self, allSeries):
  62. self._displaySeries(allSeries)
  63. if len(allSeries) == 1:
  64. # Single result, return it!
  65. print "Automatically selecting only result"
  66. return allSeries[0]
  67. if self.config['select_first'] is True:
  68. print "Automatically returning first search result"
  69. return allSeries[0]
  70. while True: # return breaks this loop
  71. try:
  72. print "Enter choice (first number, ? for help):"
  73. ans = raw_input()
  74. except KeyboardInterrupt:
  75. raise tvdb_userabort("User aborted (^c keyboard interupt)")
  76. except EOFError:
  77. raise tvdb_userabort("User aborted (EOF received)")
  78. self.log.debug('Got choice of: %s' % (ans))
  79. try:
  80. selected_id = int(ans) - 1 # The human entered 1 as first result, not zero
  81. except ValueError: # Input was not number
  82. if ans == "q":
  83. self.log.debug('Got quit command (q)')
  84. raise tvdb_userabort("User aborted ('q' quit command)")
  85. elif ans == "?":
  86. print "## Help"
  87. print "# Enter the number that corresponds to the correct show."
  88. print "# ? - this help"
  89. print "# q - abort tvnamer"
  90. else:
  91. self.log.debug('Unknown keypress %s' % (ans))
  92. else:
  93. self.log.debug('Trying to return ID: %d' % (selected_id))
  94. try:
  95. return allSeries[ selected_id ]
  96. except IndexError:
  97. self.log.debug('Invalid show number entered!')
  98. print "Invalid number (%s) selected!"
  99. self._displaySeries(allSeries)
  100. #end try
  101. #end while not valid_input