Search is not available for this dataset
text
stringlengths
75
104k
def appendtext(self, window_name, object_name, data): """ Append string sequence. @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param data: data to type. @type data: string @return: 1 on success. @rtype: integer """ object_handle = self._get_object_handle(window_name, object_name) if not object_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % object_name) object_handle.AXValue += data return 1
def getcursorposition(self, window_name, object_name): """ Get cursor position @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: Cursor position on success. @rtype: integer """ object_handle = self._get_object_handle(window_name, object_name) if not object_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % object_name) return object_handle.AXSelectedTextRange.loc
def setcursorposition(self, window_name, object_name, cursor_position): """ Set cursor position @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param cursor_position: Cursor position to be set @type object_name: string @return: 1 on success. @rtype: integer """ object_handle = self._get_object_handle(window_name, object_name) if not object_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % object_name) object_handle.AXSelectedTextRange.loc = cursor_position return 1
def cuttext(self, window_name, object_name, start_position, end_position=-1): """ cut text from start position to end position @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param start_position: Start position @type object_name: integer @param end_position: End position, default -1 Cut all the text from start position till end @type object_name: integer @return: 1 on success. @rtype: integer """ object_handle = self._get_object_handle(window_name, object_name) if not object_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % object_name) size = object_handle.AXNumberOfCharacters if end_position == -1 or end_position > size: end_position = size if start_position < 0: start_position = 0 data = object_handle.AXValue Clipboard.copy(data[start_position:end_position]) object_handle.AXValue = data[:start_position] + data[end_position:] return 1
def deletetext(self, window_name, object_name, start_position, end_position=-1): """ delete text from start position to end position @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param start_position: Start position @type object_name: integer @param end_position: End position, default -1 Delete all the text from start position till end @type object_name: integer @return: 1 on success. @rtype: integer """ object_handle = self._get_object_handle(window_name, object_name) if not object_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % object_name) size = object_handle.AXNumberOfCharacters if end_position == -1 or end_position > size: end_position = size if start_position < 0: start_position = 0 data = object_handle.AXValue object_handle.AXValue = data[:start_position] + data[end_position:] return 1
def pastetext(self, window_name, object_name, position=0): """ paste text from start position to end position @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param position: Position to paste the text, default 0 @type object_name: integer @return: 1 on success. @rtype: integer """ object_handle = self._get_object_handle(window_name, object_name) if not object_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % object_name) size = object_handle.AXNumberOfCharacters if position > size: position = size if position < 0: position = 0 clipboard = Clipboard.paste() data = object_handle.AXValue object_handle.AXValue = data[:position] + clipboard + data[position:] return 1
def main(port=4118, parentpid=None): """Main entry point. Parse command line options and start up a server.""" if "LDTP_DEBUG" in os.environ: _ldtp_debug = True else: _ldtp_debug = False _ldtp_debug_file = os.environ.get('LDTP_DEBUG_FILE', None) if _ldtp_debug: print("Parent PID: {}".format(int(parentpid))) if _ldtp_debug_file: with open(unicode(_ldtp_debug_file), "a") as fp: fp.write("Parent PID: {}".format(int(parentpid))) server = LDTPServer(('', port), allow_none=True, logRequests=_ldtp_debug, requestHandler=RequestHandler) server.register_introspection_functions() server.register_multicall_functions() ldtp_inst = core.Core() server.register_instance(ldtp_inst) if parentpid: thread.start_new_thread(notifyclient, (parentpid,)) try: server.serve_forever() except KeyboardInterrupt: pass except: if _ldtp_debug: print(traceback.format_exc()) if _ldtp_debug_file: with open(_ldtp_debug_file, "a") as fp: fp.write(traceback.format_exc())
def server_bind(self, *args, **kwargs): '''Server Bind. Forces reuse of port.''' self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Can't use super() here since SimpleXMLRPCServer is an old-style class SimpleXMLRPCServer.server_bind(self, *args, **kwargs)
def log(self, message, level=logging.DEBUG): """ Logs the message in the root logger with the log level @param message: Message to be logged @type message: string @param level: Log level, defaul DEBUG @type level: integer @return: 1 on success and 0 on error @rtype: integer """ if _ldtp_debug: print(message) self.logger.log(level, str(message)) return 1
def stoplog(self): """ Stop logging. @return: 1 on success and 0 on error @rtype: integer """ if self._file_logger: self.logger.removeHandler(_file_logger) self._file_logger = None return 1
def imagecapture(self, window_name=None, out_file=None, x=0, y=0, width=None, height=None): """ Captures screenshot of the whole desktop or given window @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param x: x co-ordinate value @type x: integer @param y: y co-ordinate value @type y: integer @param width: width co-ordinate value @type width: integer @param height: height co-ordinate value @type height: integer @return: screenshot filename @rtype: string """ if not out_file: out_file = tempfile.mktemp('.png', 'ldtp_') else: out_file = os.path.expanduser(out_file) ### Windows compatibility if _ldtp_windows_env: if width == None: width = -1 if height == None: height = -1 if window_name == None: window_name = '' ### Windows compatibility - End data = self._remote_imagecapture(window_name, x, y, width, height) f = open(out_file, 'wb') f.write(b64decode(data)) f.close() return out_file
def onwindowcreate(self, window_name, fn_name, *args): """ On window create, call the function with given arguments @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param fn_name: Callback function @type fn_name: function @param *args: arguments to be passed to the callback function @type *args: var args @return: 1 if registration was successful, 0 if not. @rtype: integer """ self._pollEvents._callback[window_name] = ["onwindowcreate", fn_name, args] return self._remote_onwindowcreate(window_name)
def registerevent(self, event_name, fn_name, *args): """ Register at-spi event @param event_name: Event name in at-spi format. @type event_name: string @param fn_name: Callback function @type fn_name: function @param *args: arguments to be passed to the callback function @type *args: var args @return: 1 if registration was successful, 0 if not. @rtype: integer """ if not isinstance(event_name, str): raise ValueError("event_name should be string") self._pollEvents._callback[event_name] = [event_name, fn_name, args] return self._remote_registerevent(event_name)
def deregisterevent(self, event_name): """ Remove callback of registered event @param event_name: Event name in at-spi format. @type event_name: string @return: 1 if registration was successful, 0 if not. @rtype: integer """ if event_name in self._pollEvents._callback: del self._pollEvents._callback[event_name] return self._remote_deregisterevent(event_name)
def registerkbevent(self, keys, modifiers, fn_name, *args): """ Register keystroke events @param keys: key to listen @type keys: string @param modifiers: control / alt combination using gtk MODIFIERS @type modifiers: int @param fn_name: Callback function @type fn_name: function @param *args: arguments to be passed to the callback function @type *args: var args @return: 1 if registration was successful, 0 if not. @rtype: integer """ event_name = "kbevent%s%s" % (keys, modifiers) self._pollEvents._callback[event_name] = [event_name, fn_name, args] return self._remote_registerkbevent(keys, modifiers)
def deregisterkbevent(self, keys, modifiers): """ Remove callback of registered event @param keys: key to listen @type keys: string @param modifiers: control / alt combination using gtk MODIFIERS @type modifiers: int @return: 1 if registration was successful, 0 if not. @rtype: integer """ event_name = "kbevent%s%s" % (keys, modifiers) if event_name in _pollEvents._callback: del _pollEvents._callback[event_name] return self._remote_deregisterkbevent(keys, modifiers)
def windowuptime(self, window_name): """ Get window uptime @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @return: "starttime, endtime" as datetime python object """ tmp_time = self._remote_windowuptime(window_name) if tmp_time: tmp_time = tmp_time.split('-') start_time = tmp_time[0].split(' ') end_time = tmp_time[1].split(' ') _start_time = datetime.datetime(int(start_time[0]), int(start_time[1]), int(start_time[2]), int(start_time[3]), int(start_time[4]), int(start_time[5])) _end_time = datetime.datetime(int(end_time[0]), int(end_time[1]), int(end_time[2]), int(end_time[3]), int(end_time[4]), int(end_time[5])) return _start_time, _end_time return None
def verifyscrollbarvertical(self, window_name, object_name): """ Verify scrollbar is vertical @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: 1 on success. @rtype: integer """ try: object_handle = self._get_object_handle(window_name, object_name) if object_handle.AXOrientation == "AXVerticalOrientation": return 1 except: pass return 0
def verifyscrollbarhorizontal(self, window_name, object_name): """ Verify scrollbar is horizontal @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: 1 on success. @rtype: integer """ try: object_handle = self._get_object_handle(window_name, object_name) if object_handle.AXOrientation == "AXHorizontalOrientation": return 1 except: pass return 0
def setmax(self, window_name, object_name): """ Set max value @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: 1 on success. @rtype: integer """ object_handle = self._get_object_handle(window_name, object_name) object_handle.AXValue = 1 return 1
def setmin(self, window_name, object_name): """ Set min value @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: 1 on success. @rtype: integer """ object_handle = self._get_object_handle(window_name, object_name) object_handle.AXValue = 0 return 1
def scrollup(self, window_name, object_name): """ Scroll up @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: 1 on success. @rtype: integer """ if not self.verifyscrollbarvertical(window_name, object_name): raise LdtpServerException('Object not vertical scrollbar') return self.setmin(window_name, object_name)
def scrolldown(self, window_name, object_name): """ Scroll down @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: 1 on success. @rtype: integer """ if not self.verifyscrollbarvertical(window_name, object_name): raise LdtpServerException('Object not vertical scrollbar') return self.setmax(window_name, object_name)
def scrollleft(self, window_name, object_name): """ Scroll left @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: 1 on success. @rtype: integer """ if not self.verifyscrollbarhorizontal(window_name, object_name): raise LdtpServerException('Object not horizontal scrollbar') return self.setmin(window_name, object_name)
def scrollright(self, window_name, object_name): """ Scroll right @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: 1 on success. @rtype: integer """ if not self.verifyscrollbarhorizontal(window_name, object_name): raise LdtpServerException('Object not horizontal scrollbar') return self.setmax(window_name, object_name)
def onedown(self, window_name, object_name, iterations): """ Press scrollbar down with number of iterations @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param interations: iterations to perform on slider increase @type iterations: integer @return: 1 on success. @rtype: integer """ if not self.verifyscrollbarvertical(window_name, object_name): raise LdtpServerException('Object not vertical scrollbar') object_handle = self._get_object_handle(window_name, object_name) i = 0 maxValue = 1.0 / 8 flag = False while i < iterations: if object_handle.AXValue >= 1: raise LdtpServerException('Maximum limit reached') object_handle.AXValue += maxValue time.sleep(1.0 / 100) flag = True i += 1 if flag: return 1 else: raise LdtpServerException('Unable to increase scrollbar')
def oneup(self, window_name, object_name, iterations): """ Press scrollbar up with number of iterations @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param interations: iterations to perform on slider increase @type iterations: integer @return: 1 on success. @rtype: integer """ if not self.verifyscrollbarvertical(window_name, object_name): raise LdtpServerException('Object not vertical scrollbar') object_handle = self._get_object_handle(window_name, object_name) i = 0 minValue = 1.0 / 8 flag = False while i < iterations: if object_handle.AXValue <= 0: raise LdtpServerException('Minimum limit reached') object_handle.AXValue -= minValue time.sleep(1.0 / 100) flag = True i += 1 if flag: return 1 else: raise LdtpServerException('Unable to decrease scrollbar')
def oneright(self, window_name, object_name, iterations): """ Press scrollbar right with number of iterations @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param interations: iterations to perform on slider increase @type iterations: integer @return: 1 on success. @rtype: integer """ if not self.verifyscrollbarhorizontal(window_name, object_name): raise LdtpServerException('Object not horizontal scrollbar') object_handle = self._get_object_handle(window_name, object_name) i = 0 maxValue = 1.0 / 8 flag = False while i < iterations: if object_handle.AXValue >= 1: raise LdtpServerException('Maximum limit reached') object_handle.AXValue += maxValue time.sleep(1.0 / 100) flag = True i += 1 if flag: return 1 else: raise LdtpServerException('Unable to increase scrollbar')
def oneleft(self, window_name, object_name, iterations): """ Press scrollbar left with number of iterations @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param interations: iterations to perform on slider increase @type iterations: integer @return: 1 on success. @rtype: integer """ if not self.verifyscrollbarhorizontal(window_name, object_name): raise LdtpServerException('Object not horizontal scrollbar') object_handle = self._get_object_handle(window_name, object_name) i = 0 minValue = 1.0 / 8 flag = False while i < iterations: if object_handle.AXValue <= 0: raise LdtpServerException('Minimum limit reached') object_handle.AXValue -= minValue time.sleep(1.0 / 100) flag = True i += 1 if flag: return 1 else: raise LdtpServerException('Unable to decrease scrollbar')
def selecttab(self, window_name, object_name, tab_name): """ Select tab based on name. @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param tab_name: tab to select @type data: string @return: 1 on success. @rtype: integer """ tab_handle = self._get_tab_handle(window_name, object_name, tab_name) tab_handle.Press() return 1
def selecttabindex(self, window_name, object_name, tab_index): """ Select tab based on index. @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param tab_index: tab to select @type data: integer @return: 1 on success. @rtype: integer """ children = self._get_tab_children(window_name, object_name) length = len(children) if tab_index < 0 or tab_index > length: raise LdtpServerException(u"Invalid tab index %s" % tab_index) tab_handle = children[tab_index] if not tab_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % object_name) tab_handle.Press() return 1
def verifytabname(self, window_name, object_name, tab_name): """ Verify tab name. @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param tab_name: tab to select @type data: string @return: 1 on success 0 on failure @rtype: integer """ try: tab_handle = self._get_tab_handle(window_name, object_name, tab_name) if tab_handle.AXValue: return 1 except LdtpServerException: pass return 0
def gettabcount(self, window_name, object_name): """ Get tab count. @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: tab count on success. @rtype: integer """ children = self._get_tab_children(window_name, object_name) return len(children)
def gettabname(self, window_name, object_name, tab_index): """ Get tab name @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param tab_index: Index of tab (zero based index) @type object_name: int @return: text on success. @rtype: string """ children = self._get_tab_children(window_name, object_name) length = len(children) if tab_index < 0 or tab_index > length: raise LdtpServerException(u"Invalid tab index %s" % tab_index) tab_handle = children[tab_index] if not tab_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % object_name) return tab_handle.AXTitle
def mouseleftclick(self, window_name, object_name): """ Mouse left click on an object. @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. Or menu heirarchy @type object_name: string @return: 1 on success. @rtype: integer """ object_handle = self._get_object_handle(window_name, object_name) if not object_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % object_name) self._grabfocus(object_handle) x, y, width, height = self._getobjectsize(object_handle) # Mouse left click on the object object_handle.clickMouseButtonLeft((x + width / 2, y + height / 2)) return 1
def mouserightclick(self, window_name, object_name): """ Mouse right click on an object. @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. Or menu heirarchy @type object_name: string @return: 1 on success. @rtype: integer """ object_handle = self._get_object_handle(window_name, object_name) if not object_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % object_name) self._grabfocus(object_handle) x, y, width, height = self._getobjectsize(object_handle) # Mouse right click on the object object_handle.clickMouseButtonRight((x + width / 2, y + height / 2)) return 1
def generatemouseevent(self, x, y, eventType="b1c", drag_button_override='drag_default_button'): """ Generate mouse event on x, y co-ordinates. @param x: X co-ordinate @type x: int @param y: Y co-ordinate @type y: int @param eventType: Mouse click type @type eventType: str @param drag_button_override: Any drag_xxx value Only relevant for movements, i.e. |type| = "abs" or "rel" Quartz is not fully compatible with windows, so for drags the drag button must be explicitly defined. generatemouseevent will remember the last button pressed by default, and drag that button, use this argument to override that. @type drag_button_override: str @return: 1 on success. @rtype: integer """ if drag_button_override not in mouse_click_override: raise ValueError('Unsupported drag_button_override type: %s' % \ drag_button_override) global drag_button_remembered point = (x, y) button = centre # Only matters for "other" buttons click_type = None if eventType == "abs" or eventType == "rel": if drag_button_override is not 'drag_default_button': events = [mouse_click_override[drag_button_override]] elif drag_button_remembered: events = [drag_button_remembered] else: events = [move] if eventType == "rel": point = CGEventGetLocation(CGEventCreate(None)) point.x += x point.y += y elif eventType == "b1p": events = [press_left] drag_button_remembered = drag_left elif eventType == "b1r": events = [release_left] drag_button_remembered = None elif eventType == "b1c": events = [press_left, release_left] elif eventType == "b1d": events = [press_left, release_left] click_type = double_click elif eventType == "b2p": events = [press_other] drag_button_remembered = drag_other elif eventType == "b2r": events = [release_other] drag_button_remembered = None elif eventType == "b2c": events = [press_other, release_other] elif eventType == "b2d": events = [press_other, release_other] click_type = double_click elif eventType == "b3p": events = [press_right] drag_button_remembered = drag_right elif eventType == "b3r": events = [release_right] drag_button_remembered = None elif eventType == "b3c": events = [press_right, release_right] elif eventType == "b3d": events = [press_right, release_right] click_type = double_click else: raise LdtpServerException(u"Mouse event '%s' not implemented" % eventType) for event in events: CG_event = CGEventCreateMouseEvent(None, event, point, button) if click_type: CGEventSetIntegerValueField( CG_event, kCGMouseEventClickState, click_type) CGEventPost(kCGHIDEventTap, CG_event) # Give the event time to happen time.sleep(0.01) return 1
def doubleclick(self, window_name, object_name): """ Double click on the object @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. Or menu heirarchy @type object_name: string @return: 1 on success. @rtype: integer """ object_handle = self._get_object_handle(window_name, object_name) if not object_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % object_name) self._grabfocus(object_handle) x, y, width, height = self._getobjectsize(object_handle) window = self._get_front_most_window() # Mouse double click on the object # object_handle.doubleClick() window.doubleClickMouse((x + width / 2, y + height / 2)) return 1
def selectitem(self, window_name, object_name, item_name): """ Select combo box / layered pane item @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param item_name: Item name to select @type object_name: string @return: 1 on success. @rtype: integer """ object_handle = self._get_object_handle(window_name, object_name) if not object_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % object_name) self._grabfocus(object_handle.AXWindow) try: object_handle.Press() except AttributeError: # AXPress doesn't work with Instruments # So did the following work around x, y, width, height = self._getobjectsize(object_handle) # Mouse left click on the object # Note: x + width/2, y + height / 2 doesn't work self.generatemouseevent(x + 5, y + 5, "b1c") self.wait(5) handle = self._get_sub_menu_handle(object_handle, item_name) x, y, width, height = self._getobjectsize(handle) # on OSX 10.7 default "b1c" doesn't work # so using "b1d", verified with Fusion test, this works self.generatemouseevent(x + 5, y + 5, "b1d") return 1 # Required for menuitem to appear in accessibility list self.wait(1) menu_list = re.split(";", item_name) try: menu_handle = self._internal_menu_handler(object_handle, menu_list, True) # Required for menuitem to appear in accessibility list self.wait(1) if not menu_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % \ menu_list[-1]) menu_handle.Press() except LdtpServerException: object_handle.activate() object_handle.sendKey(AXKeyCodeConstants.ESCAPE) raise return 1
def selectindex(self, window_name, object_name, item_index): """ Select combo box item / layered pane based on index @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param item_index: Item index to select @type object_name: integer @return: 1 on success. @rtype: integer """ object_handle = self._get_object_handle(window_name, object_name) if not object_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % object_name) self._grabfocus(object_handle.AXWindow) try: object_handle.Press() except AttributeError: # AXPress doesn't work with Instruments # So did the following work around x, y, width, height = self._getobjectsize(object_handle) # Mouse left click on the object # Note: x + width/2, y + height / 2 doesn't work self.generatemouseevent(x + 5, y + 5, "b1c") # Required for menuitem to appear in accessibility list self.wait(2) if not object_handle.AXChildren: raise LdtpServerException(u"Unable to find menu") # Get AXMenu children = object_handle.AXChildren[0] if not children: raise LdtpServerException(u"Unable to find menu") children = children.AXChildren tmp_children = [] for child in children: role, label = self._ldtpize_accessible(child) # Don't add empty label # Menu separator have empty label's if label: tmp_children.append(child) children = tmp_children length = len(children) try: if item_index < 0 or item_index > length: raise LdtpServerException(u"Invalid item index %d" % item_index) menu_handle = children[item_index] if not menu_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % menu_list[-1]) self._grabfocus(menu_handle) x, y, width, height = self._getobjectsize(menu_handle) # on OSX 10.7 default "b1c" doesn't work # so using "b1d", verified with Fusion test, this works window = object_handle.AXWindow # For some reason, # self.generatemouseevent(x + 5, y + 5, "b1d") # doesn't work with Fusion settings # Advanced window, so work around with this # ldtp.selectindex('*Advanced', 'Automatic', 1) """ Traceback (most recent call last): File "build/bdist.macosx-10.8-intel/egg/atomac/ldtpd/utils.py", line 178, in _dispatch return getattr(self, method)(*args) File "build/bdist.macosx-10.8-intel/egg/atomac/ldtpd/combo_box.py", line 146, in selectindex self.generatemouseevent(x + 5, y + 5, "b1d") File "build/bdist.macosx-10.8-intel/egg/atomac/ldtpd/mouse.py", line 97, in generatemouseevent window=self._get_front_most_window() File "build/bdist.macosx-10.8-intel/egg/atomac/ldtpd/utils.py", line 185, in _get_front_most_window front_app=atomac.NativeUIElement.getFrontmostApp() File "build/bdist.macosx-10.8-intel/egg/atomac/AXClasses.py", line 114, in getFrontmostApp raise ValueError('No GUI application found.') ValueError: No GUI application found. """ window.doubleClickMouse((x + 5, y + 5)) # If menuitem already pressed, set child to None # So, it doesn't click back in combobox in finally block child = None finally: if child: child.Cancel() return 1
def getallitem(self, window_name, object_name): """ Get all combo box item @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: list of string on success. @rtype: list """ object_handle = self._get_object_handle(window_name, object_name) if not object_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % object_name) object_handle.Press() # Required for menuitem to appear in accessibility list self.wait(1) child = None try: if not object_handle.AXChildren: raise LdtpServerException(u"Unable to find menu") # Get AXMenu children = object_handle.AXChildren[0] if not children: raise LdtpServerException(u"Unable to find menu") children = children.AXChildren items = [] for child in children: label = self._get_title(child) # Don't add empty label # Menu separator have empty label's if label: items.append(label) finally: if child: # Set it back, by clicking combo box child.Cancel() return items
def showlist(self, window_name, object_name): """ Show combo box list / menu @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: 1 on success. @rtype: integer """ object_handle = self._get_object_handle(window_name, object_name) if not object_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % object_name) object_handle.Press() return 1
def hidelist(self, window_name, object_name): """ Hide combo box list / menu @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: 1 on success. @rtype: integer """ object_handle = self._get_object_handle(window_name, object_name) object_handle.activate() object_handle.sendKey(AXKeyCodeConstants.ESCAPE) return 1
def verifydropdown(self, window_name, object_name): """ Verify drop down list / menu poped up @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: 1 on success 0 on failure. @rtype: integer """ try: object_handle = self._get_object_handle(window_name, object_name) if not object_handle.AXEnabled or not object_handle.AXChildren: return 0 # Get AXMenu children = object_handle.AXChildren[0] if children: return 1 except LdtpServerException: pass return 0
def verifyselect(self, window_name, object_name, item_name): """ Verify the item selected in combo box @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param item_name: Item name to select @type object_name: string @return: 1 on success. @rtype: integer """ try: object_handle = self._get_object_handle(window_name, object_name) if not object_handle.AXEnabled: return 0 role, label = self._ldtpize_accessible(object_handle) title = self._get_title(object_handle) if re.match(item_name, title, re.M | re.U | re.L) or \ re.match(item_name, label, re.M | re.U | re.L) or \ re.match(item_name, u"%u%u" % (role, label), re.M | re.U | re.L): return 1 except LdtpServerException: pass return 0
def getcombovalue(self, window_name, object_name): """ Get current selected combobox value @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: selected item on success, else LdtpExecutionError on failure. @rtype: string """ object_handle = self._get_object_handle(window_name, object_name) if not object_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % object_name) return self._get_title(object_handle)
def login(self, username=None, password=None, android_id=None): """Authenticate the gmusicapi Mobileclient instance. Parameters: username (Optional[str]): Your Google Music username. Will be prompted if not given. password (Optional[str]): Your Google Music password. Will be prompted if not given. android_id (Optional[str]): The 16 hex digits from an Android device ID. Default: Use gmusicapi.Mobileclient.FROM_MAC_ADDRESS to create ID from computer's MAC address. Returns: ``True`` on successful login or ``False`` on unsuccessful login. """ cls_name = type(self).__name__ if username is None: username = input("Enter your Google username or email address: ") if password is None: password = getpass.getpass("Enter your Google Music password: ") if android_id is None: android_id = Mobileclient.FROM_MAC_ADDRESS try: self.api.login(username, password, android_id) except OSError: logger.exception("{} authentication failed.".format(cls_name)) if not self.is_authenticated: logger.warning("{} authentication failed.".format(cls_name)) return False logger.info("{} authentication succeeded.\n".format(cls_name)) return True
def get_google_songs(self, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False): """Create song list from user's Google Music library. Parameters: include_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid Google Music metadata field available to the Mobileclient client. Patterns are Python regex patterns. Google Music songs are filtered out if the given metadata field values don't match any of the given patterns. exclude_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid Google Music metadata field available to the Mobileclient client. Patterns are Python regex patterns. Google Music songs are filtered out if the given metadata field values match any of the given patterns. all_includes (bool): If ``True``, all include_filters criteria must match to include a song. all_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song. Returns: A list of Google Music song dicts matching criteria and a list of Google Music song dicts filtered out using filter criteria. """ logger.info("Loading Google Music songs...") google_songs = self.api.get_all_songs() matched_songs, filtered_songs = filter_google_songs( google_songs, include_filters=include_filters, exclude_filters=exclude_filters, all_includes=all_includes, all_excludes=all_excludes ) logger.info("Filtered {0} Google Music songs".format(len(filtered_songs))) logger.info("Loaded {0} Google Music songs".format(len(matched_songs))) return matched_songs, filtered_songs
def get_google_playlist(self, playlist): """Get playlist information of a user-generated Google Music playlist. Parameters: playlist (str): Name or ID of Google Music playlist. Names are case-sensitive. Google allows multiple playlists with the same name. If multiple playlists have the same name, the first one encountered is used. Returns: dict: The playlist dict as returned by Mobileclient.get_all_user_playlist_contents. """ logger.info("Loading playlist {0}".format(playlist)) for google_playlist in self.api.get_all_user_playlist_contents(): if google_playlist['name'] == playlist or google_playlist['id'] == playlist: return google_playlist else: logger.warning("Playlist {0} does not exist.".format(playlist)) return {}
def get_google_playlist_songs(self, playlist, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False): """Create song list from a user-generated Google Music playlist. Parameters: playlist (str): Name or ID of Google Music playlist. Names are case-sensitive. Google allows multiple playlists with the same name. If multiple playlists have the same name, the first one encountered is used. include_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid Google Music metadata field available to the Musicmanager client. Patterns are Python regex patterns. Google Music songs are filtered out if the given metadata field values don't match any of the given patterns. exclude_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid Google Music metadata field available to the Musicmanager client. Patterns are Python regex patterns. Google Music songs are filtered out if the given metadata field values match any of the given patterns. all_includes (bool): If ``True``, all include_filters criteria must match to include a song. all_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song. Returns: A list of Google Music song dicts in the playlist matching criteria and a list of Google Music song dicts in the playlist filtered out using filter criteria. """ logger.info("Loading Google Music playlist songs...") google_playlist = self.get_google_playlist(playlist) if not google_playlist: return [], [] playlist_song_ids = [track['trackId'] for track in google_playlist['tracks']] playlist_songs = [song for song in self.api.get_all_songs() if song['id'] in playlist_song_ids] matched_songs, filtered_songs = filter_google_songs( playlist_songs, include_filters=include_filters, exclude_filters=exclude_filters, all_includes=all_includes, all_excludes=all_excludes ) logger.info("Filtered {0} Google playlist songs".format(len(filtered_songs))) logger.info("Loaded {0} Google playlist songs".format(len(matched_songs))) return matched_songs, filtered_songs
def cast_to_list(position): """Cast the positional argument at given position into a list if not already a list.""" @wrapt.decorator def wrapper(function, instance, args, kwargs): if not isinstance(args[position], list): args = list(args) args[position] = [args[position]] args = tuple(args) return function(*args, **kwargs) return wrapper
def _pybossa_req(method, domain, id=None, payload=None, params={}, headers={'content-type': 'application/json'}, files=None): """ Send a JSON request. Returns True if everything went well, otherwise it returns the status code of the response. """ url = _opts['endpoint'] + '/api/' + domain if id is not None: url += '/' + str(id) if 'api_key' in _opts: params['api_key'] = _opts['api_key'] if method == 'get': r = requests.get(url, params=params) elif method == 'post': if files is None and headers['content-type'] == 'application/json': r = requests.post(url, params=params, headers=headers, data=json.dumps(payload)) else: r = requests.post(url, params=params, files=files, data=payload) elif method == 'put': r = requests.put(url, params=params, headers=headers, data=json.dumps(payload)) elif method == 'delete': r = requests.delete(url, params=params, headers=headers, data=json.dumps(payload)) if r.status_code // 100 == 2: if r.text and r.text != '""': return json.loads(r.text) else: return True else: return json.loads(r.text)
def get_projects(limit=100, offset=0, last_id=None): """Return a list of registered projects. :param limit: Number of returned items, default 100 :type limit: integer :param offset: Offset for the query, default 0 :type offset: integer :param last_id: id of the last project, used for pagination. If provided, offset is ignored :type last_id: integer :rtype: list :returns: A list of PYBOSSA Projects """ if last_id is not None: params = dict(limit=limit, last_id=last_id) else: print(OFFSET_WARNING) params = dict(limit=limit, offset=offset) try: res = _pybossa_req('get', 'project', params=params) if type(res).__name__ == 'list': return [Project(project) for project in res] else: raise TypeError except: # pragma: no cover raise
def get_project(project_id): """Return a PYBOSSA Project for the project_id. :param project_id: PYBOSSA Project ID :type project_id: integer :rtype: PYBOSSA Project :returns: A PYBOSSA Project object """ try: res = _pybossa_req('get', 'project', project_id) if res.get('id'): return Project(res) else: return res except: # pragma: no cover raise
def find_project(**kwargs): """Return a list with matching project arguments. :param kwargs: PYBOSSA Project members :rtype: list :returns: A list of projects that match the kwargs """ try: res = _pybossa_req('get', 'project', params=kwargs) if type(res).__name__ == 'list': return [Project(project) for project in res] else: return res except: # pragma: no cover raise
def create_project(name, short_name, description): """Create a project. :param name: PYBOSSA Project Name :type name: string :param short_name: PYBOSSA Project short name or slug :type short_name: string :param description: PYBOSSA Project description :type decription: string :returns: True -- the response status code """ try: project = dict(name=name, short_name=short_name, description=description) res = _pybossa_req('post', 'project', payload=project) if res.get('id'): return Project(res) else: return res except: # pragma: no cover raise
def update_project(project): """Update a project instance. :param project: PYBOSSA project :type project: PYBOSSA Project :returns: True -- the response status code """ try: project_id = project.id project = _forbidden_attributes(project) res = _pybossa_req('put', 'project', project_id, payload=project.data) if res.get('id'): return Project(res) else: return res except: # pragma: no cover raise
def delete_project(project_id): """Delete a Project with id = project_id. :param project_id: PYBOSSA Project ID :type project_id: integer :returns: True -- the response status code """ try: res = _pybossa_req('delete', 'project', project_id) if type(res).__name__ == 'bool': return True else: return res except: # pragma: no cover raise
def get_categories(limit=20, offset=0, last_id=None): """Return a list of registered categories. :param limit: Number of returned items, default 20 :type limit: integer :param offset: Offset for the query, default 0 :type offset: integer :param last_id: id of the last category, used for pagination. If provided, offset is ignored :type last_id: integer :rtype: list :returns: A list of PYBOSSA Categories """ if last_id is not None: params = dict(limit=limit, last_id=last_id) else: params = dict(limit=limit, offset=offset) print(OFFSET_WARNING) try: res = _pybossa_req('get', 'category', params=params) if type(res).__name__ == 'list': return [Category(category) for category in res] else: raise TypeError except: raise
def get_category(category_id): """Return a PYBOSSA Category for the category_id. :param category_id: PYBOSSA Category ID :type category_id: integer :rtype: PYBOSSA Category :returns: A PYBOSSA Category object """ try: res = _pybossa_req('get', 'category', category_id) if res.get('id'): return Category(res) else: return res except: # pragma: no cover raise
def find_category(**kwargs): """Return a list with matching Category arguments. :param kwargs: PYBOSSA Category members :rtype: list :returns: A list of project that match the kwargs """ try: res = _pybossa_req('get', 'category', params=kwargs) if type(res).__name__ == 'list': return [Category(category) for category in res] else: return res except: # pragma: no cover raise
def create_category(name, description): """Create a Category. :param name: PYBOSSA Category Name :type name: string :param description: PYBOSSA Category description :type decription: string :returns: True -- the response status code """ try: category = dict(name=name, short_name=name.lower().replace(" ", ""), description=description) res = _pybossa_req('post', 'category', payload=category) if res.get('id'): return Category(res) else: return res except: # pragma: no cover raise
def update_category(category): """Update a Category instance. :param category: PYBOSSA Category :type category: PYBOSSA Category :returns: True -- the response status code """ try: res = _pybossa_req('put', 'category', category.id, payload=category.data) if res.get('id'): return Category(res) else: return res except: # pragma: no cover raise
def delete_category(category_id): """Delete a Category with id = category_id. :param category_id: PYBOSSA Category ID :type category_id: integer :returns: True -- the response status code """ try: res = _pybossa_req('delete', 'category', category_id) if type(res).__name__ == 'bool': return True else: return res except: # pragma: no cover raise
def get_tasks(project_id, limit=100, offset=0, last_id=None): """Return a list of tasks for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param limit: Number of returned items, default 100 :type limit: integer :param offset: Offset for the query, default 0 :param last_id: id of the last task, used for pagination. If provided, offset is ignored :type last_id: integer :type offset: integer :returns: True -- the response status code """ if last_id is not None: params = dict(limit=limit, last_id=last_id) else: params = dict(limit=limit, offset=offset) print(OFFSET_WARNING) params['project_id'] = project_id try: res = _pybossa_req('get', 'task', params=params) if type(res).__name__ == 'list': return [Task(task) for task in res] else: return res except: # pragma: no cover raise
def find_tasks(project_id, **kwargs): """Return a list of matched tasks for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param kwargs: PYBOSSA Task members :type info: dict :rtype: list :returns: A list of tasks that match the kwargs """ try: kwargs['project_id'] = project_id res = _pybossa_req('get', 'task', params=kwargs) if type(res).__name__ == 'list': return [Task(task) for task in res] else: return res except: # pragma: no cover raise
def create_task(project_id, info, n_answers=30, priority_0=0, quorum=0): """Create a task for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param info: PYBOSSA Project info JSON field :type info: dict :param n_answers: Number of answers or TaskRuns per task, default 30 :type n_answers: integer :param priority_0: Value between 0 and 1 indicating priority of task within Project (higher = more important), default 0.0 :type priority_0: float :param quorum: Number of times this task should be done by different users, default 0 :type quorum: integer :returns: True -- the response status code """ try: task = dict( project_id=project_id, info=info, calibration=0, priority_0=priority_0, n_answers=n_answers, quorum=quorum ) res = _pybossa_req('post', 'task', payload=task) if res.get('id'): return Task(res) else: return res except: # pragma: no cover raise
def update_task(task): """Update a task for a given task ID. :param task: PYBOSSA task """ try: task_id = task.id task = _forbidden_attributes(task) res = _pybossa_req('put', 'task', task_id, payload=task.data) if res.get('id'): return Task(res) else: return res except: # pragma: no cover raise
def delete_task(task_id): """Delete a task for a given task ID. :param task: PYBOSSA task """ #: :arg task: A task try: res = _pybossa_req('delete', 'task', task_id) if type(res).__name__ == 'bool': return True else: return res except: # pragma: no cover raise
def get_taskruns(project_id, limit=100, offset=0, last_id=None): """Return a list of task runs for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param limit: Number of returned items, default 100 :type limit: integer :param offset: Offset for the query, default 0 :type offset: integer :param last_id: id of the last taskrun, used for pagination. If provided, offset is ignored :type last_id: integer :rtype: list :returns: A list of task runs for the given project ID """ if last_id is not None: params = dict(limit=limit, last_id=last_id) else: params = dict(limit=limit, offset=offset) print(OFFSET_WARNING) params['project_id'] = project_id try: res = _pybossa_req('get', 'taskrun', params=params) if type(res).__name__ == 'list': return [TaskRun(taskrun) for taskrun in res] else: raise TypeError except: raise
def find_taskruns(project_id, **kwargs): """Return a list of matched task runs for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param kwargs: PYBOSSA Task Run members :rtype: list :returns: A List of task runs that match the query members """ try: kwargs['project_id'] = project_id res = _pybossa_req('get', 'taskrun', params=kwargs) if type(res).__name__ == 'list': return [TaskRun(taskrun) for taskrun in res] else: return res except: # pragma: no cover raise
def delete_taskrun(taskrun_id): """Delete the given taskrun. :param task: PYBOSSA task """ try: res = _pybossa_req('delete', 'taskrun', taskrun_id) if type(res).__name__ == 'bool': return True else: return res except: # pragma: no cover raise
def get_results(project_id, limit=100, offset=0, last_id=None): """Return a list of results for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param limit: Number of returned items, default 100 :type limit: integer :param offset: Offset for the query, default 0 :param last_id: id of the last result, used for pagination. If provided, offset is ignored :type last_id: integer :type offset: integer :returns: True -- the response status code """ if last_id is not None: params = dict(limit=limit, last_id=last_id) else: params = dict(limit=limit, offset=offset) print(OFFSET_WARNING) params['project_id'] = project_id try: res = _pybossa_req('get', 'result', params=params) if type(res).__name__ == 'list': return [Result(result) for result in res] else: return res except: # pragma: no cover raise
def find_results(project_id, **kwargs): """Return a list of matched results for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param kwargs: PYBOSSA Results members :type info: dict :rtype: list :returns: A list of results that match the kwargs """ try: kwargs['project_id'] = project_id res = _pybossa_req('get', 'result', params=kwargs) if type(res).__name__ == 'list': return [Result(result) for result in res] else: return res except: # pragma: no cover raise
def update_result(result): """Update a result for a given result ID. :param result: PYBOSSA result """ try: result_id = result.id result = _forbidden_attributes(result) res = _pybossa_req('put', 'result', result_id, payload=result.data) if res.get('id'): return Result(res) else: return res except: # pragma: no cover raise
def _forbidden_attributes(obj): """Return the object without the forbidden attributes.""" for key in list(obj.data.keys()): if key in list(obj.reserved_keys.keys()): obj.data.pop(key) return obj
def create_helpingmaterial(project_id, info, media_url=None, file_path=None): """Create a helping material for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param info: PYBOSSA Helping Material info JSON field :type info: dict :param media_url: URL for a media file (image, video or audio) :type media_url: string :param file_path: File path to the local image, video or sound to upload. :type file_path: string :returns: True -- the response status code """ try: helping = dict( project_id=project_id, info=info, media_url=None, ) if file_path: files = {'file': open(file_path, 'rb')} payload = {'project_id': project_id} res = _pybossa_req('post', 'helpingmaterial', payload=payload, files=files) else: res = _pybossa_req('post', 'helpingmaterial', payload=helping) if res.get('id'): return HelpingMaterial(res) else: return res except: # pragma: no cover raise
def get_helping_materials(project_id, limit=100, offset=0, last_id=None): """Return a list of helping materials for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param limit: Number of returned items, default 100 :type limit: integer :param offset: Offset for the query, default 0 :param last_id: id of the last helping material, used for pagination. If provided, offset is ignored :type last_id: integer :type offset: integer :returns: True -- the response status code """ if last_id is not None: params = dict(limit=limit, last_id=last_id) else: params = dict(limit=limit, offset=offset) print(OFFSET_WARNING) params['project_id'] = project_id try: res = _pybossa_req('get', 'helpingmaterial', params=params) if type(res).__name__ == 'list': return [HelpingMaterial(helping) for helping in res] else: return res except: # pragma: no cover raise
def find_helping_materials(project_id, **kwargs): """Return a list of matched helping materials for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param kwargs: PYBOSSA HelpingMaterial members :type info: dict :rtype: list :returns: A list of helping materials that match the kwargs """ try: kwargs['project_id'] = project_id res = _pybossa_req('get', 'helpingmaterial', params=kwargs) if type(res).__name__ == 'list': return [HelpingMaterial(helping) for helping in res] else: return res except: # pragma: no cover raise
def update_helping_material(helpingmaterial): """Update a helping material for a given helping material ID. :param helpingmaterial: PYBOSSA helping material """ try: helpingmaterial_id = helpingmaterial.id helpingmaterial = _forbidden_attributes(helpingmaterial) res = _pybossa_req('put', 'helpingmaterial', helpingmaterial_id, payload=helpingmaterial.data) if res.get('id'): return HelpingMaterial(res) else: return res except: # pragma: no cover raise
def login(self, oauth_filename="oauth", uploader_id=None): """Authenticate the gmusicapi Musicmanager instance. Parameters: oauth_filename (str): The filename of the oauth credentials file to use/create for login. Default: ``oauth`` uploader_id (str): A unique id as a MAC address (e.g. ``'00:11:22:33:AA:BB'``). This should only be provided in cases where the default (host MAC address incremented by 1) won't work. Returns: ``True`` on successful login, ``False`` on unsuccessful login. """ cls_name = type(self).__name__ oauth_cred = os.path.join(os.path.dirname(OAUTH_FILEPATH), oauth_filename + '.cred') try: if not self.api.login(oauth_credentials=oauth_cred, uploader_id=uploader_id): try: self.api.perform_oauth(storage_filepath=oauth_cred) except OSError: logger.exception("\nUnable to login with specified oauth code.") self.api.login(oauth_credentials=oauth_cred, uploader_id=uploader_id) except (OSError, ValueError): logger.exception("{} authentication failed.".format(cls_name)) return False if not self.is_authenticated: logger.warning("{} authentication failed.".format(cls_name)) return False logger.info("{} authentication succeeded.\n".format(cls_name)) return True
def get_google_songs( self, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False, uploaded=True, purchased=True): """Create song list from user's Google Music library. Parameters: include_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid Google Music metadata field available to the Musicmanager client. Patterns are Python regex patterns. Google Music songs are filtered out if the given metadata field values don't match any of the given patterns. exclude_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid Google Music metadata field available to the Musicmanager client. Patterns are Python regex patterns. Google Music songs are filtered out if the given metadata field values match any of the given patterns. all_includes (bool): If ``True``, all include_filters criteria must match to include a song. all_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song. uploaded (bool): Include uploaded songs. Default: ``True``. purchased (bool): Include purchased songs. Default: ``True``. Returns: A list of Google Music song dicts matching criteria and a list of Google Music song dicts filtered out using filter criteria. """ if not uploaded and not purchased: raise ValueError("One or both of uploaded/purchased parameters must be True.") logger.info("Loading Google Music songs...") google_songs = [] if uploaded: google_songs += self.api.get_uploaded_songs() if purchased: for song in self.api.get_purchased_songs(): if song not in google_songs: google_songs.append(song) matched_songs, filtered_songs = filter_google_songs( google_songs, include_filters=include_filters, exclude_filters=exclude_filters, all_includes=all_includes, all_excludes=all_excludes ) logger.info("Filtered {0} Google Music songs".format(len(filtered_songs))) logger.info("Loaded {0} Google Music songs".format(len(matched_songs))) return matched_songs, filtered_songs
def download(self, songs, template=None): """Download Google Music songs. Parameters: songs (list or dict): Google Music song dict(s). template (str): A filepath which can include template patterns. Returns: A list of result dictionaries. :: [ {'result': 'downloaded', 'id': song_id, 'filepath': downloaded[song_id]}, # downloaded {'result': 'error', 'id': song_id, 'message': error[song_id]} # error ] """ if not template: template = os.getcwd() songnum = 0 total = len(songs) results = [] errors = {} pad = len(str(total)) for result in self._download(songs, template): song_id = songs[songnum]['id'] songnum += 1 downloaded, error = result if downloaded: logger.info( "({num:>{pad}}/{total}) Successfully downloaded -- {file} ({song_id})".format( num=songnum, pad=pad, total=total, file=downloaded[song_id], song_id=song_id ) ) results.append({'result': 'downloaded', 'id': song_id, 'filepath': downloaded[song_id]}) elif error: title = songs[songnum].get('title', "<empty>") artist = songs[songnum].get('artist', "<empty>") album = songs[songnum].get('album', "<empty>") logger.info( "({num:>{pad}}/{total}) Error on download -- {title} -- {artist} -- {album} ({song_id})".format( num=songnum, pad=pad, total=total, title=title, artist=artist, album=album, song_id=song_id ) ) results.append({'result': 'error', 'id': song_id, 'message': error[song_id]}) if errors: logger.info("\n\nThe following errors occurred:\n") for filepath, e in errors.items(): logger.info("{file} | {error}".format(file=filepath, error=e)) logger.info("\nThese files may need to be synced again.\n") return results
def upload(self, filepaths, enable_matching=False, transcode_quality='320k', delete_on_success=False): """Upload local songs to Google Music. Parameters: filepaths (list or str): Filepath(s) to upload. enable_matching (bool): If ``True`` attempt to use `scan and match <http://support.google.com/googleplay/bin/answer.py?hl=en&answer=2920799&topic=2450455>`__. This requieres ffmpeg or avconv. transcode_quality (str or int): If int, pass to ffmpeg/avconv ``-q:a`` for libmp3lame `VBR quality <http://trac.ffmpeg.org/wiki/Encode/MP3#VBREncoding>'__. If string, pass to ffmpeg/avconv ``-b:a`` for libmp3lame `CBR quality <http://trac.ffmpeg.org/wiki/Encode/MP3#CBREncoding>'__. Default: ``320k`` delete_on_success (bool): Delete successfully uploaded local files. Default: ``False`` Returns: A list of result dictionaries. :: [ {'result': 'uploaded', 'filepath': <filepath>, 'id': <song_id>}, # uploaded {'result': 'matched', 'filepath': <filepath>, 'id': <song_id>}, # matched {'result': 'error', 'filepath': <filepath>, 'message': <error_message>}, # error {'result': 'not_uploaded', 'filepath': <filepath>, 'id': <song_id>, 'message': <reason_message>}, # not_uploaded ALREADY_EXISTS {'result': 'not_uploaded', 'filepath': <filepath>, 'message': <reason_message>} # not_uploaded ] """ filenum = 0 total = len(filepaths) results = [] errors = {} pad = len(str(total)) exist_strings = ["ALREADY_EXISTS", "this song is already uploaded"] for result in self._upload(filepaths, enable_matching=enable_matching, transcode_quality=transcode_quality): filepath = filepaths[filenum] filenum += 1 uploaded, matched, not_uploaded, error = result if uploaded: logger.info( "({num:>{pad}}/{total}) Successfully uploaded -- {file} ({song_id})".format( num=filenum, pad=pad, total=total, file=filepath, song_id=uploaded[filepath] ) ) results.append({'result': 'uploaded', 'filepath': filepath, 'id': uploaded[filepath]}) elif matched: logger.info( "({num:>{pad}}/{total}) Successfully scanned and matched -- {file} ({song_id})".format( num=filenum, pad=pad, total=total, file=filepath, song_id=matched[filepath] ) ) results.append({'result': 'matched', 'filepath': filepath, 'id': matched[filepath]}) elif error: logger.warning("({num:>{pad}}/{total}) Error on upload -- {file}".format(num=filenum, pad=pad, total=total, file=filepath)) results.append({'result': 'error', 'filepath': filepath, 'message': error[filepath]}) errors.update(error) else: if any(exist_string in not_uploaded[filepath] for exist_string in exist_strings): response = "ALREADY EXISTS" song_id = GM_ID_RE.search(not_uploaded[filepath]).group(0) logger.info( "({num:>{pad}}/{total}) Failed to upload -- {file} ({song_id}) | {response}".format( num=filenum, pad=pad, total=total, file=filepath, response=response, song_id=song_id ) ) results.append({'result': 'not_uploaded', 'filepath': filepath, 'id': song_id, 'message': not_uploaded[filepath]}) else: response = not_uploaded[filepath] logger.info( "({num:>{pad}}/{total}) Failed to upload -- {file} | {response}".format( num=filenum, pad=pad, total=total, file=filepath, response=response ) ) results.append({'result': 'not_uploaded', 'filepath': filepath, 'message': not_uploaded[filepath]}) success = (uploaded or matched) or (not_uploaded and 'ALREADY_EXISTS' in not_uploaded[filepath]) if success and delete_on_success: try: os.remove(filepath) except (OSError, PermissionError): logger.warning("Failed to remove {} after successful upload".format(filepath)) if errors: logger.info("\n\nThe following errors occurred:\n") for filepath, e in errors.items(): logger.info("{file} | {error}".format(file=filepath, error=e)) logger.info("\nThese filepaths may need to be synced again.\n") return results
def convert_cygwin_path(path): """Convert Unix path from Cygwin to Windows path.""" try: win_path = subprocess.check_output(["cygpath", "-aw", path], universal_newlines=True).strip() except (FileNotFoundError, subprocess.CalledProcessError): logger.exception("Call to cygpath failed.") raise return win_path
def _get_mutagen_metadata(filepath): """Get mutagen metadata dict from a file.""" try: metadata = mutagen.File(filepath, easy=True) except mutagen.MutagenError: logger.warning("Can't load {} as music file.".format(filepath)) raise return metadata
def _mutagen_fields_to_single_value(metadata): """Replace mutagen metadata field list values in mutagen tags with the first list value.""" return dict((k, v[0]) for k, v in metadata.items() if v)
def _split_field_to_single_value(field): """Convert number field values split by a '/' to a single number value.""" split_field = re.match(r'(\d+)/\d+', field) return split_field.group(1) or field
def _normalize_metadata(metadata): """Normalize metadata to improve match accuracy.""" metadata = str(metadata) metadata = metadata.lower() metadata = re.sub(r'\/\s*\d+', '', metadata) # Remove "/<totaltracks>" from track number. metadata = re.sub(r'^0+([0-9]+)', r'\1', metadata) # Remove leading zero(s) from track number. metadata = re.sub(r'^\d+\.+', '', metadata) # Remove dots from track number. metadata = re.sub(r'[^\w\s]', '', metadata) # Remove any non-words. metadata = re.sub(r'\s+', ' ', metadata) # Reduce multiple spaces to a single space. metadata = re.sub(r'^\s+', '', metadata) # Remove leading space. metadata = re.sub(r'\s+$', '', metadata) # Remove trailing space. metadata = re.sub(r'^the\s+', '', metadata, re.I) # Remove leading "the". return metadata
def compare_song_collections(src_songs, dst_songs): """Compare two song collections to find missing songs. Parameters: src_songs (list): Google Music song dicts or filepaths of local songs. dest_songs (list): Google Music song dicts or filepaths of local songs. Returns: A list of Google Music song dicts or local song filepaths from source missing in destination. """ def gather_field_values(song): return tuple((_normalize_metadata(song[field]) for field in _filter_comparison_fields(song))) dst_songs_criteria = {gather_field_values(_normalize_song(dst_song)) for dst_song in dst_songs} return [src_song for src_song in src_songs if gather_field_values(_normalize_song(src_song)) not in dst_songs_criteria]
def get_supported_filepaths(filepaths, supported_extensions, max_depth=float('inf')): """Get filepaths with supported extensions from given filepaths. Parameters: filepaths (list or str): Filepath(s) to check. supported_extensions (tuple or str): Supported file extensions or a single file extension. max_depth (int): The depth in the directory tree to walk. A depth of '0' limits the walk to the top directory. Default: No limit. Returns: A list of supported filepaths. """ supported_filepaths = [] for path in filepaths: if os.name == 'nt' and CYGPATH_RE.match(path): path = convert_cygwin_path(path) if os.path.isdir(path): for root, __, files in walk_depth(path, max_depth): for f in files: if f.lower().endswith(supported_extensions): supported_filepaths.append(os.path.join(root, f)) elif os.path.isfile(path) and path.lower().endswith(supported_extensions): supported_filepaths.append(path) return supported_filepaths
def exclude_filepaths(filepaths, exclude_patterns=None): """Exclude file paths based on regex patterns. Parameters: filepaths (list or str): Filepath(s) to check. exclude_patterns (list): Python regex patterns to check filepaths against. Returns: A list of filepaths to include and a list of filepaths to exclude. """ if not exclude_patterns: return filepaths, [] exclude_re = re.compile("|".join(pattern for pattern in exclude_patterns)) included_songs = [] excluded_songs = [] for filepath in filepaths: if exclude_patterns and exclude_re.search(filepath): excluded_songs.append(filepath) else: included_songs.append(filepath) return included_songs, excluded_songs
def _check_field_value(field_value, pattern): """Check a song metadata field value for a pattern.""" if isinstance(field_value, list): return any(re.search(pattern, str(value), re.I) for value in field_value) else: return re.search(pattern, str(field_value), re.I)
def _check_filters(song, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False): """Check a song metadata dict against a set of metadata filters.""" include = True if include_filters: if all_includes: if not all(field in song and _check_field_value(song[field], pattern) for field, pattern in include_filters): include = False else: if not any(field in song and _check_field_value(song[field], pattern) for field, pattern in include_filters): include = False if exclude_filters: if all_excludes: if all(field in song and _check_field_value(song[field], pattern) for field, pattern in exclude_filters): include = False else: if any(field in song and _check_field_value(song[field], pattern) for field, pattern in exclude_filters): include = False return include
def filter_google_songs(songs, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False): """Match a Google Music song dict against a set of metadata filters. Parameters: songs (list): Google Music song dicts to filter. include_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid Google Music metadata field available to the Musicmanager client. Patterns are Python regex patterns. Google Music songs are filtered out if the given metadata field values don't match any of the given patterns. exclude_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid Google Music metadata field available to the Musicmanager client. Patterns are Python regex patterns. Google Music songs are filtered out if the given metadata field values match any of the given patterns. all_includes (bool): If ``True``, all include_filters criteria must match to include a song. all_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song. Returns: A list of Google Music song dicts matching criteria and a list of Google Music song dicts filtered out using filter criteria. :: (matched, filtered) """ matched_songs = [] filtered_songs = [] if include_filters or exclude_filters: for song in songs: if _check_filters( song, include_filters=include_filters, exclude_filters=exclude_filters, all_includes=all_includes, all_excludes=all_excludes): matched_songs.append(song) else: filtered_songs.append(song) else: matched_songs += songs return matched_songs, filtered_songs
def filter_local_songs(filepaths, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False): """Match a local file against a set of metadata filters. Parameters: filepaths (list): Filepaths to filter. include_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid mutagen metadata fields. Patterns are Python regex patterns. Local songs are filtered out if the given metadata field values don't match any of the given patterns. exclude_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid mutagen metadata fields. Patterns are Python regex patterns. Local songs are filtered out if the given metadata field values match any of the given patterns. all_includes (bool): If ``True``, all include_filters criteria must match to include a song. all_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song. Returns: A list of local song filepaths matching criteria and a list of local song filepaths filtered out using filter criteria. Invalid music files are also filtered out. :: (matched, filtered) """ matched_songs = [] filtered_songs = [] for filepath in filepaths: try: song = _get_mutagen_metadata(filepath) except mutagen.MutagenError: filtered_songs.append(filepath) else: if include_filters or exclude_filters: if _check_filters( song, include_filters=include_filters, exclude_filters=exclude_filters, all_includes=all_includes, all_excludes=all_excludes): matched_songs.append(filepath) else: filtered_songs.append(filepath) else: matched_songs.append(filepath) return matched_songs, filtered_songs
def get_suggested_filename(metadata): """Generate a filename for a song based on metadata. Parameters: metadata (dict): A metadata dict. Returns: A filename. """ if metadata.get('title') and metadata.get('track_number'): suggested_filename = '{track_number:0>2} {title}'.format(**metadata) elif metadata.get('title') and metadata.get('trackNumber'): suggested_filename = '{trackNumber:0>2} {title}'.format(**metadata) elif metadata.get('title') and metadata.get('tracknumber'): suggested_filename = '{tracknumber:0>2} {title}'.format(**metadata) else: suggested_filename = '00 {}'.format(metadata.get('title', '')) return suggested_filename
def template_to_filepath(template, metadata, template_patterns=None): """Create directory structure and file name based on metadata template. Parameters: template (str): A filepath which can include template patterns as defined by :param template_patterns:. metadata (dict): A metadata dict. template_patterns (dict): A dict of ``pattern: field`` pairs used to replace patterns with metadata field values. Default: :const TEMPLATE_PATTERNS: Returns: A filepath. """ if template_patterns is None: template_patterns = TEMPLATE_PATTERNS metadata = metadata if isinstance(metadata, dict) else _mutagen_fields_to_single_value(metadata) assert isinstance(metadata, dict) suggested_filename = get_suggested_filename(metadata).replace('.mp3', '') if template == os.getcwd() or template == '%suggested%': filepath = suggested_filename else: t = template.replace('%suggested%', suggested_filename) filepath = _replace_template_patterns(t, metadata, template_patterns) return filepath
def walk_depth(path, max_depth=float('inf')): """Walk a directory tree with configurable depth. Parameters: path (str): A directory path to walk. max_depth (int): The depth in the directory tree to walk. A depth of '0' limits the walk to the top directory. Default: No limit. """ start_level = os.path.abspath(path).count(os.path.sep) for dir_entry in os.walk(path): root, dirs, _ = dir_entry level = root.count(os.path.sep) - start_level yield dir_entry if level >= max_depth: dirs[:] = []
def get_local_songs( filepaths, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False, exclude_patterns=None, max_depth=float('inf')): """Load songs from local filepaths. Parameters: filepaths (list or str): Filepath(s) to search for music files. include_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid mutagen metadata fields. Patterns are Python regex patterns. Local songs are filtered out if the given metadata field values don't match any of the given patterns. exclude_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid mutagen metadata fields. Patterns are Python regex patterns. Local songs are filtered out if the given metadata field values match any of the given patterns. all_includes (bool): If ``True``, all include_filters criteria must match to include a song. all_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song. exclude_patterns (list or str): Pattern(s) to exclude. Patterns are Python regex patterns. Filepaths are excluded if they match any of the exclude patterns. max_depth (int): The depth in the directory tree to walk. A depth of '0' limits the walk to the top directory. Default: No limit. Returns: A list of local song filepaths matching criteria, a list of local song filepaths filtered out using filter criteria, and a list of local song filepaths excluded using exclusion criteria. """ logger.info("Loading local songs...") supported_filepaths = get_supported_filepaths(filepaths, SUPPORTED_SONG_FORMATS, max_depth=max_depth) included_songs, excluded_songs = exclude_filepaths(supported_filepaths, exclude_patterns=exclude_patterns) matched_songs, filtered_songs = filter_local_songs( included_songs, include_filters=include_filters, exclude_filters=exclude_filters, all_includes=all_includes, all_excludes=all_excludes ) logger.info("Excluded {0} local songs".format(len(excluded_songs))) logger.info("Filtered {0} local songs".format(len(filtered_songs))) logger.info("Loaded {0} local songs".format(len(matched_songs))) return matched_songs, filtered_songs, excluded_songs