def alert(i, group_id, id, notify) : print("######### Match found at {0}th post! Link: {1} ###########".format(i, text)) if not notify : return item = "org.freedesktop.Notifications" path = "/org/freedesktop/Notifications" interface = "org.freedesktop.Notifications" app_name = "Marketplace Notification" v = QtCore.QVariant(91424) if v.convert(QtCore.QVariant.UInt): id_replace = v icon = "" title = "Match found in marketplace!" text = "https://www.facebook.com/groups/{0}/permalink/{1}".format(group_id, id) actions_list = QtDBus.QDBusArgument([], QtCore.QMetaType.QStringList) hint = {} time = 7000 # milliseconds for display timeout bus = QtDBus.QDBusConnection.sessionBus() if not bus.isConnected(): print("Not connected to dbus!") notify = QtDBus.QDBusInterface(item, path, interface, bus) if notify.isValid(): x = notify.call(QtDBus.QDBus.AutoDetect, "Notify", app_name, id_replace, icon, title, text, actions_list, hint, time) if x.errorName(): print("Failed to send notification!") print(x.errorMessage()) else: print("Invalid dbus interface")
def _dbus_notify(self, header, msg, level='info'): item = "org.freedesktop.Notifications" path = "/org/freedesktop/Notifications" interface = "org.freedesktop.Notifications" app_name = "vorta" v = QtCore.QVariant(12321) # random int to identify all notifications if v.convert(QtCore.QVariant.UInt): id_replace = v icon = "" title = header text = msg actions_list = QtDBus.QDBusArgument([], QtCore.QMetaType.QStringList) hint = {'urgency': self.URGENCY[level]} time = 5000 # milliseconds for display timeout bus = QtDBus.QDBusConnection.sessionBus() notify = QtDBus.QDBusInterface(item, path, interface, bus) if notify.isValid(): x = notify.call(QtDBus.QDBus.AutoDetect, "Notify", app_name, id_replace, icon, title, text, actions_list, hint, time) if x.errorName(): logger.warning("Failed to send notification!") logger.warning(x.errorMessage()) else: logger.warning("Invalid dbus interface")
def __init__(self, config): self.__config: ConfigManager = ConfigManager(config) self.__yakuake = Yakuake( sessions=QtDBus.QDBusInterface("org.kde.yakuake", "/yakuake/sessions", "org.kde.yakuake"), tabs=QtDBus.QDBusInterface("org.kde.yakuake", "/yakuake/tabs", "org.kde.yakuake"), window=QtDBus.QDBusInterface("org.kde.yakuake", "/yakuake/window", "org.kde.yakuake"))
def export_objects(): app = QtWidgets.qApp app.setApplicationVersion("0.4.1") app.setOrganizationName("Youdao") app.setApplicationName("Youdao Dict") # set default font defaultFont = QtGui.QFont() defaultFont.setPointSize(11) app.setFont(defaultFont) if not session_bus.registerService(DBUS_NAME): print("Service is running: %s" % DBUS_NAME) iface = QtDBus.QDBusInterface(DBUS_NAME, DBUS_PATH, DBUS_INTERFACE, session_bus) iface.call("Raise") sys.exit(0) else: unique_obj = UniqueService() session_bus.registerObject(DBUS_PATH, unique_obj) print("Youdao Dict Unique Service is started...") youdao_api = ExternalApi() splash_window = SplashWindow(youdao_api) if not "--autostart" in sys.argv and not setting_config.get_basic_option( "start_mini"): splash_window.showCenter() splash_window.startTimer() indicator = YoudaoIndicator() return [ dict(name=unique_obj.name, obj=unique_obj), dict(name="indicator", obj=indicator), dict(name="splash_window", obj=splash_window), dict(name=youdao_api.name, obj=youdao_api), dict(name="config", obj=setting_config), ]
def exportshow_done(self, call): reply = QtDBus.QDBusPendingReply(call) if reply.isError(): self.show_status.emit(False, "DBUS error:" + str(reply.error().message())) else: ts_ = (reply.argumentAt(0).toPyObject()[0].toULongLong()[0], reply.argumentAt(0).toPyObject()[1].toULongLong()[0]) exports = [] for export in reply.argumentAt(1).toPyObject(): ex = export.toPyObject() lasttime = ex[10].toPyObject() exp = Export(ExportID=ex[0].toInt()[0], ExportPath=str(ex[1].toString()), HasNFSv3=ex[2].toBool(), HasMNT=ex[3].toBool(), HasNLM4=ex[4].toBool(), HasRQUOTA=ex[5].toBool(), HasNFSv40=ex[6].toBool(), HasNFSv41=ex[7].toBool(), HasNFSv42=ex[8].toBool(), Has9P=ex[9].toBool(), LastTime=(lasttime[0].toPyObject(), lasttime[1].toPyObject())) exports.append(exp) self.show_exports.emit(ts_, exports)
def notify(self, message, actions=[]): '''Display a notification. @message, string @actions, a list of actions ''' varRPlaceId = QtCore.QVariant(0) varRPlaceId.convert(QtCore.QVariant.UInt) varActions = QtCore.QVariant(actions) varActions.convert(QtCore.QVariant.StringList) msg = self.call( 'Notify', # `Notify` method _(constants.APP_NAME), # app name varRPlaceId, # replaces_id constants.ICON_NAME, # app icon _(constants.APP_NAME), # summary message, # message body varActions, # actions {}, # hints -1 # expire timeout, default is -1 ) reply = QtDBus.QDBusReply(msg) if reply.isValid(): return reply.value() else: return None
def exportrm_done(self, call): reply = QtDBus.QDBusPendingReply(call) if reply.isError(): self.show_status.emit(False, "Error:" + str(reply.error().message())) else: self.show_status.emit(True, "Done")
def read_dbus_property(obj, property): # QDBusInterface.property() didn't work for some reason props = QtDBus.QDBusInterface(obj.service(), obj.path(), 'org.freedesktop.DBus.Properties', obj.connection()) msg = props.call('Get', obj.interface(), property) return get_result(msg)
def exportadd_done(self, call): reply = QtDBus.QDBusPendingReply(call) if reply.isError(): self.show_status.emit(False, "Error:" + str(reply.error().message())) else: message = reply.argumentAt(0).toPyObject() self.show_status.emit(True, "Done: " + message)
def Get_done(self, call): reply = QtDBus.QDBusPendingReply(call) if reply.isError(): self.show_status.emit(False, "DBUS error:" + str(reply.error().message())) else: level = str(reply.value().toPyObject().toString()) self.show_level.emit(level)
def call_dbus(method, *args): result = self.iface.call(method, *args) reply = QtDBus.QDBusReply(result) assert reply.isValid(), 'Dbus reply was not valid: {}'.format( bus_connection.lastError().message()) LOGGER.debug("Called dbus %s: returned %s (%s)", method, reply.value(), type(reply.value())) # return the whole value return reply.value()
def __init__(self): """ Test whether DBus and KDEWallet are available. """ self.iface = QtDBus.QDBusInterface(self.service_name, self.object_path, self.interface_name, QtDBus.QDBusConnection.sessionBus()) if not (self.iface.isValid() and self.get_result("isEnabled")): raise KWalletNotAvailableException
def admin_done(self, call): reply = QtDBus.QDBusPendingReply(call) if reply.isError(): self.show_status.emit(False, "DBUS error:" + str(reply.error().message())) else: status = reply.argumentAt(0).toPyObject() msg = reply.argumentAt(1).toPyObject() self.show_status.emit(status, msg)
def exportdisplay_done(self, call): reply = QtDBus.QDBusPendingReply(call) if reply.isError(): self.show_status.emit(False, "Error:" + str(reply.error().message())) else: id_ = reply.argumentAt(0).toPyObject() fullpath = reply.argumentAt(1).toPyObject() pseudopath = reply.argumentAt(2).toPyObject() tag = reply.argumentAt(3).toPyObject() self.display_export.emit(id_, fullpath, pseudopath, tag)
def set_conn_result(self, connection_id, save_option, verdict, apply_to_all): msg = self.app.dbus_handler.interface.call( 'connection_set_result', connection_id, RuleSaveOption(save_option).value, RuleVerdict(verdict).value, apply_to_all) reply = QtDBus.QDBusReply(msg) if not reply.isValid(): logging.info('Could not apply result to connection "%s"', connection_id) logging.error(msg.arguments()[0])
def _notify(self, header, msg): if self._is_windows(): return False item = "org.freedesktop.Notifications" path = "/org/freedesktop/Notifications" interface = "org.freedesktop.Notifications" app_name = "pomito" v = QtCore.QVariant(100021) # random int to identify all notifications if v.convert(QtCore.QVariant.UInt): id_replace = v icon = "" title = header text = msg actions_list = QtDBus.QDBusArgument([], QtCore.QMetaType.QStringList) hint = {} time = 100 # milliseconds for display timeout bus = QtDBus.QDBusConnection.sessionBus() if not bus.isConnected(): logger.debug("Not connected to dbus!") return False notify = QtDBus.QDBusInterface(item, path, interface, bus) if notify.isValid(): x = notify.call(QtDBus.QDBus.AutoDetect, "Notify", app_name, id_replace, icon, title, text, actions_list, hint, time) if x.errorName(): logger.debug("Failed to send notification!") logger.debug(x.errorMessage()) return False else: logger.debug("Invalid dbus interface") return False return True
def send_notification(): global app_name global notification_id global saved_due_card_count due_card_count = len(mw.col.find_cards("is:new or is:due")) to_notify = due_card_count > saved_due_card_count saved_due_card_count = due_card_count if not to_notify: return short_app_name = "Anki" qt_notification_id = QtCore.QVariant(notification_id) qt_notification_id.convert(QtCore.QVariant.UInt) icon = app_name title = "Anki" text = str(due_card_count) + (" card" if due_card_count == 1 else " cards") + " to study" actions_list = QtDBus.QDBusArgument([], QtCore.QMetaType.QStringList) hint = {} time = -1 item = "org.freedesktop.Notifications" path = "/org/freedesktop/Notifications" interface = "org.freedesktop.Notifications" bus = QtDBus.QDBusConnection.sessionBus() if not bus.isConnected(): print("Not connected to dbus!") notify = QtDBus.QDBusInterface(item, path, interface, bus) if notify.isValid(): msg = notify.call(QtDBus.QDBus.AutoDetect, "Notify", short_app_name, qt_notification_id, icon, title, text, actions_list, hint, time) if msg.errorName(): print("Failed to send notification!") print(msg.errorMessage()) notification_id = msg.arguments()[0] else: print("Invalid dbus interface!")
def handle_connection(self): # This method will get called again after the user took action # on the currently handled connection if self.connection is not None: return try: connection = self.connection_queue.get_nowait() except queue.Empty: return # Check if process is still alive, if not we dont need to handle if connection.app_pid: try: os.kill(connection.app_pid, 0) except ProcessLookupError: return # Re-check in case permanent rule was added since connection was queued verd = False with self.rule_lock: msg = self.app.dbus_handler.interface.call( 'connection_recheck_verdict', connection.id) reply = QtDBus.QDBusReply(msg) if reply.isValid() and reply.value(): verd = True elif not reply.isValid(): logging.error(msg.arguments()[0]) # Lock needs to be released before callback can be triggered if verd: return self.add_connection_signal.emit() self.connection = connection if connection.app_path is not None: app_name, app_icon = self.desktop_parser.get_info_by_path( connection.app_path) else: app_name = 'Unknown' app_icon = None self.setup_labels(app_name) self.setup_icon(app_icon) self.setup_extra() self.result = Dialog.DEFAULT_RESULT self.action_combo_box.setCurrentIndex(0) self.show()
def __init__(self, url, width, height, open_url=None, stop_on_inactive=True, allow_screensaver=True, auto_restart_playback=False): super().__init__(None) self.url = url self.open_url = open_url self.auto_restart_playback_active = False self.dbus = QtDBus.QDBusConnection.systemBus() self.dbus_login_manager = QtDBus.QDBusInterface( "org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", self.dbus) self.dbus.connect("org.freedesktop.login1", "/org/freedesktop/login1/seat/seat0", "org.freedesktop.DBus.Properties", "PropertiesChanged", self.login_seat_changed) self.vlc_instance = vlc.Instance( "--no-disable-screensaver" if allow_screensaver else "") self.setFixedSize(QtCore.QSize(width, height)) self.media_player = None self.screensaver_state = False if auto_restart_playback: self.update_timer = QtCore.QTimer(self) self.update_timer.timeout.connect( self.update_auto_restart_playback) self.update_timer.start(1000) if stop_on_inactive: self.visibility_changed.connect(self.update_state_by_visibility) get_dashboard_instance().window_state_changed.connect( self.update_state_by_visibility) get_dashboard_instance().screensaver_state_changed.connect( self.screensaver_state_changed) else: self.play()
def GetAll_done(self, call): reply = QtDBus.QDBusPendingReply(call) if reply.isError(): self.show_status.emit(False, "DBus error:" + str(reply.error().message())) else: # what follows is DBus+Qt magic. We get a Variant object back # which contains a "map", aka "dict" in python. Each item in # the map has a variant as a key and a variant as the value # first unwrap the top variant into d... # then walk d, unwrap the variant key to store the unwrapped # variant value into a string value. prop_dict = {} d = reply.value().toPyObject() for key in d.keys(): prop_dict[str(key.toString())] = str(d[key].toPyObject().toString()) self.show_components.emit(prop_dict)
def initGui(self): self.setWindowTitle("Anna") self.setFrameStyle(widget.QFrame.NoFrame) self.setStyleSheet("background-color: transparent") self.setAttribute(core.Qt.WA_TranslucentBackground) self.pen = gui.QPen() self.pen.setWidth(3) self.pen.setColor(gui.QColor(255, 0, 0)) self.gs = widget.QGraphicsScene() self.setScene(self.gs) f = getattr(self.args, 'from') if f: reader = gui.QImageReader(f) reader.setAutoTransform(True) self.pixmap = gui.QPixmap.fromImage(reader.read()) if self.pixmap.isNull(): print('image read failed') else: self.gs.addPixmap(self.pixmap) pw, ph = self.pixmap.size().width(), \ self.pixmap.size().height() self.setGeometry(0, 0, pw, ph) self.setSceneRect(0, 0, pw, ph) else: self.setWindowFlags(core.Qt.X11BypassWindowManagerHint) rect = widget.QApplication.desktop().screenGeometry() self.setGeometry(rect) self.setSceneRect(core.QRectF(rect)) self.showFullScreen() self.mkIndicator() self.gs.addItem(self.ind) if dbus: self.interface = dbus.QDBusInterface("org.kde.KWin", "/Effects") resp = self.interface.call("Get", "org.kde.kwin.Effects", "activeEffects") if resp.type() == 2: if "diminactive" in resp.arguments()[0]: self.interface.call("unloadEffect", "diminactive") self.restore = True
def __init__(self, app, parent): self.parent = parent self.app = app super().__init__(app) self.__dbus = QtDBus.QDBusConnection.sessionBus() self.__dbus.registerObject('/', self) self.interface = QtDBus.QDBusInterface('io.opensnitch.service', '/', 'io.opensnitch.service', self.__dbus) if not self.interface.isValid(): raise RuntimeError('Could not connect to dbus') logging.info('Connected to dbus service') sig_connect = self.__dbus.connect('io.opensnitch.service', '/', 'io.opensnitch.service', 'prompt', self.prompt_user) if not sig_connect: raise RuntimeError('Could not connect dbus signal') logging.info('Connected dbus signal')
def __init__(self, url, width=None, height=None, stop_on_inactive=True, auto_restart_playback=False): super().__init__() self.url = url self.screensaver_state = False self.playing = False self.dbus = QtDBus.QDBusConnection.systemBus() self.dbus_login_manager = QtDBus.QDBusInterface( "org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", self.dbus) self.dbus.connect("org.freedesktop.login1", "/org/freedesktop/login1/seat/seat0", "org.freedesktop.DBus.Properties", "PropertiesChanged", self.login_seat_changed) if width and height: self.setFixedSize(QtCore.QSize(width, height)) self.player = QtMultimedia.QMediaPlayer(self) self.player.setVideoOutput(self) if auto_restart_playback: self.player.stateChanged.connect(self.state_changed) if stop_on_inactive: self.visibility_changed.connect(self.update_state_by_visibility) get_dashboard_instance().window_state_changed.connect( self.update_state_by_visibility) get_dashboard_instance().screensaver_state_changed.connect( self.screensaver_state_changed) else: self.play()
def __init__(self, name, path, interface, prevent_sleep_fn, allow_sleep_fn): super(DBusInhibitor, self).__init__() self.interface_name = interface self.insomnia_cookie = None bus_connection = QtDBus.QDBusConnection.sessionBus() assert bus_connection.isConnected(), 'Dbus is not connected' self.iface = QtDBus.QDBusInterface(name, path, interface, bus_connection) if self.iface.isValid(): LOGGER.debug('Registered to the DBus service: %s', name) else: LOGGER.debug('Failed to register DBus service object: %s', name) def call_dbus(method, *args): result = self.iface.call(method, *args) reply = QtDBus.QDBusReply(result) assert reply.isValid(), 'Dbus reply was not valid: {}'.format( bus_connection.lastError().message()) LOGGER.debug("Called dbus %s: returned %s (%s)", method, reply.value(), type(reply.value())) # return the whole value return reply.value() def inhibit(*args): # returns a QDBusMessage class return call_dbus(prevent_sleep_fn, *args) def uninhibit(*args): return call_dbus(allow_sleep_fn, *args) # Check we have the right attributes self._inhibit = inhibit self._uninhibit = uninhibit
def _get_iface(self, path, interface) -> QtDBus.QDBusInterface: return QtDBus.QDBusInterface(self.BUS_NAME, path, interface, self._bus)
def shutdown(self): _async = self.asyncCall("shutdown") status = QtDBus.QDBusPendingCallWatcher(_async, self) status.finished.connect(self.admin_done)
def reload(self): _async = self.asyncCall("reload") status = QtDBus.QDBusPendingCallWatcher(_async, self) status.finished.connect(self.admin_done)
def get_dbus_interface(self, service, interface): return QtDBus.QDBusInterface(service, "/org/mpris/MediaPlayer2", interface, self.bus)
def grace(self, ipaddr): _async = self.asyncCall("grace", ipaddr) status = QtDBus.QDBusPendingCallWatcher(_async, self) status.finished.connect(self.admin_done)
def Set(self, prop, setval): qval = QtDBus.QDBusVariant() qval.setVariant(str(str(setval))) _async = self.asyncCall("Set", LOGGER_PROPS, prop, qval) status = QtDBus.QDBusPendingCallWatcher(_async, self) status.finished.connect(self.Set_done)