watch.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #!/usr/bin/env python3
  2. #
  3. # Usage:
  4. # ./autocompile.py path ext1
  5. #
  6. import subprocess
  7. import sys
  8. import os
  9. import pyinotify
  10. from db import db,file_info
  11. from constants import RAW_PATH
  12. from subprocess import Popen,PIPE
  13. class OnWriteHandler(pyinotify.ProcessEvent):
  14. def my_init(self, cwd, extension):
  15. self.cwd = cwd
  16. self.extension = extension
  17. def _run_cmd(self,path):
  18. print('==> Modification detected')
  19. d=db()
  20. out_fname=os.path.join(RAW_PATH, os.path.basename(path).replace('flv','mp4'))
  21. in_fname=os.path.join(self.cwd, path)
  22. if os.path.isfile(out_fname):
  23. #exists
  24. return
  25. process=[ 'ffmpeg',
  26. '-loglevel', 'error',
  27. '-i', in_fname,
  28. '-c', 'copy',
  29. '-movflags', '+faststart',
  30. '-f','mp4',
  31. out_fname
  32. ]
  33. print(" ".join(process))
  34. proc=Popen(process, universal_newlines=True)
  35. proc.wait()
  36. rc = proc.returncode
  37. if rc != 0:
  38. print("Error?")
  39. return
  40. d.insert_raw(file_info(out_fname))
  41. def process_IN_CLOSE_WRITE(self, event):
  42. if not event.pathname.endswith(self.extension):
  43. return
  44. print(event.mask, event.maskname, event.pathname)
  45. self._run_cmd(event.pathname)
  46. def auto_compile(path, extension):
  47. wm = pyinotify.WatchManager()
  48. handler = OnWriteHandler(cwd=path, extension=extension)
  49. notifier = pyinotify.Notifier(wm, default_proc_fun=handler)
  50. wm.add_watch(path, pyinotify.ALL_EVENTS, rec=True, auto_add=True)
  51. print('==> Start monitoring %s' % path)
  52. notifier.loop()
  53. if __name__ == '__main__':
  54. path = '/home/nginx/processed/'
  55. extension = 'flv'
  56. auto_compile(path, extension)