pyponotify 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import traceback
  4. """
  5. Python part of radio playout (pypo)
  6. This function acts as a gateway between liquidsoap and the server API.
  7. Mainly used to tell the platform what pypo/liquidsoap does.
  8. Main case:
  9. - whenever LS starts playing a new track, its on_metadata callback calls
  10. a function in ls (notify(m)) which then calls the python script here
  11. with the currently starting filename as parameter
  12. - this python script takes this parameter, tries to extract the actual
  13. media id from it, and then calls back to the API to tell about it about it.
  14. """
  15. from optparse import OptionParser
  16. import sys
  17. import logging.config
  18. import json
  19. # additional modules (should be checked)
  20. from configobj import ConfigObj
  21. # custom imports
  22. #from util import *
  23. from api_clients import *
  24. from std_err_override import LogWriter
  25. LOG_LEVEL = logging.INFO
  26. LOG_PATH = '/var/log/airtime/pypo/notify.log'
  27. # help screeen / info
  28. usage = "%prog [options]" + " - notification gateway"
  29. parser = OptionParser(usage=usage)
  30. # Options
  31. parser.add_option("-d", "--data", help="Pass JSON data from Liquidsoap into this script.", metavar="data")
  32. parser.add_option("-m", "--media-id", help="ID of the file that is currently playing.", metavar="media_id")
  33. parser.add_option("-e", "--error", action="store", dest="error", type="string", help="Liquidsoap error msg.", metavar="error_msg")
  34. parser.add_option("-s", "--stream-id", help="ID stream", metavar="stream_id")
  35. parser.add_option("-c", "--connect", help="Liquidsoap connected", action="store_true", metavar="connect")
  36. parser.add_option("-t", "--time", help="Liquidsoap boot up time", action="store", dest="time", metavar="time", type="string")
  37. parser.add_option("-x", "--source-name", help="source connection name", metavar="source_name")
  38. parser.add_option("-y", "--source-status", help="source connection status", metavar="source_status")
  39. parser.add_option("-w", "--webstream", help="JSON metadata associated with webstream", metavar="json_data")
  40. parser.add_option("-n", "--liquidsoap-started", help="notify liquidsoap started", metavar="json_data", action="store_true", default=False)
  41. # parse options
  42. (options, args) = parser.parse_args()
  43. # Set up logging
  44. logFormatter = logging.Formatter("%(asctime)s [%(module)s] [%(levelname)-5.5s] %(message)s")
  45. rootLogger = logging.getLogger()
  46. rootLogger.setLevel(LOG_LEVEL)
  47. fileHandler = logging.handlers.RotatingFileHandler(filename=LOG_PATH, maxBytes=1024*1024*30,
  48. backupCount=8)
  49. fileHandler.setFormatter(logFormatter)
  50. rootLogger.addHandler(fileHandler)
  51. consoleHandler = logging.StreamHandler()
  52. consoleHandler.setFormatter(logFormatter)
  53. rootLogger.addHandler(consoleHandler)
  54. logger = rootLogger
  55. #need to wait for Python 2.7 for this..
  56. #logging.captureWarnings(True)
  57. # loading config file
  58. try:
  59. config = ConfigObj('/etc/airtime/airtime.conf')
  60. except Exception, e:
  61. logger.error('Error loading config file: %s', e)
  62. sys.exit()
  63. class Notify:
  64. def __init__(self):
  65. self.api_client = api_client.AirtimeApiClient(logger=logger)
  66. def notify_liquidsoap_started(self):
  67. logger.debug("Notifying server that Liquidsoap has started")
  68. self.api_client.notify_liquidsoap_started()
  69. def notify_media_start_playing(self, media_id):
  70. logger.debug('#################################################')
  71. logger.debug('# Calling server to update about what\'s playing #')
  72. logger.debug('#################################################')
  73. response = self.api_client.notify_media_item_start_playing(media_id)
  74. logger.debug("Response: " + json.dumps(response))
  75. # @pram time: time that LS started
  76. def notify_liquidsoap_status(self, msg, stream_id, time):
  77. logger.debug('#################################################')
  78. logger.debug('# Calling server to update liquidsoap status #')
  79. logger.debug('#################################################')
  80. logger.debug('msg = ' + str(msg))
  81. response = self.api_client.notify_liquidsoap_status(msg, stream_id, time)
  82. logger.debug("Response: " + json.dumps(response))
  83. def notify_source_status(self, source_name, status):
  84. logger.debug('#################################################')
  85. logger.debug('# Calling server to update source status #')
  86. logger.debug('#################################################')
  87. logger.debug('msg = ' + str(source_name) + ' : ' + str(status))
  88. response = self.api_client.notify_source_status(source_name, status)
  89. logger.debug("Response: " + json.dumps(response))
  90. def notify_webstream_data(self, data, media_id):
  91. logger.debug('#################################################')
  92. logger.debug('# Calling server to update webstream data #')
  93. logger.debug('#################################################')
  94. response = self.api_client.notify_webstream_data(data, media_id)
  95. logger.debug("Response: " + json.dumps(response))
  96. def run_with_options(self, options):
  97. if options.error and options.stream_id:
  98. self.notify_liquidsoap_status(options.error, options.stream_id, options.time)
  99. elif options.connect and options.stream_id:
  100. self.notify_liquidsoap_status("OK", options.stream_id, options.time)
  101. elif options.source_name and options.source_status:
  102. self.notify_source_status(options.source_name, options.source_status)
  103. elif options.webstream:
  104. self.notify_webstream_data(options.webstream, options.media_id)
  105. elif options.media_id:
  106. self.notify_media_start_playing(options.media_id)
  107. elif options.liquidsoap_started:
  108. self.notify_liquidsoap_started()
  109. else:
  110. logger.debug("Unrecognized option in options(%s). Doing nothing" \
  111. % str(options))
  112. if __name__ == '__main__':
  113. print
  114. print '#########################################'
  115. print '# *** pypo *** #'
  116. print '# pypo notification gateway #'
  117. print '#########################################'
  118. # initialize
  119. try:
  120. n = Notify()
  121. n.run_with_options(options)
  122. except Exception as e:
  123. print( traceback.format_exc() )