/rcast.py

https://github.com/vincelwt/RaspberryCast · Python · 156 lines · 94 code · 42 blank · 20 comment · 23 complexity · d8627918e5a67fb9ac0d618728ab981f MD5 · raw file

  1. #!/usr/bin/env python
  2. import urllib
  3. import urllib2
  4. import os
  5. import sys
  6. import thread
  7. import signal
  8. import socket
  9. import SimpleHTTPServer
  10. import SocketServer
  11. import time
  12. import json
  13. def signal_handler(signal, frame):
  14. print(
  15. 'You pressed Ctrl+C, stopping. Casting may continue for some time.'
  16. )
  17. sys.exit(0)
  18. # No need for advanced logging options since rcast.py is to be run manually
  19. def log(output):
  20. # If file exist, open it and append to file.
  21. # If file does not exist, create it.
  22. try:
  23. file = open(sys.path[0] + "/rcast.log", "a")
  24. except IOError:
  25. file = open(sys.path[0] + "/rcast.log", "w")
  26. file.write(time.strftime('%a %H:%M:%S') + " " + output + "\n")
  27. file.close()
  28. print output
  29. # Catch SIGINT via Ctrl + C
  30. signal.signal(signal.SIGINT, signal_handler)
  31. # Handle incorrect number of arguments
  32. if(len(sys.argv) > 3 or len(sys.argv) < 2):
  33. log("""Incorrect number of arguments given. Program expects 1-2 arguments.
  34. A playable video file, and an optional subtitle file.""")
  35. sys.exit(0)
  36. # Attempt to load and read configuration file.
  37. # If no file is found, use default values.
  38. try:
  39. with open(sys.path[0] + "/raspberrycast.conf") as f:
  40. config = json.load(f)
  41. # Read configuration file.
  42. # If no values exists (or if it's empty), use default values.
  43. if config["pi_hostname"] and config["pi_hostname"] is not "":
  44. ip = config["pi_hostname"] + ".local" + ":2020"
  45. else:
  46. ip = ip = "raspberrypi.local:2020"
  47. if config["subtitle_search"] and config["subtitle_search"] is not "":
  48. search_for_subtitles = config["subtitle_search"]
  49. else:
  50. search_for_subtitles = False
  51. # If an IOException is caught, the file could not be found.
  52. # We then use the default values for the hostname and sub_search
  53. except IOError as e:
  54. log("""INFO: Configuration file 'raspberrycast.conf' not found.
  55. Using default values.""")
  56. ip = "raspberrypi.local:2020"
  57. search_for_subtitles = False
  58. # -- MAIN PROGRAM START -- #
  59. tocast = sys.argv[1]
  60. subtitle_path = ""
  61. log("-----------------------------")
  62. log("Attempting to cast " + tocast)
  63. log("-----------------------------")
  64. if not os.path.isfile(tocast):
  65. log("File not found!")
  66. sys.exit(0)
  67. if(len(sys.argv) == 3):
  68. subtitle_path = sys.argv[2]
  69. # If two arguments are given, but in the wrong order, sort them out.
  70. if not subtitle_path.endswith(".srt"):
  71. subtitle_path = sys.argv[1]
  72. tocast = sys.argv[2]
  73. log("Subtitle path is " + subtitle_path)
  74. # Assuming user wants to search for subtitles, but no specific file was given
  75. if search_for_subtitles and len(sys.argv) == 2:
  76. file_path = sys.argv[1]
  77. filename = os.path.split(file_path)[1]
  78. base_path = os.path.split(file_path)[0]
  79. # We have to assume that the subtitle file has the same name as the file
  80. # This line "trims" the file extenstion, and appends "srt."
  81. default_subtitle = filename[:(filename.rfind("."))] + ".srt"
  82. files = [file for file in os.listdir(base_path)]
  83. for f in files:
  84. if default_subtitle == file:
  85. log("Subtitle match was found at " + file)
  86. subtitle_path = default_subtitle
  87. # Handle case where rcast is run from another directory
  88. path = os.path.split(tocast)[0]
  89. if(path is not ""):
  90. os.chdir(path)
  91. filename = os.path.split(tocast)[1]
  92. subtitle_path = os.path.split(subtitle_path)[1]
  93. PORT = 8080
  94. class MyTCPServer(SocketServer.TCPServer):
  95. def server_bind(self):
  96. self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  97. self.socket.bind(self.server_address)
  98. Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
  99. httpd = MyTCPServer(("", PORT), Handler)
  100. thread.start_new_thread(httpd.serve_forever, ())
  101. encoded_string = urllib.quote_plus("http://localhost:8080/"+filename)
  102. log("The encoded string is " + encoded_string)
  103. full_url = "http://"+ip+"/stream?url="+encoded_string
  104. # If subtitle exists, append it to the URL to send.
  105. if subtitle_path is not "":
  106. sub_string = urllib.quote_plus("http://localhost:8080/" + subtitle_path)
  107. full_url += "&subtitles=" + sub_string
  108. log("-----------------------------")
  109. log("Do not close this program while playing the file")
  110. log("Press Ctrl+C to stop")
  111. log("-----------------------------")
  112. urllib2.urlopen(full_url).read()
  113. # We don't want to quit directly, pause until Ctrl+C
  114. signal.pause()