PageRenderTime 45ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/musicplayer/musicplayer.py

https://gitlab.com/Rakowski/linsw_zad4
Python | 109 lines | 84 code | 25 blank | 0 comment | 8 complexity | ed37f0a5fcd32e711aee2268274f9b5c MD5 | raw file
  1. import os
  2. import tornado.ioloop
  3. import tornado.web
  4. import base64
  5. from subprocess import call
  6. FILES = '/mnt/files'
  7. FIFO = '/root/mplayer_fifo'
  8. MM = None
  9. class MplayerManager():
  10. mute = 0
  11. volume = 75
  12. def send(self, msg):
  13. command = 'echo "' + msg + '" > ' + FIFO
  14. print command
  15. os.system(command)
  16. def setVolume(self, val):
  17. self.volume = val
  18. self.send('volume ' + str(val) + ' 1')
  19. def toggleMute(self):
  20. if self.mute == 0:
  21. self.send('mute 1')
  22. self.mute = 1
  23. else:
  24. self.send('mute 0')
  25. self.mute = 0
  26. self.setVolume(self.volume)
  27. def pause(self):
  28. self.send('pause')
  29. def stop(self):
  30. self.send('stop')
  31. def play(self, filename):
  32. self.send('loadfile ' + FILES + '/' + filename + ' 0')
  33. self.setVolume(self.volume)
  34. class Index(tornado.web.RequestHandler):
  35. def get(self):
  36. files = []
  37. for filename in os.listdir(FILES):
  38. files.append(filename)
  39. self.render('index.html', files=files)
  40. def post(self):
  41. auth_hdr = self.request.headers.get('Authorization')
  42. print auth_hdr
  43. if auth_hdr == None or not auth_hdr.startswith('Basic '):
  44. return self.auth()
  45. auth_decoded = base64.decodestring(auth_hdr[6:])
  46. username, password = auth_decoded.split(':', 2)
  47. if username != "ja" or password != "ja":
  48. return self.auth()
  49. f = self.request.files['datafile'][0]
  50. filename = f['filename']
  51. print "Upload request with file: " + filename
  52. x = open(FILES + '/' + filename, 'w')
  53. x.write(f['body'])
  54. x.close()
  55. self.redirect("/")
  56. def auth(self):
  57. self.set_status(401)
  58. self.set_header('WWW-Authenticate', 'Basic realm=Fileserver')
  59. self.finish()
  60. return False
  61. class VolumeChanged(tornado.web.RequestHandler):
  62. def get(self, vol):
  63. MM.setVolume(vol)
  64. class MuteToggled(tornado.web.RequestHandler):
  65. def get(self):
  66. MM.toggleMute()
  67. class Paused(tornado.web.RequestHandler):
  68. def get(self):
  69. MM.pause()
  70. class Play(tornado.web.RequestHandler):
  71. def get(self, filename):
  72. MM.play(filename)
  73. self.redirect('/')
  74. if __name__ == "__main__":
  75. MM = MplayerManager()
  76. webserv = tornado.web.Application([
  77. (r"/", Index),
  78. (r"/volume_changed/(1?[0-9]?[0-9])", VolumeChanged),
  79. (r"/mute/", MuteToggled),
  80. (r"/pause/", Paused),
  81. (r"/play/(.*)", Play)
  82. ])
  83. webserv.listen(80)
  84. tornado.ioloop.IOLoop.instance().start()