def AddUPnPMapping(internal_client, internal_port, external_port, protocol, description, duration=3600): cmd = [ upnpc_path, '-e', description, '-a', internal_client, str(internal_port), str(external_port), protocol, str(duration) ] p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=HydrusData.GetSubprocessStartupInfo()) p.wait() (output, error) = p.communicate() if output is not None and 'failed with code' in output: raise Exception('Problem while trying to add UPnP mapping:' + os.linesep * 2 + HydrusData.ToUnicode(output)) if error is not None and len(error) > 0: raise Exception('Problem while trying to add UPnP mapping:' + os.linesep * 2 + HydrusData.ToUnicode(error))
def initialize(self, start_index=0): self.close() if self._mime == HC.IMAGE_GIF: ss = 0 self.pos = 0 skip_frames = start_index else: ss = float(start_index) / self.fps self.pos = start_index skip_frames = 0 (w, h) = self._target_resolution cmd = [ FFMPEG_PATH, '-ss', "%.03f" % ss, '-i', self._path, '-loglevel', 'quiet', '-f', 'image2pipe', "-pix_fmt", self.pix_fmt, "-s", str(w) + 'x' + str(h), '-vcodec', 'rawvideo', '-' ] self.process = subprocess.Popen( cmd, bufsize=self.bufsize, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=HydrusData.GetSubprocessStartupInfo()) if skip_frames > 0: self.skip_frames(skip_frames)
def AddUPnPMapping(internal_client, internal_port, external_port, protocol, description, duration=3600): cmd = [ upnpc_path, '-e', description, '-a', internal_client, str(internal_port), str(external_port), protocol, str(duration) ] p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=HydrusData.GetSubprocessStartupInfo()) HydrusData.WaitForProcessToFinish(p, 30) (output, error) = p.communicate() if 'x.x.x.x:' + str( external_port ) + ' TCP is redirected to internal ' + internal_client + ':' + str( internal_port) in output: raise HydrusExceptions.FirewallException( 'The UPnP mapping of ' + internal_client + ':' + internal_port + '->external:' + external_port + ' already exists as a port forward. If this UPnP mapping is automatic, please disable it.' ) if output is not None and 'failed with code' in output: if 'UnknownError' in output: raise HydrusExceptions.FirewallException( 'Problem while trying to add UPnP mapping:' + os.linesep * 2 + HydrusData.ToUnicode(output)) else: raise Exception('Problem while trying to add UPnP mapping:' + os.linesep * 2 + HydrusData.ToUnicode(output)) if error is not None and len(error) > 0: raise Exception('Problem while trying to add UPnP mapping:' + os.linesep * 2 + HydrusData.ToUnicode(error))
def GetExternalIP(): if HC.options['external_host'] is not None: return HC.options['external_host'] if HydrusData.TimeHasPassed(EXTERNAL_IP['time'] + (3600 * 24)): cmd = [upnpc_path, '-l'] p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=HydrusData.GetSubprocessStartupInfo()) HydrusData.WaitForProcessToFinish(p, 30) (output, error) = p.communicate() if error is not None and len(error) > 0: raise Exception('Problem while trying to fetch External IP:' + os.linesep * 2 + HydrusData.ToUnicode(error)) else: try: lines = HydrusData.SplitByLinesep(output) i = lines.index( ' i protocol exPort->inAddr:inPort description remoteHost leaseTime' ) '''ExternalIPAddress = ip''' (gumpf, external_ip_address) = lines[i - 1].split(' = ') except ValueError: raise Exception('Could not parse external IP!') if external_ip_address == '0.0.0.0': raise Exception( 'Your UPnP device returned your external IP as 0.0.0.0! Try rebooting it, or overwrite it in options!' ) EXTERNAL_IP['ip'] = external_ip_address EXTERNAL_IP['time'] = HydrusData.GetNow() return EXTERNAL_IP['ip']
def GetFFMPEGVersion(): # open the file in a pipe, provoke an error, read output cmd = [FFMPEG_PATH, '-version'] try: proc = subprocess.Popen( cmd, bufsize=10**5, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=HydrusData.GetSubprocessStartupInfo()) except Exception as e: if not os.path.exists(FFMPEG_PATH): return 'no ffmpeg found' else: HydrusData.ShowException(e) return 'unable to execute ffmpeg' infos = proc.stdout.read().decode('utf8') proc.terminate() del proc lines = infos.splitlines() if len(lines) > 0: # typically 'ffmpeg version [VERSION] Copyright ... top_line = lines[0] if top_line.startswith('ffmpeg version '): top_line = top_line.replace('ffmpeg version ', '') if ' ' in top_line: version_string = top_line.split(' ')[0] return version_string return 'unknown'
def RemoveUPnPMapping(external_port, protocol): cmd = [upnpc_path, '-d', str(external_port), protocol] p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=HydrusData.GetSubprocessStartupInfo()) HydrusData.WaitForProcessToFinish(p, 30) (output, error) = p.communicate() if error is not None and len(error) > 0: raise Exception('Problem while trying to remove UPnP mapping:' + os.linesep * 2 + HydrusData.ToUnicode(error))
def do_it(): if HC.PLATFORM_WINDOWS: os.startfile( path ) else: if HC.PLATFORM_OSX: cmd = [ 'open' ] elif HC.PLATFORM_LINUX: cmd = [ 'xdg-open' ] cmd.append( path ) process = subprocess.Popen( cmd, startupinfo = HydrusData.GetSubprocessStartupInfo() ) process.wait() process.communicate()
def RenderPageToFile(path, temp_path, page_index): cmd = [SWFRENDER_PATH, path, '-o', temp_path, '-p', str(page_index)] timeout = HydrusData.GetNow() + 60 p = subprocess.Popen(cmd, startupinfo=HydrusData.GetSubprocessStartupInfo()) while p.poll() is None: if HydrusData.TimeHasPassed(timeout): p.terminate() raise Exception('Could not render the swf page within 60 seconds!') time.sleep(0.5) p.communicate()
def Hydrusffmpeg_parse_infos(filename, print_infos=False): """Get file infos using ffmpeg. Returns a dictionnary with the fields: "video_found", "video_fps", "duration", "video_nframes", "video_duration" "audio_found", "audio_fps" "video_duration" is slightly smaller than "duration" to avoid fetching the uncomplete frames at the end, which raises an error. """ # open the file in a pipe, provoke an error, read output cmd = [FFMPEG_PATH, "-i", filename] is_GIF = filename.endswith('.gif') if is_GIF: if HC.PLATFORM_WINDOWS: cmd += ["-f", "null", "NUL"] else: cmd += ["-f", "null", "/dev/null"] proc = subprocess.Popen(cmd, bufsize=10**5, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=HydrusData.GetSubprocessStartupInfo()) infos = proc.stderr.read().decode('utf8') proc.terminate() del proc if print_infos: # print the whole info text returned by FFMPEG HydrusData.Print(infos) lines = infos.splitlines() if "No such file or directory" in lines[-1]: raise IOError("%s not found ! Wrong path ?" % filename) result = dict() # get duration (in seconds) # Duration: 00:00:02.46, start: 0.033000, bitrate: 1069 kb/s try: keyword = ('frame=' if is_GIF else 'Duration: ') line = [l for l in lines if keyword in l][0] if 'start:' in line: m = re.search('(start\\: )' + '-?[0-9]+\\.[0-9]*', line) start_offset = float(line[m.start() + 7:m.end()]) if abs( start_offset ) > 1.0: # once had a file with start offset of 957499 seconds jej start_offset = 0 else: start_offset = 0 match = re.search("[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9]", line) hms = map(float, line[match.start() + 1:match.end()].split(':')) if len(hms) == 1: result['duration'] = hms[0] elif len(hms) == 2: result['duration'] = 60 * hms[0] + hms[1] elif len(hms) == 3: result['duration'] = 3600 * hms[0] + 60 * hms[1] + hms[2] result['duration'] -= start_offset except: raise IOError("Error reading duration in file %s," % (filename) + "Text parsed: %s" % infos) try: (input_line, ) = [l for l in lines if l.startswith('Input #0')] # Input #0, matroska, webm, from 'm.mkv': text = input_line[10:] mime_text = text.split(', from')[0] result['mime_text'] = mime_text except: pass # get the output line that speaks about video lines_video = [l for l in lines if ' Video: ' in l] result['video_found'] = (lines_video != []) if result['video_found']: line = lines_video[0] # get the size, of the form 460x320 (w x h) match = re.search(" [0-9]*x[0-9]*(,| )", line) s = list(map(int, line[match.start():match.end() - 1].split('x'))) result['video_size'] = s # get the frame rate try: match = re.search("( [0-9]*.| )[0-9]* tbr", line) result['video_fps'] = float( line[match.start():match.end()].split(' ')[1]) except: match = re.search("( [0-9]*.| )[0-9]* fps", line) result['video_fps'] = float( line[match.start():match.end()].split(' ')[1]) num_frames = result['duration'] * result['video_fps'] if num_frames != int(num_frames): num_frames += 1 # rounding up result['video_nframes'] = int(num_frames) result['video_duration'] = result['duration'] # We could have also recomputed the duration from the number # of frames, as follows: # >>> result['video_duration'] = result['video_nframes'] / result['video_fps'] lines_audio = [l for l in lines if ' Audio: ' in l] result['audio_found'] = lines_audio != [] if result['audio_found']: line = lines_audio[0] try: match = re.search(" [0-9]* Hz", line) result['audio_fps'] = int(line[match.start() + 1:match.end()]) except: result['audio_fps'] = 'unknown' return result
def GetUPnPMappings(): external_ip_address = GetExternalIP() cmd = [upnpc_path, '-l'] p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=HydrusData.GetSubprocessStartupInfo()) HydrusData.WaitForProcessToFinish(p, 30) (output, error) = p.communicate() if error is not None and len(error) > 0: raise Exception('Problem while trying to fetch UPnP mappings:' + os.linesep * 2 + HydrusData.ToUnicode(error)) else: try: lines = HydrusData.SplitByLinesep(output) i = lines.index( ' i protocol exPort->inAddr:inPort description remoteHost leaseTime' ) data_lines = [] i += 1 while i < len(lines): if not lines[i][0] in (' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'): break data_lines.append(lines[i]) i += 1 processed_data = [] for line in data_lines: ''' 0 UDP 65533->192.168.0.197:65533 'Skype UDP at 192.168.0.197:65533 (2665)' '' 0''' while ' ' in line: line = line.replace(' ', ' ') if line.startswith(' '): (empty, number, protocol, mapping_data, rest_of_line) = line.split(' ', 4) else: (number, protocol, mapping_data, rest_of_line) = line.split(' ', 3) (external_port, rest_of_mapping_data) = mapping_data.split('->') external_port = int(external_port) (internal_client, internal_port) = rest_of_mapping_data.split(':') internal_port = int(internal_port) (empty, description, space, remote_host, rest_of_line) = rest_of_line.split('\'', 4) lease_time = int(rest_of_line[1:]) processed_data.append( (description, internal_client, internal_port, external_ip_address, external_port, protocol, lease_time)) return processed_data except Exception as e: HydrusData.Print(traceback.format_exc()) raise Exception('Problem while trying to parse UPnP mappings:' + os.linesep * 2 + HydrusData.ToUnicode(e))