RaNas.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. # -*- coding:UTF-8 -*-
  2. import json
  3. import os
  4. import datetime
  5. import time
  6. import shutil
  7. class RaNas:
  8. def __init__(self, Components):
  9. """
  10. Initialisiert das RaNas
  11. :param Components: RaComponents Element
  12. :type Components: RaComponents
  13. """
  14. self.components = Components
  15. self.config = self.load_json("config.json")
  16. def load_json(self, filename):
  17. """
  18. Lädt die Menüstruktur aus einer JSON-Datei.
  19. :param filename: Der Name der JSON-Datei.
  20. """
  21. res=dict()
  22. with open(filename, "r") as file:
  23. res = json.load(file) # Menüstruktur aus JSON laden
  24. return res
  25. def Sync(self):
  26. self.components.Menu.Progress(-1)
  27. self.MountNas()
  28. path = self.config["recording"]["dir"]
  29. files = list()
  30. filesizeTotal=0
  31. for filename in os.listdir(path):
  32. f = os.path.join(path, filename)
  33. t = os.path.getmtime(f)
  34. dt = datetime.datetime.fromtimestamp(t)
  35. year,month,day,hour,minute,second = time.localtime(dt)[:-3]
  36. filesize = os.path.getsize(f)
  37. mp4Exists = False
  38. rawExists = False
  39. mp4Path = self.config["nas"]["remote_path"]+"/Video/"+str(year)+"-"+str(month)+"-"+str(day)+"/"+filename[:-4]+"mp4"
  40. rawPath = self.config["nas"]["remote_path"]+"/Raw/"+str(year)+"-"+str(month)+"-"+str(day)+"/"+filename
  41. if self.config["nas"]["copy_raw"]==True:
  42. if os.path.exists(rawPath)==True:
  43. rawExists = True
  44. else:
  45. rawExists = True
  46. if self.config["nas"]["copy_mp4"]==True:
  47. if os.path.exists(mp4Path)==True:
  48. mp4Exists = True
  49. else:
  50. mp4Exists = True
  51. if mp4Exists==False or rawExists==False:
  52. files.append({
  53. "Souce_path":f,
  54. "size":filesize,
  55. "date":dt,
  56. "Raw_filename":filename,
  57. "Mp4_targetname": filename[:-4]+"mp4",
  58. "Mp4_targetpath": mp4Path,
  59. "Raw_targetpath": rawPath,
  60. "Mp4_subdir":self.config["nas"]["remote_path"]+"/Video/"+str(year)+"-"+str(month)+"-"+str(day),
  61. "Raw_subdir":self.config["nas"]["remote_path"]+"/Raw/"+str(year)+"-"+str(month)+"-"+str(day)
  62. })
  63. filesizeTotal+=filesize
  64. FileIndex = 0
  65. FileLength = len(files)
  66. CopiedSize = 0
  67. fps = 30
  68. if "fps" in self.config["recording"] and isinstance(self.config["recording"]["fps"], int):
  69. fps = self.config["recording"]["fps"]
  70. # Create Base Dir
  71. if self.config["nas"]["copy_raw"]==True and os.path.exists(self.config["nas"]["remote_path"]+"/Raw")==False:
  72. os.mkdir(self.config["nas"]["remote_path"]+"/Raw")
  73. if self.config["nas"]["copy_raw"]==True and os.path.exists(self.config["nas"]["remote_path"]+"/Video")==False:
  74. os.mkdir(self.config["nas"]["remote_path"]+"/Video")
  75. if self.config["nas"]["copy_scans"]==True and os.path.exists(self.config["nas"]["remote_path"]+"/Scans")==False:
  76. os.mkdir(self.config["nas"]["remote_path"]+"/Scans")
  77. self.components.Menu.Progress(0)
  78. for itm in files.items():
  79. # Copy Raw
  80. if self.config["nas"]["copy_raw"]==True:
  81. if os.path.exists(itm["Raw_subdir"])==False:
  82. os.mkdir(itm["Raw_subdir"])
  83. if os.path.exists(itm["Raw_targetpath"])==True:
  84. shutil.copyfile(itm["Souce_path"], itm["Raw_targetpath"])
  85. # Convert mp4 and Copy
  86. if self.config["nas"]["copy_raw"]==True:
  87. if os.path.exists(itm["Raw_subdir"])==False:
  88. os.mkdir(itm["Raw_subdir"])
  89. if os.path.exists(itm["Raw_targetpath"])==True:
  90. self.SudoCmd("MP4Box -fps "+fps+" -add '"+itm["path"]+"' '"+itm["targetpath"]+"'")
  91. # Delete File
  92. if self.config["nas"]["delete_after_sync"]==True:
  93. os.remove(itm["Souce_path"])
  94. FileIndex+=1
  95. CopiedSize+=os.path.getsize(f)
  96. #self.components.Menu.Progress((FileIndex*100)/FileLength)
  97. self.components.Menu.Progress((CopiedSize*100)/filesizeTotal)
  98. self.UnmountNas()
  99. self.components.Menu.StopProgress()
  100. def Ping(self):
  101. hostname = self.config["nas"]["address"]
  102. response = os.system("ping -c 1 " + hostname)
  103. if response == 0:
  104. return True
  105. else:
  106. return False
  107. def checkSudo(self):
  108. """
  109. Überprüft, ob der Benutzer Sudo-Rechte besitzt
  110. :ret: bool
  111. """
  112. if 'SUDO_UID' in os.environ.keys() or os.geteuid() == 0:
  113. return True
  114. else:
  115. pass # TODO: chekc für Sudo-Test Befehl akzeptiert
  116. return False
  117. def SudoCmd(self, command):
  118. """
  119. Führt einen Sudo Befehl aus.
  120. """
  121. from subprocess import PIPE, run
  122. if 'SUDO_UID' in os.environ.keys() or os.geteuid() == 0:
  123. result = run(command, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
  124. print(result.returncode, result.stdout, result.stderr)
  125. elif "sudo" in self.config["system"]:
  126. if self.config["system"]["sudo"]!=None and isinstance(self.config["system"]["sudo"], str) and self.config["system"]["sudo"]!="":
  127. result = run("echo "+self.config["system"]["sudo"]+" | sudo -S "+command, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
  128. print(result.returncode, result.stdout, result.stderr)
  129. def MountNas(self):
  130. if self.Ping()==False:
  131. print("Failed to Mount. Could not ping NAS")
  132. return False
  133. if self.checkSudo()==False:
  134. print("Failed to Mount. Missing permission for '"+self.config["nas"]["local_path"]+"'")
  135. return False
  136. if os.path.isdir(self.config["nas"]["local_path"]) == False:
  137. self.SudoCmd("mkdir "+self.config["nas"]["local_path"])
  138. # sudo mount -n -w -t cifs //192.168.1.2/freigabe /media/freigabe -o user=pi,pass=raspberry
  139. self.SudoCmd("mount -n -w -t cifs //"+self.config["nas"]["address"]+self.config["nas"]["remote_path"]+" "+self.config["nas"]["local_path"]+" -o user="+self.config["nas"]["username"]+",pass="+self.config["nas"]["password"])
  140. def UnmountNas(self):
  141. self.SudoCmd("unmount //"+self.config["nas"]["address"]+self.config["nas"]["remote_path"])