def copy_windows(text): # This function is heavily based on # http://msdn.com/ms649016#_win32_Copying_Information_to_the_Clipboard with window() as hwnd: # http://msdn.com/ms649048 # If an application calls OpenClipboard with hwnd set to NULL, # EmptyClipboard sets the clipboard owner to NULL; # this causes SetClipboardData to fail. # => We need a valid hwnd to copy something. with clipboard(hwnd): safeEmptyClipboard() if text: # http://msdn.com/ms649051 # If the hMem parameter identifies a memory object, # the object must have been allocated using the # function with the GMEM_MOVEABLE flag. count = wcslen(text) + 1 handle = safeGlobalAlloc(GMEM_MOVEABLE, count * sizeof(c_wchar)) locked_handle = safeGlobalLock(handle) ctypes.memmove(c_wchar_p(locked_handle), c_wchar_p(text), count * sizeof(c_wchar)) safeGlobalUnlock(handle) safeSetClipboardData(CF_UNICODETEXT, handle)
def __call__(self, w=0, l=0): if type(w) == type("x"): ww = c_wchar_p(w) elif type(w) == type(b"x"): ww = c_char_p(w) elif w is None: ww = WPARAM() else: ww = WPARAM(w) if self._stringResult: lengthBytes = self._fn(self._ptr, self._msg, ww, None) if lengthBytes == 0: return bytearray() result = (ctypes.c_byte * lengthBytes)(0) lengthBytes2 = self._fn(self._ptr, self._msg, ww, result) assert lengthBytes == lengthBytes2 return bytearray(result)[:lengthBytes] else: if type(l) == type("x"): ll = c_wchar_p(l) elif type(l) == type(b"x"): ll = c_char_p(l) elif type(l) == type(1): ll = LPARAM(l) else: ll = l return self._fn(self._ptr, self._msg, ww, ll)
def getmeta(self, meta_name, default=NoDefaultMeta): if meta_name == 'free_space': if platform.system() == 'Windows': try: import ctypes free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(self.root_path), None, None, ctypes.pointer(free_bytes)) return free_bytes.value except ImportError: # Fall through to call the base class pass else: stat = os.statvfs(self.root_path) return stat.f_bfree * stat.f_bsize elif meta_name == 'total_space': if platform.system() == 'Windows': try: import ctypes total_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(self.root_path), None, ctypes.pointer(total_bytes), None) return total_bytes.value except ImportError: # Fall through to call the base class pass else: stat = os.statvfs(self.root_path) return stat.f_blocks * stat.f_bsize return super(OSFS, self).getmeta(meta_name, default)
def __init__(self, name, size, bold=False, italic=False, dpi=None): if not name: name = self._default_name super(GDIPlusFont, self).__init__(name, size, bold, italic, dpi) family = ctypes.c_void_p() name = ctypes.c_wchar_p(name) # Look in private collection first: if self._private_fonts: gdiplus.GdipCreateFontFamilyFromName(name, self._private_fonts, ctypes.byref(family)) # Then in system collection: if not family: gdiplus.GdipCreateFontFamilyFromName(name, None, ctypes.byref(family)) # Nothing found, use default font. if not family: name = self._default_name gdiplus.GdipCreateFontFamilyFromName(ctypes.c_wchar_p(name), None, ctypes.byref(family)) if dpi is None: unit = UnitPoint else: unit = UnitPixel size = (size * dpi) / 72 style = 0 if bold: style |= FontStyleBold if italic: style |= FontStyleItalic self.italic = italic # XXX needed for HACK HACK HACK self._gdipfont = ctypes.c_void_p() gdiplus.GdipCreateFont(family, ctypes.c_float(size), style, unit, ctypes.byref(self._gdipfont))
def prepare_MFO_args( nAuthMode, szPass1, bTimeLimit, tStartTimeW, tEndTimeW, bTimesLimit, nTimes, nRight, szKey1, szSrcFile1, nFileCount, szExeDstFile1 ): ''' Take care of ctypes type for each arguments. Call this before make call to MakeFileOut(). Read the original doc for FileOutDll.dll to see detailed usage. ''' files = ((ctypes.c_wchar * 256) * 250)() for i in xrange(len(szSrcFile1)): files[i].value = unicode(szSrcFile1[i]) return ( ctypes.c_int(nAuthMode), ctypes.c_wchar_p(unicode(szPass1)), ctypes.c_bool(bTimeLimit), ctypes.c_wchar_p(unicode(tStartTimeW)), ctypes.c_wchar_p(unicode(tEndTimeW)), ctypes.c_bool(bTimesLimit), ctypes.c_int(nTimes), ctypes.c_int(nRight), ctypes.c_wchar_p(szKey1), files, ctypes.c_int(nFileCount), ctypes.c_wchar_p(unicode(szExeDstFile1)) )
def _do_open_dlg(func, window, title, filters, flags): assert isinstance(title, unicode) buf = create_unicode_buffer(1024) ofn = OPENFILENAME() ofn.lStructSize = sizeof(OPENFILENAME) ofn.lpstrFile = cast(pointer(buf), LPWSTR) ofn.nMaxFile = 1024 ofn.lpstrTitle = c_wchar_p(title) ofn.flags = flags if window: ofn.hwndOwner = window._hwnd filters = flatten(filters) or [u"All files(*.*)", u"*.*"] assert all([isinstance(i, unicode) for i in filters]) assert len(filters) % 2 == 0 filters = u"\0".join(filters) + u"\0\0" ofn.lpstrFilter = c_wchar_p(filters) func(byref(ofn)) rst = buf[:].strip("\0") if flags & OFN_ALLOWMULTISELECT: return rst.split("\0") else: return rst
def _remove_persistent_login(self, persistent_login): self._run_and_check_output( iscsidsc.RemoveIScsiPersistentTargetW, ctypes.c_wchar_p(persistent_login.InitiatorInstance), persistent_login.InitiatorPortNumber, ctypes.c_wchar_p(persistent_login.TargetName), ctypes.byref(persistent_login.TargetPortal))
def getFrames(self): frames = [] #current_buffer = ctypes.POINTER(ctypes.c_char)() current_buffer = ctypes.c_void_p() buffer_size = ctypes.c_longlong() while(self.waitBuffer(current_buffer, buffer_size)): # Convert the buffer to an image. check(sdk3_utility.AT_ConvertBuffer(current_buffer, ctypes.c_void_p(self.frame_data[self.frame_data_cur].getDataPtr()), ctypes.c_long(self.frame_x), ctypes.c_long(self.frame_y), ctypes.c_long(self.stride), ctypes.c_wchar_p(self.pixel_encoding), ctypes.c_wchar_p("Mono16")), "AT_ConvertBuffer") frames.append(self.frame_data[self.frame_data_cur]) # Update current frame. self.frame_data_cur += 1 if (self.frame_data_cur == len(self.frame_data)): self.frame_data_cur = 0 # Re-queue the buffers. check(sdk3.AT_QueueBuffer(self.camera_handle, current_buffer, buffer_size)) return [frames, [self.frame_x, self.frame_y]]
def _create_window(self): if self.hwnd: return if not self.hinstance: self.hinstance = self.kernel32.GetModuleHandleW(0) if not self.parent_hwnd: self.parent_hwnd = self._find_parent_wnd() print 'hinst: %08X, parent: %08X' % (self.hinstance, self.parent_hwnd) flags = self.WS_CHILD if self.parent_hwnd else self.WS_POPUP self.hwnd = self.user32.CreateWindowExW(0, C.c_wchar_p('STATIC'), C.c_wchar_p('Labeless'), flags, 0, 0, 100, 100, self.parent_hwnd, 0, self.hinstance, 0) if not self.hwnd: raise Exception('Unable to create helper window, le:%08X' % self.kernel32.GetLastError()) WndProcType = C.WINFUNCTYPE(C.c_int, C.c_long, C.c_int, C.c_int, C.c_int) self.old_wndproc = self.user32.SetWindowLongW(self.hwnd, C.c_int(self.GWL_WNDPROC), WndProcType(self._wnd_proc)) self.hlpLogMessageId = self.user32.RegisterWindowMessageW(C.c_wchar_p("{B221E840-FBD2-4ED3-A69E-3DDAB1F7EC36}")) if not self.hlpLogMessageId: print >> sys.stdout, "RegisterWindowMessageW(hlpLogMessageId) failed. LastError: %08X" % self.kernel32.GetLastError() return False self.hlpCommandReceived = self.user32.RegisterWindowMessageW(C.c_wchar_p("{79F0D105-76FF-40DB-9448-E9D9E5BA7938}")) if not self.hlpCommandReceived: print >> sys.stdout, "RegisterWindowMessageW(hlpCommandReceived) failed. LastError: %08X" % self.kernel32.GetLastError() return False self.hlpPortChanged = self.user32.RegisterWindowMessageW(C.c_wchar_p("{774A37C9-6398-44AD-8F07-A421B55F0435}")) if not self.hlpPortChanged: print >> sys.stdout, "RegisterWindowMessageW(hlpPortChanged) failed. LastError: %08X" % self.kernel32.GetLastError() return False return True
def move(srcfile, destfile, overwrite, warn_between_drives=False, traceToStdout=False): if not exists(srcfile): raise IOError('source path does not exist') if traceToStdout: trace('move()', srcfile, destfile) if srcfile == destfile: pass elif sys.platform.startswith('win'): from ctypes import windll, c_wchar_p, c_int, GetLastError ERROR_NOT_SAME_DEVICE = 17 flags = 0 flags |= 1 if overwrite else 0 flags |= 0 if warn_between_drives else 2 res = windll.kernel32.MoveFileExW(c_wchar_p(srcfile), c_wchar_p(destfile), c_int(flags)) if not res: err = GetLastError() if err == ERROR_NOT_SAME_DEVICE and warn_between_drives: rinput('Note: moving file from one drive to another. ' + '%s %s Press Enter to continue.\r\n'%(srcfile, destfile)) return move(srcfile, destfile, overwrite, warn_between_drives=False) raise IOError('MoveFileExW failed (maybe dest already exists?) err=%d' % err + getPrintable(srcfile + '->' + destfile)) elif sys.platform.startswith('linux') and overwrite: _os.rename(srcfile, destfile) else: copy(srcfile, destfile, overwrite) _os.unlink(srcfile) assertTrue(exists(destfile))
def _login_iscsi_target(self, target_name, portal=None, login_opts=None, is_persistent=True, initiator_name=None): session_id = iscsi_struct.ISCSI_UNIQUE_SESSION_ID() connection_id = iscsi_struct.ISCSI_UNIQUE_CONNECTION_ID() portal_ref = ctypes.byref(portal) if portal else None login_opts_ref = ctypes.byref(login_opts) if login_opts else None initiator_name_ref = (ctypes.c_wchar_p(initiator_name) if initiator_name else None) # If the portal is not provided, the initiator will try to reach any # portal exporting the requested target. self._run_and_check_output( iscsidsc.LoginIScsiTargetW, ctypes.c_wchar_p(target_name), False, # IsInformationalSession initiator_name_ref, ctypes.c_ulong(iscsi_struct.ISCSI_ANY_INITIATOR_PORT), portal_ref, iscsi_struct.ISCSI_SECURITY_FLAGS( iscsi_struct.ISCSI_DEFAULT_SECURITY_FLAGS), None, # Security flags / mappings (using default / auto) login_opts_ref, ctypes.c_ulong(0), None, # Preshared key size / key is_persistent, ctypes.byref(session_id), ctypes.byref(connection_id), ignored_error_codes=[iscsierr.ISDSC_TARGET_ALREADY_LOGGED_IN]) return session_id, connection_id
def GenerateResult (self): resultFilePath = os.path.join (self.resultsFolder, 'result.html') htmlTableWriter = HTMLTableWriter.HTMLTableWriter (resultFilePath, 'Result') htmlTableWriter.WriteHeader (); htmlTableWriter.WriteTableHeader (['file name', 'image 1', 'image 2', 'diff image', 'diff count', 'result']); for fileName in os.listdir (self.referencesFolder): filePath1 = os.path.join (self.referencesFolder, fileName) filePath2 = os.path.join (self.currentFolder, fileName) filePath3 = os.path.join (self.differencesFolder, fileName) column1 = '<a href="../' + self.referencesFolder + '/' + fileName + '">image</a>'; column2 = '<a href="../' + self.currentFolder + '/' + fileName + '">image</a>'; column3 = '<a href="../' + self.differencesFolder + '/' + fileName + '">image</a>'; if not os.path.exists (filePath1) or not os.path.exists (filePath2): result = '<span class="failed">not exists</span>' htmlTableWriter.WriteTableRow ([fileName, column1, column2, '-', '-', result]); continue diffRes = self.testRunner.TRCompareImages (ctypes.c_wchar_p (filePath1), ctypes.c_wchar_p (filePath2), ctypes.c_wchar_p (filePath3)) if diffRes == -1: result = '<span class="failed">not equal size</span>' htmlTableWriter.WriteTableRow ([fileName, column1, column2, '-', '-', result]); continue if diffRes > 0: result = '<span class="failed">failed</span>' htmlTableWriter.WriteTableRow ([fileName, column1, column2, column3, str (diffRes), result]); continue result = '<span class="succeeded">succeeded</span>' htmlTableWriter.WriteTableRow ([fileName, column1, column2, '-', '-', result]); htmlTableWriter.WriteTableFooter (); htmlTableWriter.WriteFooter ();
def getEnumeratedString(handle, command): max_size = 100 response = ctypes.c_wchar_p(' ' * max_size) if check(sdk3.AT_GetEnumStringByIndex(handle, ctypes.c_wchar_p(command), ctypes.c_longlong(getEnumeratedIndex(handle, command)), response, max_size), "AT_GetEnumStringByIndex"): return response.value else: return ''
def logi_arx_set_tags_content_by_class(tag_class, new_content): """ change at runtime the content (innerHTML) of a tag with the class tag_class from the old content to the new_content. """ if arx_dll: tag_class = ctypes.c_wchar_p(tag_class) new_content = ctypes.c_wchar_p(new_content) return bool(arx_dll.LogiArxSetTagsPropertyByClass(tag_class, new_content)) else: return False
def logi_arx_set_tag_content_by_id(tag_id, new_content): """ change at runtime the content (innerHTML) of a tag with the id tag_id from the old content to the new_content. """ if arx_dll: tag_id = ctypes.c_wchar_p(tag_id) new_content = ctypes.c_wchar_p(new_content) return bool(arx_dll.LogiArxSetTagContentById(tag_id, new_content)) else: return False
def get(): OpenClipboard(None) handle = GetClipboardData(CF_UNICODETEXT) data = ctypes.c_wchar_p(handle).value pcontents = GlobalLock(handle) data = ctypes.c_wchar_p(pcontents).value if pcontents else u'' GlobalUnlock(handle) CloseClipboard() return data
def logi_arx_add_utf8_string_as(string_content, file_name, mime_type = None): """ sends a UTF8 string to the device and saves it to a virtual file called file_name. mime_type, if assigned, specifies the MIME type of the file. """ if arx_dll: string_content = ctypes.c_wchar_p(string_content) file_name = ctypes.c_wchar_p(file_name) mime_type = ctypes.c_wchar_p(mime_type) if mime_type else ctypes.c_wchar_p('') return bool(arx_dll.LogiArxAddUTF8StringAs(string_content, file_name, mime_type)) else: return False
def logi_arx_set_tags_property_by_class(tag_class, prop, new_value): """ change at runtime a prop (property) on the tag with the class tag_class from the old value to the new_value. """ if arx_dll: tag_class = ctypes.c_wchar_p(tag_class) prop = ctypes.c_wchar_p(prop) new_value = ctypes.c_wchar_p(new_value) return bool(arx_dll.LogiArxSetTagsPropertyByClass(tag_class, prop, new_value)) else: return False
def logi_arx_set_tag_property_by_id(tag_id, prop, new_value): """ change at runtime a prop (property) on the tag with the id tag_id from the old value to the new_value. """ if arx_dll: tag_id = ctypes.c_wchar_p(tag_id) prop = ctypes.c_wchar_p(prop) new_value = ctypes.c_wchar_p(new_value) return bool(arx_dll.LogiArxSetTagPropertyById(tag_id, prop, new_value)) else: return False
def logi_arx_add_file_as(file_path, file_name, mime_type = None): """ sends a file to the device from local a file_path and assigns a file_name to it. mime_type, if assigned, specifies the MIME type of the file. """ if arx_dll: file_path = ctypes.c_wchar_p(file_path) file_name = ctypes.c_wchar_p(file_name) mime_type = ctypes.c_wchar_p(mime_type) if mime_type else ctypes.c_wchar_p('') return bool(arx_dll.LogiArxAddFileAs(file_path, file_name, mime_type)) else: return False
def create_win32_window(self, window_class=None, text="", style=0, identifier=None, ): window_class = window_class or self.window_class window_class = c_wchar_p(window_class) text = c_wchar_p(text) style |= self.default_style style |= self.control_style x, y, width, height = [int(i) for i in self._geometry] parent = self.window._impl self._impl = user32.CreateWindowExW(0, window_class, text, style, x, y, width, height, parent, identifier, 0, 0)
def copy(self, src, dest): # With large files this is 2x-3x faster than shutil.copy(src, dest), # especially with UNC targets. kernel32 = ctypes.windll.kernel32 kernel32.CopyFileW.restype = wintypes.BOOL retcode = kernel32.CopyFileW(ctypes.c_wchar_p(src), ctypes.c_wchar_p(dest), wintypes.BOOL(True)) if not retcode: raise IOError(_("The file copy from %(src)s to %(dest)s failed.") % {"src": src, "dest": dest})
def getDigitalSigner(filepath): if os.path.splitext(filepath)[1] not in extlist: return None pStr = ctypes.c_wchar_p(filepath) temp = dll.GetDigitalSigner(pStr) result = ctypes.c_wchar_p(temp).value if result: return result return None
def logi_arx_add_content_as(content, size, file_name, mime_type = None): """ sends content to the device and saves it to a virtual file called file_name. mime_type, if assigned, specifies the MIME type of the file. """ if arx_dll: content = ctypes.c_void_p(content) size = ctypes.c_int(size) file_name = ctypes.c_wchar_p(file_name) mime_type = ctypes.c_wchar_p(mime_type) if mime_type else ctypes.c_wchar_p('') return bool(arx_dll.LogiArxAddContentAs(content, size, file_name, mime_type)) else: return False
def __login(self): setSoftInfo = self.uu.uu_setSoftInfoW s_id = c_int(111830) s_key = c_wchar_p('adfa045fc2c547aea45362915e1e0450') setSoftInfo(s_id, s_key) login = self.uu.uu_loginW username = c_wchar_p(self.username) password = c_wchar_p(self.password) user_id = login(username, password)
def getString(handle, command): maxLength = ctypes.c_int() if not check(sdk3.AT_GetStringMaxLength(handle, ctypes.c_wchar_p(command), ctypes.byref(maxLength)), "AT_GetStringMaxLength"): return '' response = ctypes.c_wchar_p(' ' * maxLength.value) if check(sdk3.AT_GetString(handle, ctypes.c_wchar_p(command), response, maxLength), "AT_GetString"): return response.value else: return ''
def recognize_by_path(self, image_path, code_type): self.__login() captcha_recognize = self.uu.uu_recognizeByCodeTypeAndPathW result = c_wchar_p(' ') # 申请内存空间 code_id = captcha_recognize(c_wchar_p(image_path), c_int(code_type), result) if code_id <= 0: self.report_error(code_id) return '', code_id code = result.value.split('_')[-1] return code, code_id
def set_wallpaper_direct(pic_path): tile = u"0" style = u"10" set_registry_value(HKEY_CURRENT_USER, u'Control Panel\\Desktop', u"TileWallpaper", REG_SZ, ctypes.c_wchar_p(tile), len(tile)) set_registry_value(HKEY_CURRENT_USER, u'Control Panel\\Desktop', u"WallpaperStyle", REG_SZ, ctypes.c_wchar_p(style), len(style)) bmp_path = os.path.splitext(pic_path)[0] + '.bmp' Image.open(pic_path).save(bmp_path, format='BMP') done = ctypes.windll.user32.SystemParametersInfoW(0x0014, 0, ctypes.create_unicode_buffer(bmp_path), 1) print('set wallpaper', 'successfully' if done else 'failed')
def logi_arx_init(identifier, friendly_name, py_callback_function = None): """ initializes the applet on the app with the given friendly_name. """ if arx_dll: global on_callback global callback_ref on_callback = py_callback_function if py_callback_function else default_callback callback_ref = ctypes.byref(CALLBACK_DEFINITION(callback_wrapper)) identifier = ctypes.c_wchar_p(identifier) friendly_name = ctypes.c_wchar_p(friendly_name) return bool(arx_dll.LogiArxInit(identifier, friendly_name, callback_ref)) else: return False
def getDigitalSigner(filepath): try: if os.path.splitext(filepath)[1] not in ['.exe', '.dll', '.sys']: return None pStr = ctypes.c_wchar_p(filepath) temp = dll.GetDigitalSigner(pStr) result = ctypes.c_wchar_p(temp).value result=str(result.replace('\n','\t')) if result<>'': return result return None except: print '文件类型不对!'
def unicode_as_lparam(source): pointer = ctypes.cast(ctypes.c_wchar_p(source), ctypes.c_void_p) return LPARAM(pointer.value)
def get_free_space(folder='/', unit='auto'): """Get the free space on the drive/folder marked by folder. Returns a float of unit unit. folder - (optional) a string uri to a folder or drive on disk. Defaults to '/' ('C:' on Windows') unit - (optional) a string, one of ['B', 'MB', 'GB', 'TB', 'auto']. If 'auto', the unit returned will be automatically calculated based on available space. Defaults to 'auto'. returns a string marking the space free and the selected unit. Number is rounded to two decimal places.'""" units = {'B': 1024, 'MB': 1024**2.0, 'GB': 1024**3.0, 'TB': 1024**4.0} if platform.system() == 'Windows': if folder == '/': folder = 'C:' free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(folder), None, None, ctypes.pointer(free_bytes)) free_space = free_bytes.value else: try: space = os.statvfs(folder) except OSError: # Thrown when folder does not yet exist # In this case, we need to take the path to the desired folder and # walk backwards along its directory tree until we find the mount # point. This mount point is then used for statvfs. abspath = os.path.abspath(folder) while not os.path.ismount(abspath): abspath = os.path.dirname(abspath) space = os.statvfs(abspath) # space.f_frsize is the fundamental file system block size # space.f_bavail is the num. free blocks available to non-root user free_space = (space.f_frsize * space.f_bavail) # If antomatic unit detection is preferred, do it. Otherwise, just get the # unit desired from the units dictionary. if unit == 'auto': units = sorted(units.iteritems(), key=lambda unit: unit[1], reverse=True) selected_unit = units[0] for unit, multiplier in units: free_unit = free_space / multiplier if free_unit % 1024 == free_unit: selected_unit = (unit, multiplier) factor = selected_unit[1] # get the multiplier unit = selected_unit[0] else: factor = units[unit] # Calculate space available in desired units, rounding to 2 places. space_avail = round(free_space/factor, 2) # Format the return string. return str('%s %s' % (space_avail, unit))
# file formats (CH 13) x['CSVReaderType'] = csv.reader(_cstrI) x['CSVWriterType'] = csv.writer(_cstrO) x['CSVDictReaderType'] = csv.DictReader(_cstrI) x['CSVDictWriterType'] = csv.DictWriter(_cstrO, {}) # cryptographic services (CH 14) x['HashType'] = hashlib.md5() x['HMACType'] = hmac.new(_in) # generic operating system services (CH 15) if HAS_CURSES: pass #x['CursesWindowType'] = _curwin = curses.initscr() #FIXME: messes up tty #x['CursesTextPadType'] = textpad.Textbox(_curwin) #x['CursesPanelType'] = panel.new_panel(_curwin) if HAS_CTYPES: x['CCharPType'] = ctypes.c_char_p() x['CWCharPType'] = ctypes.c_wchar_p() x['CVoidPType'] = ctypes.c_void_p() if sys.platform[:3] == 'win': x['CDLLType'] = _cdll = ctypes.cdll.msvcrt else: x['CDLLType'] = _cdll = ctypes.CDLL(None) if not IS_PYPY: x['PyDLLType'] = _pydll = ctypes.pythonapi x['FuncPtrType'] = _cdll._FuncPtr() x['CCharArrayType'] = ctypes.create_string_buffer(1) x['CWCharArrayType'] = ctypes.create_unicode_buffer(1) x['CParamType'] = ctypes.byref(_cchar) x['LPCCharType'] = ctypes.pointer(_cchar) x['LPCCharObjType'] = _lpchar = ctypes.POINTER(ctypes.c_char) x['NullPtrType'] = _lpchar() x['NullPyObjectType'] = ctypes.py_object()
def getenumerated(self, strcommand): """Run command and set Enumerated return value. """ result = ct.c_int() command = ct.c_wchar_p(strcommand) self.lib.AT_GetEnumerated(self.AT_H, command, ct.addressof(result))
def setenumstring(self, strcommand, item): """Set command with EnumeratedString value parameter. """ command = ct.c_wchar_p(strcommand) item = ct.c_wchar_p(item) self.lib.AT_SetEnumString(self.AT_H, command, item)
def _paste_text(self, sid,s): self._get_osmodule().pasteText(sid,ctypes.c_wchar_p(unicode(s)))
def sendCommand(handle, command): return check(sdk3.AT_Command(handle, ctypes.c_wchar_p(command)), "AT_Command", command)
def command(self, strcommand): """Run command. """ command = ct.c_wchar_p(strcommand) self.lib.AT_Command(self.AT_H, command)
def getdrivesize(path): if _platform == "win32": free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW( ctypes.c_wchar_p(path), None, None, ctypes.pointer(free_bytes)) return free_bytes.value
def getBoolean(handle, command): read_bool = ctypes.c_bool(False) check( sdk3.AT_GetBool(handle, ctypes.c_wchar_p(command), ctypes.byref(read_bool)), "AT_GetBool", command) return read_bool.value
def delete(sql, client, sub_servers, C_lib): names = sql.MakeList(client) c = 0 if names == 0: client["socket"].send('UPLOAD!') else: listt = '\n'.join(x[0] for x in names) client["socket"].send(listt) no = client["socket"].recv(10) print "Here is filename user want to delete...", no, names[int(no) - 1][0] #c = sql.exeq('select count(m_checksum) from log where m_checksum="%s"'%(names[int(no)-1][1])) not working...??? c = sql.exeq( 'select c_checksum from 256kb_chunks where m_checksum="%s" limit 1' % (names[int(no) - 1][1])) sql.exeq('delete from log where username="******" and filename="%s";' % (client["username"], names[int(no) - 1][0])) r = sql.exeq( 'select c_checksum from 256kb_chunks where m_checksum = "%s"' % (names[int(no) - 1][1])) c = ctypes.c_int(C_lib.GET_COUNT(ctypes.c_char_p(c[0][0]))) c = c.value if c == 1: sql.exeq('delete from 256kb_chunks where m_checksum="%s"' % (names[int(no) - 1][1])) for i in r: print "]]]]]]]]]]]]]>>>>>", c if c == 1: print "HERERE", i[0] ips = ctypes.c_wchar_p(C_lib.SEARCH_NODE(ctypes.c_char_p( i[0]))) ipss = chunks_manager.intoip(ips.value) print "---------->>>>>> ips from deleter.py", ipss for j in ipss: print "Created deletion Thread to", j Thread(target=_sub_del, args=( sub_servers[0][sub_servers[1].index(j)], i[0], )).start() oo = ctypes.c_int(C_lib.GET_COUNT(ctypes.c_char_p(i[0]))) print "Count of", i[0], "is", oo.value g = ctypes.c_int(C_lib.DEC_COUNT(ctypes.c_char_p(i[0]))) oo = ctypes.c_int(C_lib.GET_COUNT(ctypes.c_char_p(i[0]))) print "decreased of", i[0], "is", oo.value if g.value == 1: print "Successfully decreased count of", i[0] if oo.value == 0: sql.exeq('delete from 256kb_chunks where m_checksum="%s"' % (names[int(no) - 1][1])) ips = ctypes.c_wchar_p( C_lib.SEARCH_NODE(ctypes.c_char_p(i[0]))) ipss = chunks_manager.intoip(ips.value) print "~~~~~~~~}}} ips from deleter.py", ipss for j in ipss: print "Created deletion Thread to", j Thread(target=_sub_del, args=( sub_servers[0][sub_servers[1].index(j)], i[0], )).start() else: print "Failed to decrease count of", i[0] sql.exeq('commit') print "Ended deletion..." return
def setString(handle, command, string): return check( sdk3.AT_SetString(handle, ctypes.c_wchar_p(command), ctypes.c_wchar_p(string)), "AT_SetString", command)
def setEnumeratedIndex(handle, command, index): return check( sdk3.AT_SetEnumIndex(handle, ctypes.c_wchar_p(command), ctypes.c_longlong(index)), "AT_SetEnumIndex", command)
def setBoolean(handle, command, bool_value): return check( sdk3.AT_SetBool(handle, ctypes.c_wchar_p(command), ctypes.c_bool(bool_value)), "AT_SetBool", command)
def EnumWindowsCallback(hwnd, lparam): global hwnd_note hh = c_wchar_p('EnumWindowsCallback') tt = c_wchar_p(f'hwnd {hwnd}') # int MessageBox( # HWND hWnd, # LPCTSTR lpText, # LPCTSTR lpCaption, # UINT uType # ); #MessageBox(0,tt,hh,0x00000004 + 0x00000040) # int GetWindowTextA( # HWND hWnd, # LPSTR lpString, # int nMaxCount # ); length = GetWindowTextLength(hwnd) + 1 buffer = create_string_buffer(length) GetWindowText(hwnd, buffer, length) # BOOL IsWindowVisible( # HWND hWnd # ); if (IsWindowVisible(hwnd) and length != 0): # DWORD GetWindowThreadProcessId( # HWND hWnd, # LPDWORD lpdwProcessId # ); ProcessID = DWORD() GetWindowThreadProcessId(hwnd, byref(ProcessID)) # HANDLE OpenProcess( # DWORD dwDesiredAccess, # BOOL bInheritHandle, # DWORD dwProcessId # ); PROCESS_ALL_ACCESS = 0x1fffff PROCESS_QUERY_INFORMATION = 0x0400 PROCESS_VM_READ = 0x0010 hProcess = HANDLE() hProcess = OpenProcess(PROCESS_QUERY_INFORMATION + PROCESS_VM_READ, False, ProcessID.value) if (hProcess != 0): nameProc = create_string_buffer(MAX_PATH) # DWORD GetProcessImageFileNameA( # HANDLE hProcess, # LPSTR lpImageFileName, # DWORD nSize # ); if (GetProcessImageFileName(hProcess, nameProc, getsizeof(nameProc)) != 0): exe = path.split(nameProc.value)[1] if exe == b'notepad.exe': print(f'bingo notepad.exe found {exe}') hwnd_note = hwnd else: print(f'[**] Error GetProcessImageFileName {hProcess}') CloseHandle(hProcess) else: print(f"[**] GetLastError {GetLastError()}") print( f'[**] Error OpenProcess {buffer.value} PID {ProcessID.value}' ) #return from EnumWindowsCallback return True
def approach(): msg = json.dumps({"MsgType": "approach", "Param": ""}) cds.cbData = ctypes.sizeof(ctypes.create_unicode_buffer(msg)) cds.lpData = ctypes.c_wchar_p(msg) SendMessage(ai_hnd, win32con.WM_COPYDATA, ctypes.byref(cds), ctypes.byref(cds))
from MaterialLibraryInterface import LibraryManager import getpass import uuid import ctypes import os if __name__ == "__main__": #run only if main #get path to public documents path = ctypes.c_wchar_p(chr(0x00) * 256) FOLDERID_Documents = ctypes.c_char_p( uuid.UUID("ED4824AF-DCE4-45A8-81E2-FC7965083634").bytes_le) ctypes.windll.shell32.SHGetKnownFolderPath(FOLDERID_Documents, 0, None, ctypes.byref(path)) libraryLocation = os.path.join(path.value, "META Documents", "MaterialLibrary", "material_library.json") library_manager = LibraryManager(libraryLocation) username = raw_input("Username: "******"Password: ") matList = library_manager.checkVersion(username, password)
def findInList(self, text, reverse, caseSensitive, stopCheck=lambda: False): """performs search in item list, via shell32 object.""" curFolder = self.curWindow.Document.Folder # names of children objects of current list item, # as "size", "modify date", "duration"... # note that icon has no name detailNames = [c.name for c in self.children if c.name] # corresponding indexes to query info for each file detailIndexes = [] # 500 limit seems reasonable (they are 300+ on my system!) for index in rangeFunc(0, 500): # localized detail name, as "size" detailName = curFolder.GetDetailsOf("", index) # we get index corresponding to name, so update lists if detailName in detailNames: detailNames.remove(detailName) detailIndexes.append(index) # to speed-up process, we want only visible details if not detailNames: break # useful to compute size bytePerSector = ctypes.c_ulonglong(0) # path without leading file:// curPath = self.curWindow.LocationURL.rsplit("/", 1)[0][8:] # we get from current path, to ensure precision # also on external drives or different partitions getBytePerSector( ctypes.c_wchar_p(curPath), None, ctypes.pointer(bytePerSector), None, None, ) listLen = self.positionInfo["similarItemsInGroup"] # 1-based index curIndex = self.positionInfo["indexInGroup"] # pointer to item list items = curFolder.Items() res = None if reverse: # indexes = rangeFunc(curIndex-2,-1,-1) # unfortunately, list pointer seems to change # for each query in reverse order # so, this range indexes = rangeFunc(0, curIndex - 1) else: indexes = rangeFunc(curIndex, listLen) for index in indexes: # pointer to item item = items.Item(index) # detail value list tempItemInfo = [] for index in detailIndexes: # getDetailsOf(item, 1) returns file size in KB, MB, etc, # item.size returns as file size in bytes # but explorer shows file size on disk, in kilobytes... if (index == 1) and not item.IsFolder: # formula below is an optimization of ((item.size-1)/bytePerSector.value+1)*bytePerSector.value diskSizeB = ( (item.size - 1) & ~(bytePerSector.value - 1) ) + bytePerSector.value if item.size > 512 else 1024 diskSizeKB = int(round(diskSizeB / 1024.0)) # to insert thousands separator formattedSize = locale.format_string( '%d', diskSizeKB, True) formattedSize = formattedSize if py3 else formattedSize.decode( 'mbcs') explorerSize = ' '.join([formattedSize, "KB"]) tempItemInfo.append(explorerSize) else: tempItemInfo.append(curFolder.GetDetailsOf(item, index)) # our reconstruction of item as shown in explorer itemInfo = '; '.join(tempItemInfo) # finally, the search if if ((not caseSensitive and text.lower() in itemInfo.lower()) or (caseSensitive and text in itemInfo)): res = item if not reverse: # we can stop; if reverse # we must scroll everything break return res
def wait_named_pipe(self, pipe_name, timeout=WAIT_PIPE_DEFAULT_TIMEOUT): """Wait a given ammount of time for a pipe to become available.""" self._run_and_check_output(kernel32.WaitNamedPipeW, ctypes.c_wchar_p(pipe_name), timeout * units.k)
def _updateCache(): global _removableCache while True: drives = [] if platform.system() == "Windows": from ctypes import windll import ctypes bitmask = windll.kernel32.GetLogicalDrives() for letter in string.uppercase: if letter != 'A' and letter != 'B' and bitmask & 1 and windll.kernel32.GetDriveTypeA( letter + ':/') == 2: volumeName = '' nameBuffer = ctypes.create_unicode_buffer(1024) if windll.kernel32.GetVolumeInformationW( ctypes.c_wchar_p(letter + ':/'), nameBuffer, ctypes.sizeof(nameBuffer), None, None, None, None, 0) == 0: volumeName = nameBuffer.value if volumeName == '': volumeName = 'NO NAME' freeBytes = ctypes.c_longlong(0) if windll.kernel32.GetDiskFreeSpaceExA( letter + ':/', ctypes.byref(freeBytes), None, None) == 0: continue if freeBytes.value < 1: continue drives.append(('%s (%s:)' % (volumeName, letter), letter + ':/', volumeName)) bitmask >>= 1 elif platform.system() == "Darwin": p = subprocess.Popen(['system_profiler', 'SPUSBDataType', '-xml'], stdout=subprocess.PIPE) xml = ElementTree.fromstring(p.communicate()[0]) p.wait() xml = _parseStupidPListXML(xml) for dev in _findInTree(xml, 'Mass Storage Device'): if 'removable_media' in dev and dev[ 'removable_media'] == 'yes' and 'volumes' in dev and len( dev['volumes']) > 0: for vol in dev['volumes']: if 'mount_point' in vol: volume = vol['mount_point'] drives.append( (os.path.basename(volume), volume + '/', os.path.basename(volume))) p = subprocess.Popen( ['system_profiler', 'SPCardReaderDataType', '-xml'], stdout=subprocess.PIPE) xml = ElementTree.fromstring(p.communicate()[0]) p.wait() xml = _parseStupidPListXML(xml) for entry in xml: if '_items' in entry: for item in entry['_items']: for dev in item['_items']: if 'removable_media' in dev and dev[ 'removable_media'] == 'yes' and 'volumes' in dev and len( dev['volumes']) > 0: for vol in dev['volumes']: if 'mount_point' in vol: volume = vol['mount_point'] drives.append( (os.path.basename(volume), volume + '/', os.path.basename(volume))) else: for volume in glob.glob('/media/*'): if os.path.ismount(volume): drives.append((os.path.basename(volume), volume + '/', os.path.basename(volume))) elif volume == '/media/' + os.getenv('USER'): for volume in glob.glob('/media/' + os.getenv('USER') + '/*'): if os.path.ismount(volume): drives.append( (os.path.basename(volume), volume + '/', os.path.basename(volume))) _removableCache = drives time.sleep(1)
def ask(s): msg = json.dumps({"MsgType": "RecoginizeByFile", "Param": s}) cds.cbData = ctypes.sizeof(ctypes.create_unicode_buffer(msg)) cds.lpData = ctypes.c_wchar_p(msg) SendMessage(ai_hnd, win32con.WM_COPYDATA, ctypes.byref(cds), ctypes.byref(cds))
def get_environment(): """ Devuelve las variables de entorno del OS, de Kodi y de Alfa más habituales, necesarias para el diagnóstico de fallos """ try: import base64 import ast PLATFORM = config.get_system_platform() environment = config.get_platform(full_version=True) environment['num_version'] = str(environment['num_version']) environment['python_version'] = '%s (%s, %s)' % (str(platform.python_version()), \ str(sys.api_version), str(platform.python_implementation())) environment['os_release'] = str(platform.release()) environment['prod_model'] = '' try: import multiprocessing environment['proc_num'] = ' (%sx)' % str(multiprocessing.cpu_count()) except: environment['proc_num'] = '' if PLATFORM in ['windows', 'xbox']: environment['os_name'] = PLATFORM.capitalize() try: if platform.platform(): environment['os_release'] = str(platform.platform()).replace('Windows-', '') elif platform._syscmd_ver()[2]: environment['os_release'] = str(platform._syscmd_ver()[2]) command = ["wmic", "cpu", "get", "name"] p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=0x08000000) output_cmd, error_cmd = p.communicate() if PY3 and isinstance(output_cmd, bytes): output_cmd = output_cmd.decode() output_cmd = re.sub(r'\n|\r|\s{2}', '', output_cmd) environment['prod_model'] = str(scrapertools.find_single_match(output_cmd, \ '\w+.*?(?i)(?:Intel\(R\))?(?:\s*Core\(TM\))\s*(.*?CPU.*?)\s*(?:\@|$)')) except: pass elif PLATFORM in ['android', 'atv2']: environment['os_name'] = PLATFORM.capitalize() try: for label_a in subprocess.check_output('getprop').split(FF): if PY3 and isinstance(label_a, bytes): label_a = label_a.decode() if 'build.version.release' in label_a: environment['os_release'] = str(scrapertools.find_single_match(label_a, ':\s*\[(.*?)\]$')) if 'product.model' in label_a: environment['prod_model'] = str(scrapertools.find_single_match(label_a, ':\s*\[(.*?)\]$')) except: try: for label_a in filetools.read(os.environ['ANDROID_ROOT'] + '/build.prop').split(): if PY3 and isinstance(label_a, bytes): label_a = label_a.decode() if 'build.version.release' in label_a: environment['os_release'] = str(scrapertools.find_single_match(label_a, '=(.*?)$')) if 'product.model' in label_a: environment['prod_model'] = str(scrapertools.find_single_match(label_a, '=(.*?)$')) except: pass environment['prod_model'] += ' (%s)' % config.is_rooted(silent=True) elif PLATFORM in ['linux']: environment['os_name'] = PLATFORM.capitalize() try: for label_a in subprocess.check_output('hostnamectl').split(FF): if PY3 and isinstance(label_a, bytes): label_a = label_a.decode() if 'Operating' in label_a: environment['os_release'] = str(scrapertools.find_single_match(label_a, 'Operating\s*S\w+:\s*(.*?)\s*$')) break for label_a in subprocess.check_output(['cat', '/proc/cpuinfo']).split(FF): if PY3 and isinstance(label_a, bytes): label_a = label_a.decode() if 'model name' in label_a: environment['prod_model'] = str(scrapertools.find_single_match(label_a, \ 'model.*?:\s*(?i)(?:Intel\(R\))?(?:\s*Core\(TM\))\s*(.*?CPU.*?)\s*(?:\@|$)')) break except: pass elif PLATFORM in ['raspberry']: environment['os_name'] = 'RaspberryPi' else: environment['os_name'] = str(PLATFORM.capitalize()) if not environment['os_release']: environment['os_release'] = str(platform.release()) if environment['proc_num'] and environment['prod_model']: environment['prod_model'] += environment['proc_num'] environment['machine'] = str(platform.machine()) environment['architecture'] = str(sys.maxsize > 2 ** 32 and "64-bit" or "32-bit") environment['language'] = str(xbmc.getInfoLabel('System.Language')) environment['cpu_usage'] = str(xbmc.getInfoLabel('System.CpuUsage')) environment['mem_total'] = str(xbmc.getInfoLabel('System.Memory(total)')).replace('MB', '').replace('KB', '') environment['mem_free'] = str(xbmc.getInfoLabel('System.Memory(free)')).replace('MB', '').replace('KB', '') if not environment['mem_total'] or not environment['mem_free']: try: if environment['os_name'].lower() in ['windows', 'xbox']: kernel32 = ctypes.windll.kernel32 c_ulong = ctypes.c_ulong c_ulonglong = ctypes.c_ulonglong class MEMORYSTATUS(ctypes.Structure): _fields_ = [ ('dwLength', c_ulong), ('dwMemoryLoad', c_ulong), ('dwTotalPhys', c_ulonglong), ('dwAvailPhys', c_ulonglong), ('dwTotalPageFile', c_ulonglong), ('dwAvailPageFile', c_ulonglong), ('dwTotalVirtual', c_ulonglong), ('dwAvailVirtual', c_ulonglong), ('availExtendedVirtual', c_ulonglong) ] memoryStatus = MEMORYSTATUS() memoryStatus.dwLength = ctypes.sizeof(MEMORYSTATUS) kernel32.GlobalMemoryStatus(ctypes.byref(memoryStatus)) environment['mem_total'] = str(old_div(int(memoryStatus.dwTotalPhys), (1024**2))) environment['mem_free'] = str(old_div(int(memoryStatus.dwAvailPhys), (1024**2))) else: with open('/proc/meminfo') as f: meminfo = f.read() environment['mem_total'] = str(old_div(int(re.search(r'MemTotal:\s+(\d+)', meminfo).groups()[0]), 1024)) environment['mem_free'] = str(old_div(int(re.search(r'MemAvailable:\s+(\d+)', meminfo).groups()[0]), 1024)) except: environment['mem_total'] = '' environment['mem_free'] = '' try: environment['kodi_buffer'] = '20' environment['kodi_bmode'] = '0' environment['kodi_rfactor'] = '4.0' if filetools.exists(filetools.join("special://userdata", "advancedsettings.xml")): advancedsettings = filetools.read(filetools.join("special://userdata", "advancedsettings.xml")).split('\n') for label_a in advancedsettings: if 'memorysize' in label_a: environment['kodi_buffer'] = str(old_div(int(scrapertools.find_single_match (label_a, '>(\d+)<\/')), 1024**2)) if 'buffermode' in label_a: environment['kodi_bmode'] = str(scrapertools.find_single_match (label_a, '>(\d+)<\/')) if 'readfactor' in label_a: environment['kodi_rfactor'] = str(scrapertools.find_single_match (label_a, '>(.*?)<\/')) except: pass environment['userdata_path'] = str(config.get_data_path()) environment['userdata_path_perm'] = filetools.file_info(environment['userdata_path']) if not environment['userdata_path_perm']: del environment['userdata_path_perm'] try: if environment['os_name'].lower() in ['windows', 'xbox']: free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(environment['userdata_path']), None, None, ctypes.pointer(free_bytes)) environment['userdata_free'] = str(round(float(free_bytes.value) / (1024**3), 3)) else: disk_space = os.statvfs(environment['userdata_path']) if not disk_space.f_frsize: disk_space.f_frsize = disk_space.f_frsize.f_bsize environment['userdata_free'] = str(round((float(disk_space.f_bavail) / \ (1024**3)) * float(disk_space.f_frsize), 3)) except: environment['userdata_free'] = '?' if environment.get('userdata_path_perm', ''): environment['userdata_path'] = environment['userdata_path_perm'] del environment['userdata_path_perm'] environment['torrent_lang'] = '%s/%s' % (config.get_setting("channel_language", default="").upper(), \ config.get_setting("second_language", default="").upper()) try: environment['videolab_series'] = '?' environment['videolab_episodios'] = '?' environment['videolab_pelis'] = '?' environment['videolab_path'] = str(config.get_videolibrary_path()) environment['videolab_path_perm'] = filetools.file_info(environment['videolab_path']) if not environment['videolab_path_perm']: environment['videolab_path_perm'] = environment['videolab_path'] if filetools.exists(filetools.join(environment['videolab_path'], \ config.get_setting("folder_tvshows"))): environment['videolab_series'] = str(len(filetools.listdir(filetools.join(environment['videolab_path'], \ config.get_setting("folder_tvshows"))))) counter = 0 for root, folders, files in filetools.walk(filetools.join(environment['videolab_path'], \ config.get_setting("folder_tvshows"))): for file in files: if file.endswith('.strm'): counter += 1 environment['videolab_episodios'] = str(counter) if filetools.exists(filetools.join(environment['videolab_path'], \ config.get_setting("folder_movies"))): environment['videolab_pelis'] = str(len(filetools.listdir(filetools.join(environment['videolab_path'], \ config.get_setting("folder_movies"))))) except: pass try: video_updates = ['No', 'Inicio', 'Una vez', 'Inicio+Una vez', 'Dos veces al día'] environment['videolab_update'] = str(video_updates[config.get_setting("update", "videolibrary")]) if config.get_setting("videolibrary_backup_scan", "videolibrary", default=False): environment['videolab_update'] += ' (Solo SCAN)' except: environment['videolab_update'] = '?' try: if environment['os_name'].lower() in ['windows', 'xbox']: free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(environment['videolab_path']), None, None, ctypes.pointer(free_bytes)) environment['videolab_free'] = str(round(float(free_bytes.value) / (1024**3), 3)) else: disk_space = os.statvfs(environment['videolab_path']) if not disk_space.f_frsize: disk_space.f_frsize = disk_space.f_frsize.f_bsize environment['videolab_free'] = str(round((float(disk_space.f_bavail) / \ (1024**3)) * float(disk_space.f_frsize), 3)) except: environment['videolab_free'] = '?' torrent_paths = torrent_dirs() environment['torrent_list'] = [] environment['torrentcli_option'] = '' environment['torrent_error'] = '' environment['torrentcli_rar'] = config.get_setting("mct_rar_unpack", server="torrent", default=True) environment['torrentcli_backgr'] = config.get_setting("mct_background_download", server="torrent", default=True) environment['torrentcli_lib_path'] = config.get_setting("libtorrent_path", server="torrent", default="") if environment['torrentcli_lib_path']: lib_path = 'Activo' else: lib_path = 'Inactivo' if config.get_setting("libtorrent_version", server="torrent", default=""): lib_path += '-%s' % config.get_setting("libtorrent_version", server="torrent", default="") environment['torrentcli_unrar'] = config.get_setting("unrar_path", server="torrent", default="") if environment['torrentcli_unrar']: unrar = config.get_setting("unrar_device", server="torrent", default="").capitalize() else: unrar = 'Inactivo' torrent_id = config.get_setting("torrent_client", server="torrent", default=0) environment['torrentcli_option'] = str(torrent_id) torrent_options = platformtools.torrent_client_installed() if lib_path != 'Inactivo': torrent_options = [': MCT'] + torrent_options torrent_options = [': BT'] + torrent_options environment['torrent_list'].append({'Torrent_opt': str(torrent_id), 'Libtorrent': lib_path, \ 'RAR_Auto': str(environment['torrentcli_rar']), \ 'RAR_backgr': str(environment['torrentcli_backgr']), \ 'UnRAR': unrar}) environment['torrent_error'] = config.get_setting("libtorrent_error", server="torrent", default="") if environment['torrent_error']: environment['torrent_list'].append({'Libtorrent_error': environment['torrent_error']}) for torrent_option in torrent_options: cliente = dict() cliente['D_load_Path'] = '' cliente['Libre'] = '?' cliente['Plug_in'] = scrapertools.find_single_match(torrent_option, ':\s*(\w+)') if cliente['Plug_in'] not in ['BT', 'MCT']: cliente['Plug_in'] = cliente['Plug_in'].capitalize() cliente['D_load_Path'] = torrent_paths[cliente['Plug_in'].upper()] cliente['D_load_Path_perm'] = filetools.file_info(cliente['D_load_Path']) cliente['Buffer'] = str(torrent_paths[cliente['Plug_in'].upper()+'_buffer']) cliente['Version'] = str(torrent_paths[cliente['Plug_in'].upper()+'_version']) if cliente['Plug_in'].upper() == 'TORREST': cliente['Buffer'] = str(int(int(torrent_paths[cliente['Plug_in'].upper()+'_buffer']) /(1024*1024))) bin_path = filetools.join('special://home', 'addons', 'plugin.video.torrest', 'resources', 'bin') if filetools.exists(bin_path): cliente['Platform'] = str(filetools.listdir(bin_path)[0]) else: cliente['Platform'] = 'None' try: __settings__ = xbmcaddon.Addon(id="plugin.video.torrest") cliente['Platform'] += ': %s: %s:%s' % (str(__settings__.getSetting("service_enabled")), \ str(__settings__.getSetting("service_ip")), str(__settings__.getSetting("port"))) except: pass #cliente['Options'] = str(filetools.read(filetools.join('special://masterprofile', \ # 'addon_data', 'plugin.video.torrest', 'settings.xml'))) if torrent_paths.get(cliente['Plug_in'].upper()+'_memory_size', ''): cliente['Memoria'] = str(torrent_paths[cliente['Plug_in'].upper()+'_memory_size']) if cliente.get('D_load_Path', ''): try: if environment['os_name'].lower() in ['windows', 'xbox']: free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(cliente['D_load_Path']), None, None, ctypes.pointer(free_bytes)) cliente['Libre'] = str(round(float(free_bytes.value) / \ (1024**3), 3)).replace('.', ',') else: disk_space = os.statvfs(cliente['D_load_Path']) if not disk_space.f_frsize: disk_space.f_frsize = disk_space.f_frsize.f_bsize cliente['Libre'] = str(round((float(disk_space.f_bavail) / \ (1024**3)) * float(disk_space.f_frsize), 3)).replace('.', ',') except: pass if cliente.get('D_load_Path_perm', ''): cliente['D_load_Path'] = cliente['D_load_Path_perm'] del cliente['D_load_Path_perm'] environment['torrent_list'].append(cliente) environment['proxy_active'] = '' try: proxy_channel_bloqued_str = base64.b64decode(config.get_setting('proxy_channel_bloqued')).decode('utf-8') proxy_channel_bloqued = dict() proxy_channel_bloqued = ast.literal_eval(proxy_channel_bloqued_str) for channel_bloqued, proxy_active in list(proxy_channel_bloqued.items()): if proxy_active != 'OFF': environment['proxy_active'] += channel_bloqued + ', ' except: pass if not environment['proxy_active']: environment['proxy_active'] = 'OFF' environment['proxy_active'] = environment['proxy_active'].rstrip(', ') for root, folders, files in filetools.walk("special://logpath/"): for file in files: if file.lower() in ['kodi.log', 'jarvis.log', 'spmc.log', 'cemc.log', \ 'mygica.log', 'wonderbox.log', 'leiapp,log', \ 'leianmc.log', 'kodiapp.log', 'anmc.log', \ 'latin-anmc.log']: environment['log_path'] = str(filetools.join(root, file)) break else: environment['log_path'] = '' break if environment.get('log_path', ''): environment['log_size_bytes'] = str(filetools.getsize(environment['log_path'])) environment['log_size'] = str(round(float(environment['log_size_bytes']) / \ (1024*1024), 3)) else: environment['log_size_bytes'] = '' environment['log_size'] = '' environment['debug'] = str(config.get_setting('debug')) environment['addon_version'] = '%s (Upd: %s h.)' % (str(config.get_addon_version(from_xml=True)), \ str(config.get_setting("addon_update_timer", default=12)).replace('0', 'No')) environment['assistant_version'] = str(None) if filetools.exists(filetools.join(config.get_data_path(), 'alfa-mobile-assistant.version')): environment['assistant_version'] = filetools.read(filetools.join(config.get_data_path(), 'alfa-mobile-assistant.version')) environment['assistant_version'] += '; Req: %s' % str(config.get_setting('assistant_binary', default=False)) environment['assistant_cf_ua'] = str(config.get_setting('cf_assistant_ua', default=None)) assistant_path = filetools.join(os.getenv('ANDROID_STORAGE'), 'emulated', '0', 'Android', 'data', 'com.alfa.alfamobileassistant') if PLATFORM in ['android', 'atv2'] and filetools.exists(assistant_path): environment['assistant_path'] = str(filetools.file_info(assistant_path)) except: logger.error(traceback.format_exc()) environment = {} environment['log_size'] = '' environment['cpu_usage'] = '' environment['python_version'] = '' environment['log_path'] = '' environment['userdata_free'] = '' environment['mem_total'] = '' environment['machine'] = '' environment['platform'] = '' environment['videolab_path'] = '' environment['num_version'] = '' environment['os_name'] = '' environment['video_db'] = '' environment['userdata_path'] = '' environment['log_size_bytes'] = '' environment['name_version'] = '' environment['language'] = '' environment['mem_free'] = '' environment['prod_model'] = '' environment['proxy_active'] = '' environment['architecture'] = '' environment['os_release'] = '' environment['videolab_free'] = '' environment['kodi_buffer'] = '' environment['kodi_bmode'] = '' environment['kodi_rfactor'] = '' environment['videolab_series'] = '' environment['videolab_episodios'] = '' environment['videolab_pelis'] = '' environment['videolab_update'] = '' environment['videolab_path_perm'] = '' environment['debug'] = '' environment['addon_version'] = '' environment['torrent_list'] = [] environment['torrent_lang'] = '' environment['torrentcli_option'] = '' environment['torrentcli_rar'] = '' environment['torrentcli_lib_path'] = '' environment['torrentcli_unrar'] = '' environment['torrent_error'] = '' environment['assistant_version'] = '' environment['assistant_cf_ua'] = '' return environment
def get_environment(): """ Devuelve las variables de entorno del OS, de Kodi y de Alfa más habituales, necesarias para el diagnóstico de fallos """ try: import base64 import ast environment = config.get_platform(full_version=True) environment['num_version'] = str(environment['num_version']) environment['python_version'] = str(platform.python_version()) environment['os_release'] = str(platform.release()) if xbmc.getCondVisibility("system.platform.Windows"): try: if platform._syscmd_ver()[2]: environment['os_release'] = str(platform._syscmd_ver()[2]) except: pass environment['prod_model'] = '' if xbmc.getCondVisibility("system.platform.Android"): environment['os_name'] = 'Android' try: for label_a in subprocess.check_output('getprop').split('\n'): if 'build.version.release' in label_a: environment['os_release'] = str( scrapertools.find_single_match( label_a, ':\s*\[(.*?)\]$')) if 'product.model' in label_a: environment['prod_model'] = str( scrapertools.find_single_match( label_a, ':\s*\[(.*?)\]$')) except: try: for label_a in filetools.read(os.environ['ANDROID_ROOT'] + '/build.prop').split(): if 'build.version.release' in label_a: environment['os_release'] = str( scrapertools.find_single_match( label_a, '=(.*?)$')) if 'product.model' in label_a: environment['prod_model'] = str( scrapertools.find_single_match( label_a, '=(.*?)$')) except: pass elif xbmc.getCondVisibility("system.platform.Linux.RaspberryPi"): environment['os_name'] = 'RaspberryPi' else: environment['os_name'] = str(platform.system()) environment['machine'] = str(platform.machine()) environment['architecture'] = str(sys.maxsize > 2**32 and "64-bit" or "32-bit") environment['language'] = str(xbmc.getInfoLabel('System.Language')) environment['cpu_usage'] = str(xbmc.getInfoLabel('System.CpuUsage')) environment['mem_total'] = str( xbmc.getInfoLabel('System.Memory(total)')).replace('MB', '').replace( 'KB', '') environment['mem_free'] = str( xbmc.getInfoLabel('System.Memory(free)')).replace('MB', '').replace( 'KB', '') if not environment['mem_total'] or not environment['mem_free']: try: if environment['os_name'].lower() == 'windows': kernel32 = ctypes.windll.kernel32 c_ulong = ctypes.c_ulong c_ulonglong = ctypes.c_ulonglong class MEMORYSTATUS(ctypes.Structure): _fields_ = [('dwLength', c_ulong), ('dwMemoryLoad', c_ulong), ('dwTotalPhys', c_ulonglong), ('dwAvailPhys', c_ulonglong), ('dwTotalPageFile', c_ulonglong), ('dwAvailPageFile', c_ulonglong), ('dwTotalVirtual', c_ulonglong), ('dwAvailVirtual', c_ulonglong), ('availExtendedVirtual', c_ulonglong)] memoryStatus = MEMORYSTATUS() memoryStatus.dwLength = ctypes.sizeof(MEMORYSTATUS) kernel32.GlobalMemoryStatus(ctypes.byref(memoryStatus)) environment['mem_total'] = str( old_div(int(memoryStatus.dwTotalPhys), (1024**2))) environment['mem_free'] = str( old_div(int(memoryStatus.dwAvailPhys), (1024**2))) else: with open('/proc/meminfo') as f: meminfo = f.read() environment['mem_total'] = str( old_div( int( re.search(r'MemTotal:\s+(\d+)', meminfo).groups()[0]), 1024)) environment['mem_free'] = str( old_div( int( re.search(r'MemAvailable:\s+(\d+)', meminfo).groups()[0]), 1024)) except: environment['mem_total'] = '' environment['mem_free'] = '' try: environment['kodi_buffer'] = '20' environment['kodi_bmode'] = '0' environment['kodi_rfactor'] = '4.0' if filetools.exists( filetools.join(xbmc.translatePath("special://userdata"), "advancedsettings.xml")): advancedsettings = filetools.read( filetools.join(xbmc.translatePath("special://userdata"), "advancedsettings.xml")).split('\n') for label_a in advancedsettings: if 'memorysize' in label_a: environment['kodi_buffer'] = str( old_div( int( scrapertools.find_single_match( label_a, '>(\d+)<\/')), 1024**2)) if 'buffermode' in label_a: environment['kodi_bmode'] = str( scrapertools.find_single_match( label_a, '>(\d+)<\/')) if 'readfactor' in label_a: environment['kodi_rfactor'] = str( scrapertools.find_single_match( label_a, '>(.*?)<\/')) except: pass environment['userdata_path'] = str( xbmc.translatePath(config.get_data_path())) try: if environment['os_name'].lower() == 'windows': free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW( ctypes.c_wchar_p(environment['userdata_path']), None, None, ctypes.pointer(free_bytes)) environment['userdata_free'] = str( round(float(free_bytes.value) / (1024**3), 3)) else: disk_space = os.statvfs(environment['userdata_path']) if not disk_space.f_frsize: disk_space.f_frsize = disk_space.f_frsize.f_bsize environment['userdata_free'] = str(round((float(disk_space.f_bavail) / \ (1024**3)) * float(disk_space.f_frsize), 3)) except: environment['userdata_free'] = '?' try: environment['videolab_series'] = '?' environment['videolab_episodios'] = '?' environment['videolab_pelis'] = '?' environment['videolab_path'] = str( xbmc.translatePath(config.get_videolibrary_path())) if filetools.exists(filetools.join(environment['videolab_path'], \ config.get_setting("folder_tvshows"))): environment['videolab_series'] = str(len(filetools.listdir(filetools.join(environment['videolab_path'], \ config.get_setting("folder_tvshows"))))) counter = 0 for root, folders, files in filetools.walk(filetools.join(environment['videolab_path'], \ config.get_setting("folder_tvshows"))): for file in files: if file.endswith('.strm'): counter += 1 environment['videolab_episodios'] = str(counter) if filetools.exists(filetools.join(environment['videolab_path'], \ config.get_setting("folder_movies"))): environment['videolab_pelis'] = str(len(filetools.listdir(filetools.join(environment['videolab_path'], \ config.get_setting("folder_movies"))))) except: pass try: video_updates = ['No', 'Inicio', 'Una vez', 'Inicio+Una vez'] environment['videolab_update'] = str( video_updates[config.get_setting("update", "videolibrary")]) except: environment['videolab_update'] = '?' try: if environment['os_name'].lower() == 'windows': free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW( ctypes.c_wchar_p(environment['videolab_path']), None, None, ctypes.pointer(free_bytes)) environment['videolab_free'] = str( round(float(free_bytes.value) / (1024**3), 3)) else: disk_space = os.statvfs(environment['videolab_path']) if not disk_space.f_frsize: disk_space.f_frsize = disk_space.f_frsize.f_bsize environment['videolab_free'] = str(round((float(disk_space.f_bavail) / \ (1024**3)) * float(disk_space.f_frsize), 3)) except: environment['videolab_free'] = '?' environment['torrent_list'] = [] environment['torrentcli_option'] = '' environment['torrent_error'] = '' environment['torrentcli_rar'] = config.get_setting("mct_rar_unpack", server="torrent", default=True) environment['torrentcli_backgr'] = config.get_setting( "mct_background_download", server="torrent", default=True) environment['torrentcli_lib_path'] = config.get_setting( "libtorrent_path", server="torrent", default="") if environment['torrentcli_lib_path']: lib_path = 'Activo' else: lib_path = 'Inactivo' environment['torrentcli_unrar'] = config.get_setting("unrar_path", server="torrent", default="") if environment['torrentcli_unrar']: if xbmc.getCondVisibility("system.platform.Android"): unrar = 'Android' else: unrar, bin = filetools.split(environment['torrentcli_unrar']) unrar = unrar.replace('\\', '/') if not unrar.endswith('/'): unrar = unrar + '/' unrar = scrapertools.find_single_match( unrar, '\/([^\/]+)\/$').capitalize() else: unrar = 'Inactivo' torrent_id = config.get_setting("torrent_client", server="torrent", default=0) environment['torrentcli_option'] = str(torrent_id) torrent_options = platformtools.torrent_client_installed() if lib_path == 'Activo': torrent_options = ['MCT'] + torrent_options torrent_options = ['BT'] + torrent_options environment['torrent_list'].append({'Torrent_opt': str(torrent_id), 'Libtorrent': lib_path, \ 'RAR_Auto': str(environment['torrentcli_rar']), \ 'RAR_backgr': str(environment['torrentcli_backgr']), \ 'UnRAR': unrar}) environment['torrent_error'] = config.get_setting("libtorrent_error", server="torrent", default="") if environment['torrent_error']: environment['torrent_list'].append( {'Libtorrent_error': environment['torrent_error']}) for torrent_option in torrent_options: cliente = dict() cliente['D_load_Path'] = '' cliente['Libre'] = '?' cliente['Plug_in'] = torrent_option.replace('Plugin externo: ', '') if cliente['Plug_in'] == 'BT': cliente['D_load_Path'] = str( config.get_setting("bt_download_path", server="torrent", default='')) if not cliente['D_load_Path']: continue cliente['Buffer'] = str( config.get_setting("bt_buffer", server="torrent", default=50)) elif cliente['Plug_in'] == 'MCT': cliente['D_load_Path'] = str( config.get_setting("mct_download_path", server="torrent", default='')) if not cliente['D_load_Path']: continue cliente['Buffer'] = str( config.get_setting("mct_buffer", server="torrent", default=50)) elif xbmc.getCondVisibility('System.HasAddon("plugin.video.%s")' % cliente['Plug_in']): __settings__ = xbmcaddon.Addon(id="plugin.video.%s" % cliente['Plug_in']) cliente['Plug_in'] = cliente['Plug_in'].capitalize() if cliente['Plug_in'] == 'Torrenter': cliente['D_load_Path'] = str( xbmc.translatePath(__settings__.getSetting('storage'))) if not cliente['D_load_Path']: cliente['D_load_Path'] = str(filetools.join(xbmc.translatePath("special://home/"), \ "cache", "xbmcup", "plugin.video.torrenter", "Torrenter")) cliente['Buffer'] = str( __settings__.getSetting('pre_buffer_bytes')) else: cliente['D_load_Path'] = str( xbmc.translatePath( __settings__.getSetting('download_path'))) cliente['Buffer'] = str( __settings__.getSetting('buffer_size')) if __settings__.getSetting( 'download_storage' ) == '1' and __settings__.getSetting('memory_size'): cliente['Memoria'] = str( __settings__.getSetting('memory_size')) if cliente['D_load_Path']: try: if environment['os_name'].lower() == 'windows': free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW( ctypes.c_wchar_p(cliente['D_load_Path']), None, None, ctypes.pointer(free_bytes)) cliente['Libre'] = str(round(float(free_bytes.value) / \ (1024**3), 3)).replace('.', ',') else: disk_space = os.statvfs(cliente['D_load_Path']) if not disk_space.f_frsize: disk_space.f_frsize = disk_space.f_frsize.f_bsize cliente['Libre'] = str(round((float(disk_space.f_bavail) / \ (1024**3)) * float(disk_space.f_frsize), 3)).replace('.', ',') except: pass environment['torrent_list'].append(cliente) environment['proxy_active'] = '' try: proxy_channel_bloqued_str = base64.b64decode( config.get_setting('proxy_channel_bloqued')).decode('utf-8') proxy_channel_bloqued = dict() proxy_channel_bloqued = ast.literal_eval(proxy_channel_bloqued_str) for channel_bloqued, proxy_active in list( proxy_channel_bloqued.items()): if proxy_active != 'OFF': environment['proxy_active'] += channel_bloqued + ', ' except: pass if not environment['proxy_active']: environment['proxy_active'] = 'OFF' environment['proxy_active'] = environment['proxy_active'].rstrip(', ') for root, folders, files in filetools.walk( xbmc.translatePath("special://logpath/")): for file in files: if file.lower() in ['kodi.log', 'jarvis.log', 'spmc.log', 'cemc.log', \ 'mygica.log', 'wonderbox.log', 'leiapp,log', \ 'leianmc.log', 'kodiapp.log', 'anmc.log', \ 'latin-anmc.log']: environment['log_path'] = str(filetools.join(root, file)) break else: environment['log_path'] = '' break if environment['log_path']: environment['log_size_bytes'] = str( filetools.getsize(environment['log_path'])) environment['log_size'] = str(round(float(environment['log_size_bytes']) / \ (1024*1024), 3)) else: environment['log_size_bytes'] = '' environment['log_size'] = '' environment['debug'] = str(config.get_setting('debug')) environment['addon_version'] = str(config.get_addon_version()) except: logger.error(traceback.format_exc()) environment = {} environment['log_size'] = '' environment['cpu_usage'] = '' environment['python_version'] = '' environment['log_path'] = '' environment['userdata_free'] = '' environment['mem_total'] = '' environment['machine'] = '' environment['platform'] = '' environment['videolab_path'] = '' environment['num_version'] = '' environment['os_name'] = '' environment['video_db'] = '' environment['userdata_path'] = '' environment['log_size_bytes'] = '' environment['name_version'] = '' environment['language'] = '' environment['mem_free'] = '' environment['prod_model'] = '' environment['proxy_active'] = '' environment['architecture'] = '' environment['os_release'] = '' environment['videolab_free'] = '' environment['kodi_buffer'] = '' environment['kodi_bmode'] = '' environment['kodi_rfactor'] = '' environment['videolab_series'] = '' environment['videolab_episodios'] = '' environment['videolab_pelis'] = '' environment['videolab_update'] = '' environment['debug'] = '' environment['addon_version'] = '' environment['torrent_list'] = [] environment['torrentcli_option'] = '' environment['torrentcli_rar'] = '' environment['torrentcli_lib_path'] = '' environment['torrentcli_unrar'] = '' environment['torrent_error'] = '' return environment
def _setSearchW(self,string): temp = c.c_wchar_p (string) self.lib.Everything_SetSearchW.argtypes = [c.c_wchar_p] self.lib.Everything_SetSearchW ( temp ) return None
def setint(self, strcommand, value): """SetInt function. """ command = ct.c_wchar_p(strcommand) value = ct.c_longlong(value) self.lib.AT_SetInt(self.AT_H, command, value)
def get_dir(abs_src_dir): ip = request.remote_addr dict_dir_2_url = dict() dict_dir_2_freespace = dict() abs_src_dir = url_transfer_to_dir(abs_src_dir) logging.info('/get_dir ip : %s, user : %s, get_dir : %s' % (str(ip), str(g_dict_ip_2_user.get(ip)), abs_src_dir)) if g_dict_ip_2_loginstatus.get( ip) is None or g_dict_ip_2_loginstatus[ip] == False: return "<h1>GO F**K YOURSELF</h1>" if abs_src_dir == 'home': if system == 'Windows': free_bytes = ctypes.c_ulonglong(0) for char in string.ascii_uppercase: disk = char + ':' + file_separator_list[system] if os.path.isdir(disk): ctypes.windll.kernel32.GetDiskFreeSpaceExW( ctypes.c_wchar_p(disk), None, None, ctypes.pointer(free_bytes)) dict_dir_2_freespace[disk] = str( free_bytes.value / 1024 / 1024 / 1024) + ' GB left' dict_dir_2_url[disk] = dir_transfer_to_url( disk) # c:\ -> c:* elif system == 'Linux': st = os.statvfs('/home') dict_dir_2_freespace['/home'] = str( st.f_bavail * st.f_frsize / 1024 / 1024 / 1024) + ' GB left' dict_dir_2_url['/home'] = dir_transfer_to_url( '/home') # /home -> *home return render_template("index.html", dict_dir_2_url=dict_dir_2_url, dict_dir_2_freespace=dict_dir_2_freespace, file_separator=file_separator_list[system]) elif os.path.isdir(abs_src_dir): abs_src_dir_listdir = os.listdir(abs_src_dir) abs_src_dir_listdir.sort() for dir in abs_src_dir_listdir: under_abs_src_dir = os.path.join(abs_src_dir, dir) dict_dir_2_freespace[under_abs_src_dir] = "" dict_dir_2_url[under_abs_src_dir] = dir_transfer_to_url( under_abs_src_dir) return render_template("index.html", dict_dir_2_url=dict_dir_2_url, dict_dir_2_freespace=dict_dir_2_freespace, file_separator=file_separator_list[system]) elif os.path.isfile(abs_src_dir): file_format = abs_src_dir.split('.')[-1].lower() if file_format in [ 'md', 'c', 'cpp', 'py', 'txt', 'json', 'html', 'log', 'dat', 'ini', 'inf', 'bat', 'sh' ]: file_open = open(abs_src_dir, 'rb') file_content = file_open.read() charset = chardet.detect(file_content)['encoding'] resp = make_response(file_content) resp.headers["Content-type"] = "text/plan;charset=" + charset return resp elif file_format in ['mp3'] or file_format in ['mp4', 'mkv', 'flv']: static_dir = os.path.join(root, 'static') static_media_dir = os.path.join(static_dir, 'media') if not os.path.exists(static_media_dir): os.mkdir(static_media_dir) filename = abs_src_dir.split(file_separator_list[system])[-1] abs_to_play_dir = os.path.join(static_media_dir, filename) to_play_dir = "/static/media/" + filename if file_format in ['mp3']: if filename not in os.listdir(static_media_dir): move_media_file_to_staticdir(abs_src_dir, abs_to_play_dir, "copy") html = ''' <audio width=1000 height=500 controls> <source src="%s" type="audio/mp3"> </audio> ''' % (to_play_dir) else: if not filename.endswith('.mp4'): filename = filename.replace('.' + file_format, '.mp4') if not filename in os.listdir(static_media_dir): abs_to_play_dir = abs_to_play_dir.replace( '.' + file_format, '.mp4') move_media_file_to_staticdir(abs_src_dir, abs_to_play_dir, "ffmpeg") else: if not filename in os.listdir(static_media_dir): move_media_file_to_staticdir(abs_src_dir, abs_to_play_dir, "copy") html = ''' <video width=1000 height=500 controls> <source src="%s" type="video/mp4"> </video> ''' % (to_play_dir) return html elif file_format in ['jpg', 'bmp', 'png', 'ico']: to_sava_format = { 'jpg': "JPEG", 'bmp': "BMP", 'png': "PNG", 'ico': 'ICO' } img_io = BytesIO() img = Image.open(abs_src_dir) image = img.convert('RGB') image.save(img_io, to_sava_format[file_format], quality=70) img_io.seek(0) return send_file(img_io, mimetype='image/' + to_sava_format[file_format].lower()) elif file_format in ['pdf']: abs_src_dir_split = abs_src_dir.split(file_separator_list[system]) filename = abs_src_dir_split.pop() directory = file_separator_list[system].join(abs_src_dir_split) return send_from_directory(directory=directory, filename=filename, mimetype='application/pdf')
def setfloat(self, strcommand, value): """Set command with Float value parameter. """ command = ct.c_wchar_p(strcommand) value = ct.c_double(value) self.lib.AT_SetFloat(self.AT_H, command, value)
def setbool(self, strcommand, value): """Set command with Bool value parameter. """ command = ct.c_wchar_p(strcommand) value = ct.c_bool(value) self.lib.AT_SetBool(self.AT_H, command, value)
__status__ = "Prototype" import ctypes from ctypes import windll, c_void_p from ctypes import c_uint32 from ctypes import c_wchar_p from ctypes import byref GENERIC_WRITE = 0x40000000 OPEN_EXISTING = 3 FILE_WRITE_ACCESS = 0x0002 FILE_SHARE_WRITE = 0x00000002 FILE_ATTRIBUTE_NORMAL = 0x00000080 METHOD_BUFFERED = 0 FILE_DEVICE_PROCMON_LOG = 0x00009535 PROCMON_DEBUGGER_HANDLER = c_wchar_p(r"\\.\Global\ProcmonDebugLogger") DW_IO_CONTROL_CODE = 2503311876 k32 = windll.kernel32 msg = "Hello ProcMon from python 2.7 with ctypes!".encode('UTF-16') handle = k32.CreateFileW(PROCMON_DEBUGGER_HANDLER, GENERIC_WRITE, FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0) if handle == -1: raise RuntimeWarning("ProcMon doesn't appear to be running") print("Handle: %d" % handle) k32.DeviceIoControl( handle,
progress(files_to_process, 40, i) # show progress bar #file_size=file_size/1024 # convert KB first # round up to ceiling 8kb (Isilon uses an 8KB filesystem block size, so we need to round up) if (block_size == 0): testfs = file_size try: block_size = os.statvfs( dirname ).f_frsize #try to find the native FS block size using Unix stats command (will fail in Windows based OS) except AttributeError: # if above command fails, let's try finding the native FS block size using Windows native DLL instead import ctypes sectorsPerCluster = ctypes.c_ulonglong(0) bytesPerSector = ctypes.c_ulonglong(0) rootPathName = ctypes.c_wchar_p(dirname) ctypes.windll.kernel32.GetDiskFreeSpaceW( rootPathName, ctypes.pointer(sectorsPerCluster), ctypes.pointer(bytesPerSector), None, None, ) spc = sectorsPerCluster.value bps = bytesPerSector.value block_size = spc * bps #Round all the filesize calculations (for the original data size) to the blocksize of the native filesystem (of the system this script is running on) #block_size=8192 # just for testing (to match oneFS block size) testfs = file_size