class LogView(QObject): def __init__(self, app, logpath, id, sdk_model, row_number): QObject.__init__(self) self.app = app self.logpath = logpath self.window = QMainWindow() self.window.setWindowTitle("Raptor build viewer") self.build_list = BuildListModel(self.logpath) self.controller = BuildController(app, self.build_list, id, sdk_model, row_number) self.view = QDeclarativeView() self.glw = QtOpenGL.QGLWidget() self.view.setViewport(self.glw) self.view.setResizeMode(QtDeclarative.QDeclarativeView.SizeRootObjectToView) self.window.setCentralWidget(self.view) self.rc = self.view.rootContext() self.rc.setContextProperty('controller', self.controller) self.rc.setContextProperty('pyBuildListModel', self.build_list) self.rc.setContextProperty('logpath', self.logpath) self.rc.setContextProperty('info', sdk_model.sdk_info(id)) self.rc.setContextProperty('window', self.window) self.rc.setContextProperty('row', row_number) self.view.setSource('logchooser.qml') self.window.show() def checked(self): for build in self.build_list.checked(): yield build
class DiffView(QObject): def __init__(self, app, difftext, leftfile, rightfile): QObject.__init__(self) self.app = app self.difftext = difftext self.window = QMainWindow() self.window.setWindowTitle("Log Diffs") self.leftfile = leftfile self.rightfile = rightfile self.view = QDeclarativeView() self.glw = QtOpenGL.QGLWidget() self.view.setViewport(self.glw) self.view.setResizeMode( QtDeclarative.QDeclarativeView.SizeRootObjectToView) self.window.setCentralWidget(self.view) self.rc = self.view.rootContext() self.rc.setContextProperty('controller', self) self.rc.setContextProperty('difftext', self.difftext) self.view.setSource('diffview.qml') self.window.show() @Slot() def diff_viewer(self): p = subprocess.Popen("gvim -d {0} {1}".format(self.leftfile, self.rightfile), shell=True) sts = os.waitpid(p.pid, 0)[1] def checked(self): for build in self.build_list.checked(): yield build
class DiffView(QObject): def __init__(self, app, difftext, leftfile, rightfile): QObject.__init__(self) self.app = app self.difftext = difftext self.window = QMainWindow() self.window.setWindowTitle("Log Diffs") self.leftfile = leftfile self.rightfile = rightfile self.view = QDeclarativeView() self.glw = QtOpenGL.QGLWidget() self.view.setViewport(self.glw) self.view.setResizeMode(QtDeclarative.QDeclarativeView.SizeRootObjectToView) self.window.setCentralWidget(self.view) self.rc = self.view.rootContext() self.rc.setContextProperty('controller', self) self.rc.setContextProperty('difftext', self.difftext) self.view.setSource('diffview.qml') self.window.show() @Slot() def diff_viewer(self): p = subprocess.Popen("gvim -d {0} {1}".format(self.leftfile, self.rightfile), shell=True) sts = os.waitpid(p.pid, 0)[1] def checked(self): for build in self.build_list.checked(): yield build
class OverlayWidget(QtGui.QWidget): def __init__(self, *args): super(OverlayWidget, self).__init__(*args) # Set this widget itself to be transparent self.setAttribute(QtCore.Qt.WA_TranslucentBackground) # We need to set the base colour of the qml widget to be transparent. # This is done by setting its palette. palette = QtGui.QPalette() palette.setColor(QtGui.QPalette.Base, QtCore.Qt.transparent) self.setPalette(palette) self.qml_view = QDeclarativeView(self) self.qml_view.setResizeMode(QDeclarativeView.SizeRootObjectToView) self.qml_view.setPalette(palette) self.qml_view.setResizeMode(QDeclarativeView.SizeRootObjectToView) url = QUrl('dynamic_drawers.qml') self.qml_view.setSource(url) def resizeEvent(self, event): self.qml_view.resize(event.size())
class LogView(QObject): def __init__(self, app, logpath, id, sdk_model, row_number): QObject.__init__(self) self.app = app self.logpath = logpath self.window = QMainWindow() self.window.setWindowTitle("Raptor build viewer") self.build_list = BuildListModel(self.logpath) self.controller = BuildController(app, self.build_list, id, sdk_model, row_number) self.view = QDeclarativeView() self.glw = QtOpenGL.QGLWidget() self.view.setViewport(self.glw) self.view.setResizeMode( QtDeclarative.QDeclarativeView.SizeRootObjectToView) self.window.setCentralWidget(self.view) self.rc = self.view.rootContext() self.rc.setContextProperty('controller', self.controller) self.rc.setContextProperty('pyBuildListModel', self.build_list) self.rc.setContextProperty('logpath', self.logpath) self.rc.setContextProperty('info', sdk_model.sdk_info(id)) self.rc.setContextProperty('window', self.window) self.rc.setContextProperty('row', row_number) self.view.setSource('logchooser.qml') self.window.show() def checked(self): for build in self.build_list.checked(): yield build
def main(argv): app = QApplication(argv) display_widget = QDeclarativeView() display_widget.setViewport(QGLWidget()) display_widget.setResizeMode(QDeclarativeView.SizeRootObjectToView) display_widget.setSource(QUrl('drawer_demo.qml')) display_widget.show() display_widget.resize(640,480) sys.exit(app.exec_())
def main(argv): app = QApplication(argv) display_widget = QDeclarativeView() display_widget.setViewport(QGLWidget()) display_widget.setResizeMode(QDeclarativeView.SizeRootObjectToView) display_widget.setSource(QUrl('drawer_demo.qml')) display_widget.show() display_widget.resize(640, 480) sys.exit(app.exec_())
def main(): QApplication.setOrganizationName('OpenBossa') QApplication.setApplicationName('mobtrans') QApplication.setGraphicsSystem('raster') app = QApplication([]) serverConfig = ServerConfig() server = Server(serverConfig) model = TorrentModel(server) searchModel = SearchModel() view = QDeclarativeView() #view.setMinimumSize(800, 600) view.setResizeMode(QDeclarativeView.SizeRootObjectToView) view.rootContext().setContextProperty('server', server) view.rootContext().setContextProperty('torrentModel', model) view.rootContext().setContextProperty('searchModel', searchModel) view.setSource(QUrl.fromLocalFile('./qml/main.qml')) view.show() app.exec_()
class SDKView(QObject): def __init__(self, app, window, logpath=None): QObject.__init__(self) self.app = app self.sdk_list_model = SDKListModel() self.controller = SDKController(app, self.sdk_list_model) self.view = QDeclarativeView() self.glw = QtOpenGL.QGLWidget() self.view.setViewport(self.glw) self.view.setResizeMode(QtDeclarative.QDeclarativeView.SizeRootObjectToView) window.setCentralWidget(self.view) self.rc = self.view.rootContext() self.rc.setContextProperty('sdk_controller', self.controller) self.rc.setContextProperty('pySDKListModel', self.sdk_list_model) self.view.setSource('sdkchooser.qml') @Slot() def quit(self): self.controller.quit()
class SDKView(QObject): def __init__(self, app, window, logpath=None): QObject.__init__(self) self.app = app self.sdk_list_model = SDKListModel() self.controller = SDKController(app, self.sdk_list_model) self.view = QDeclarativeView() self.glw = QtOpenGL.QGLWidget() self.view.setViewport(self.glw) self.view.setResizeMode( QtDeclarative.QDeclarativeView.SizeRootObjectToView) window.setCentralWidget(self.view) self.rc = self.view.rootContext() self.rc.setContextProperty('sdk_controller', self.controller) self.rc.setContextProperty('pySDKListModel', self.sdk_list_model) self.view.setSource('sdkchooser.qml') @Slot() def quit(self): self.controller.quit()
class QtControl(Thread): def __init__(self, gs): super(QtControl, self).__init__() self.gs = gs self.cmd=Commands(gs) self.results=ResultsModel(self.gs.best_times['_']) def get_results(self): # self.ctxt.setContextProperty("resutlts", [['<b>{0: >4}.</b> {2} [<font align="right" color="grey">{1:.2f}</font>]'.format(i, t[0], t[1]['name']) # for i,t in enumerate(self.gs.best_times[s],1)] # for s in self.gs.sets]) self.ctxt.setContextProperty("results", self.results) def run(self): self.app=QApplication([]) self.view=QDeclarativeView() self.view.setResizeMode(QDeclarativeView.SizeRootObjectToView) self.ctxt = self.view.rootContext() # setting context properities self.ctxt.setContextProperty("sets", self.gs.sets) self.ctxt.setContextProperty("cmd", self.cmd) self.ctxt.setContextProperty("dist", self.gs.dist) self.ctxt.setContextProperty("results", self.results) self.view.setSource(QUrl(os.path.join(BASE_QML_PATH, 'view_n900.qml'))) self.root=self.view.rootObject() # connecting signals self.gs.out.qiface.update_race.connect(self.root.update_race) self.gs.out.qiface.start.connect(self.root.start) self.gs.out.qiface.abort.connect(self.root.abort) self.gs.out.qiface.finish.connect(self.root.finish) self.gs.out.qiface.finish.connect(self.get_results) self.gs.out.qiface.new_race.connect(self.root.new_race) self.view.show() self.app.exec_()
class QtControl(Thread): def __init__(self, gs): super(QtControl, self).__init__() self.gs = gs self.cmd = Commands(gs) self.results = ResultsModel(self.gs.best_times['_']) def get_results(self): # self.ctxt.setContextProperty("resutlts", [['<b>{0: >4}.</b> {2} [<font align="right" color="grey">{1:.2f}</font>]'.format(i, t[0], t[1]['name']) # for i,t in enumerate(self.gs.best_times[s],1)] # for s in self.gs.sets]) self.ctxt.setContextProperty("results", self.results) def run(self): self.app = QApplication([]) self.view = QDeclarativeView() self.view.setResizeMode(QDeclarativeView.SizeRootObjectToView) self.ctxt = self.view.rootContext() # setting context properities self.ctxt.setContextProperty("sets", self.gs.sets) self.ctxt.setContextProperty("cmd", self.cmd) self.ctxt.setContextProperty("dist", self.gs.dist) self.ctxt.setContextProperty("results", self.results) self.view.setSource(QUrl(os.path.join(BASE_QML_PATH, 'view_n900.qml'))) self.root = self.view.rootObject() # connecting signals self.gs.out.qiface.update_race.connect(self.root.update_race) self.gs.out.qiface.start.connect(self.root.start) self.gs.out.qiface.abort.connect(self.root.abort) self.gs.out.qiface.finish.connect(self.root.finish) self.gs.out.qiface.finish.connect(self.get_results) self.gs.out.qiface.new_race.connect(self.root.new_race) self.view.show() self.app.exec_()
class OverlayWidget(QtGui.QWidget): def __init__(self, *args): super(OverlayWidget, self).__init__(*args) # Set this widget itself to be transparent self.setAttribute(QtCore.Qt.WA_TranslucentBackground) # We need to set the base colour of the qml widget to be transparent. # This is done by setting its palette. palette = QtGui.QPalette() palette.setColor(QtGui.QPalette.Base, QtCore.Qt.transparent) self.setPalette(palette) self.qml_view = QDeclarativeView(self) self.qml_view.setResizeMode(QDeclarativeView.SizeRootObjectToView) self.qml_view.setPalette(palette) url = QUrl('drawer_demo.qml') self.qml_view.setSource(url) def resizeEvent(self, event): self.qml_view.resize(event.size())
class QtClient: host = "localhost" port = 9998 ctxt = '' class Commands(QObject, Thread): finish = Signal() daemon = True def __init__(self, host, port): Thread.__init__(self) QObject.__init__(self) self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.connect((host, port)) self.socket.settimeout(.5) self.setDaemon(True) def run(self): print 'running' while 1: try: data = self.socket.recv(400) if data: print data if data.startswith('finish'): self.finish.emit() except socket.error: sleep(3) except KeyboardInterrupt: sys.exit() @Slot(str, str, str, str, result=str) def new_race(self, *args): self.socket.send('new_race("%s","%s","%s","%s")\n' % (args)) @Slot() def swap(self): self.socket.send('swap\n') @Slot() def start_race(self): self.socket.send('start\n') @Slot() def abort(self): self.socket.send('abort\n') @Slot(str, int, int) def show_results(self, *args): try: self.socket.recv(4096) except socket.error: pass self.socket.send('show_results %s %s %s\n' % (args)) results = '' while 1: try: results += self.socket.recv(4096) except socket.error: break results = results.splitlines()[1:-1] self.ctxt.setContextProperty('results', results) @Slot() def sponsors(self): self.socket.send("sponsors\n") @Slot() def init_bt(self): self.socket.send("init_bt\n") @Slot(str) def set_dist(self, *args): self.socket.send('set_dist("%s")\n' % (args)) def __init__(self, host, port): self.host = host or self.host self.port = port or self.port def connect(self): self.cmd = self.Commands(self.host, self.port) self.cmd.start() def get_results(self): pass def show(self, qml_file): self.app = QApplication([]) self.view = QDeclarativeView() self.view.setResizeMode(QDeclarativeView.SizeRootObjectToView) self.view.setSource(QUrl(qml_file)) self.ctxt = self.view.rootContext() self.cmd.ctxt = self.ctxt self.ctxt.setContextProperty("cmd", self.cmd) self.cmd.finish.connect(self.view.rootObject().finish) #self.ctxt.setContextProperty("dist", self.cmd.abort()) self.view.show() self.app.exec_()
class QtClient: host="localhost" port=9998 ctxt='' class Commands(QObject, Thread): finish = Signal() daemon = True def __init__(self, host, port): Thread.__init__(self) QObject.__init__(self) self.socket=socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.connect((host,port)) self.socket.settimeout(.5) self.setDaemon(True) def run(self): print 'running' while 1: try: data = self.socket.recv(400) if data: print data if data.startswith('finish'): self.finish.emit() except socket.error: sleep(3) except KeyboardInterrupt: sys.exit() @Slot(str, str, str, str, result=str) def new_race(self, *args): self.socket.send('new_race("%s","%s","%s","%s")\n' % (args)) @Slot() def swap(self): self.socket.send('swap\n') @Slot() def start_race(self): self.socket.send('start\n') @Slot() def abort(self): self.socket.send('abort\n') @Slot(str,int,int) def show_results(self, *args): try: self.socket.recv(4096) except socket.error: pass self.socket.send('show_results %s %s %s\n' % (args)) results='' while 1: try: results+=self.socket.recv(4096) except socket.error: break results=results.splitlines()[1:-1] self.ctxt.setContextProperty('results', results) @Slot() def sponsors(self): self.socket.send("sponsors\n") @Slot() def init_bt(self): self.socket.send("init_bt\n") @Slot(str) def set_dist(self, *args): self.socket.send('set_dist("%s")\n' %(args)) def __init__(self, host, port): self.host=host or self.host self.port=port or self.port def connect(self): self.cmd = self.Commands(self.host, self.port) self.cmd.start() def get_results(self): pass def show(self,qml_file): self.app=QApplication([]) self.view=QDeclarativeView() self.view.setResizeMode(QDeclarativeView.SizeRootObjectToView) self.view.setSource(QUrl(qml_file)) self.ctxt = self.view.rootContext() self.cmd.ctxt = self.ctxt self.ctxt.setContextProperty("cmd", self.cmd) self.cmd.finish.connect(self.view.rootObject().finish) #self.ctxt.setContextProperty("dist", self.cmd.abort()) self.view.show() self.app.exec_()
# -*- coding: utf-8 -*- """ Created on Wed Nov 26 12:19:44 2014 @author: ngordon """ import sys from PySide.QtCore import * from PySide.QtGui import * from PySide.QtDeclarative import QDeclarativeView # Create Qt Aplication and the QDeclarative view app = QApplication(sys.argv) view = QDeclarativeView() # Create an URL to the QML file url = QUrl('view.qml') #set the qml and show view.setSource(url) # resizes the red when the window size is changed view.setResizeMode(QDeclarativeView.SizeRootObjectToView) view.show() #Enter Qt main loop sys.exit(app.exec_())
@QtCore.Slot(QtCore.QObject) def elementSelected(self, elementWrapper): element = elementWrapper._name self._elementData._new_element(element) elementList = ElementList(element_datalist.get_sorted_element_list()) eelsEdgeList = EELSEdgeList() edsLineList = EDSLineList() elementName = ElementName() elementData = ElementData(eelsEdgeList, edsLineList, elementName) controller = Controller(elementData) app = QtGui.QApplication(sys.argv) view = QDeclarativeView() view.setResizeMode(QDeclarativeView.SizeRootObjectToView) rootObject = view.rootObject() rootContext = view.rootContext() rootContext.setContextProperty('elementList', elementList) rootContext.setContextProperty('eelsEdgeList', eelsEdgeList) rootContext.setContextProperty('edsLineList', edsLineList) rootContext.setContextProperty('controller', controller) rootContext.setContextProperty('elementName', elementName) #"debugging" mode to run without the N9 specific QML if options.desktop: if options.landscape: view.setSource(QtCore.QUrl('qml/Eels_edx_lookup_landscape.qml'))
class MainWindow(QObject): ################################################ # validations ################################################ def validate_email(self, string): if len(string) > 7: if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", string) != None: return True return False def validate_fields(self): if self.curVars.user_name == '': self.rootO.show_alert("Empty name!", "Please type in your name.",False) return False if self.validate_email(self.curVars.email) == False: self.rootO.show_alert("Invalid email", "Please make sure the email address you typed is valid.",False) return False if len(self.curVars.password) < 6: self.rootO.show_alert("Bad password", "Password should contain at least 6 chars. Please try again.",False) return False elif self.curVars.password != self.curVars.password_confirm: self.rootO.show_alert("Passwords don't match", "Please make sure both passwords match!",False) return False return True ################################################ # setting getting ################################################ def prey_exists(self): if not os.path.exists(PREY_PATH + '/core'): self.rootO.show_alert("Prey not installed", "Couldn't find a Prey installation on this system. Sorry.", True) else: return True def is_config_writable(self): command = 'if [ ! -w "'+PREY_PATH+'/config" ]; then echo 1; fi' no_access = os.popen(command).read().strip() if no_access == '1': self.rootO.show_alert("Unauthorized", "You don't have access to manage Prey's configuration. Sorry.", True) else: return True def get_setting(self, var): command = 'grep \''+var+'=\' '+CONFIG_FILE+' | sed "s/'+var+'=\'\(.*\)\'/\\1/"' return os.popen(command).read().strip() def get_current_settings(self): #delay = os.popen("/opt/cron/bin/crontab -l | grep prey | cut -c 3-4").read() command = 'cat '+DAEMON_FILE+' | grep preyd | cut -d \' \' -f 3' self.curVars.delay = int(os.popen(command).read()) #if not delay: # self.curVars.delay = 30 #else: # self.curVars.delay = int(delay) self.curVars.auto_connect = self.get_setting('auto_connect') self.curVars.extended_headers = self.get_setting('extended_headers') self.curVars.lang = self.get_setting('lang') self.curVars.check_url = self.get_setting('check_url') self.curVars.post_method = self.get_setting('post_method') self.curVars.api_key = self.get_setting('api_key') self.curVars.device_key = self.get_setting('device_key') self.curVars.mail_to = self.get_setting('mail_to') self.curVars.smtp_server = self.get_setting('smtp_server') self.curVars.smtp_username = self.get_setting('smtp_username') def check_if_configured(self): if self.curVars.post_method == 'http' and self.curVars.api_key == '': return False else: return True ################################################ # setting settings ################################################ def save(self, param, value): if param == 'check_url': value = value.replace('/', '\/') command = 'sed -i -e "s/'+param+'=\'.*\'/'+param+'=\''+value+'\'/" '+ CONFIG_FILE os.system(command) @Slot(int) def apply_main_settings(self,delay): # save('lang', text('lang')) self.save('auto_connect', self.curVars.auto_connect) self.save('extended_headers', self.curVars.extended_headers) # check and change the crontab interval if delay != int(self.curVars.delay): # print 'Updating delay in crontab...' sub1 = ' -e \'s/preyd '+str(self.curVars.delay)+'/preyd '+str(delay)+'/g\' ' sub2 = ' -e \'s/every '+str(self.curVars.delay)+'/every '+str(delay)+'/g\' ' command = 'sed -i ' + sub1 + sub2 + DAEMON_FILE os.system('initctl stop apps/preyd') os.system(command) os.system('initctl start apps/preyd') #os.system('(/opt/cron/bin/crontab -l | tail -n+4 | grep -v prey; echo "*/'+str(delay)+' * * * * aegis-exec -s /opt/prey/prey.sh > /var/log/prey.log") | /opt/cron/bin/crontab -') if self.check_if_configured() == False: self.rootO.show_alert("All good.", "Configuration saved. Remember you still need to set up your posting method, otherwise Prey won't work!", True) else: self.rootO.show_alert("All good.", "Configuration saved!", True) @Slot() def create_new_user(self): if self.validate_fields(): self.create_user() def apply_control_panel_settings(self): if self.curVars.post_method != 'http': self.save('post_method', 'http') if self.curVars.check_url != CONTROL_PANEL_URL: self.save('check_url', CONTROL_PANEL_URL) # we could eventually use the email as a checking method to remove prey # i.e. "under which email was this account set up?" # self.save('mail_to', self.email) self.save('api_key', self.curVars.api_key) if self.curVars.device_key != "": self.save('device_key', self.curVars.device_key) @Slot(str) def apply_standalone_settings(self,password): if self.curVars.post_method != 'email': self.save('post_method', 'email') self.save('check_url', self.curVars.check_url) self.save('mail_to', self.curVars.mail_to) self.save('smtp_server', self.curVars.smtp_server) self.save('smtp_username', self.curVars.smtp_username) #smtp_password = self.('smtp_password') if password != '': encoded_pass = os.popen('echo -n "'+ password +'" | openssl enc -base64').read().strip() self.save('smtp_password', encoded_pass) self.exit_configurator() def exit_configurator(self): self.run_prey() self.rootO.show_alert(_("Success"), _("Configuration saved! Your device is now setup and being tracked by Prey. Happy hunting!"), True) def run_prey(self): os.system(PREY_PATH + '/run ') ################################################ # control panel api ################################################ def report_connection_issue(self, result): print("Connection error. Response from server: " + result) self.rootO.show_alert("Problem connecting", "We seem to be having a problem connecting to the Prey Control Panel. This is likely a temporary issue. Please try again in a few moments.",False) def user_has_available_slots(self, string): matches = re.search(r"<available_slots>(\w*)</available_slots>", string) if matches and int(matches.groups()[0]) > 0: return True else: return False def get_api_key(self, string): matches = re.search(r"<key>(\w*)</key>", string) if matches: self.curVars.api_key = matches.groups()[0] @Slot(result=int) def create_device_list(self): self.deviceList = self.rootO.findChild(QObject,"deviceList") self.deviceList.clear() for device in self.deviceNames: self.deviceList.add(device) return self.chosen def get_device_keys(self, string, has_available_slots): hostname = os.popen("hostname").read().strip() index = -1 self.deviceKeys = [] self.deviceNames = [] self.chosen = index matches = re.findall(r"<device>\s*<key>(\w*)</key>.*?<title>([\.\s\w]*)</title>\s*</device>", string, re.DOTALL) for match in matches: index += 1 key = match[0] title = match[1] self.deviceKeys.append(key) self.deviceNames.append(title) if key == self.curVars.device_key: #set the choice because we have a matching device key self.chosen = index elif title.lower() == hostname.lower and self.chosen < 0: #set the choice because we likely have a matching title (but device key takes precedence) self.chosen = index if index < 0: self.rootO.show_alert("No devices exist", "There are no devices currently defined in your Control Panel.\n\nPlease select the option to create a new device.",False) return False if self.chosen < 0: self.chosen = 0 return True def create_user(self): params = urllib.urlencode({'user[name]': self.curVars.user_name, 'user[email]': self.curVars.email, 'user[password]': self.curVars.password, 'user[password_confirmation]' : self.curVars.password_confirm}) result = os.popen('curl -i -s -k --connect-timeout 10 '+ CONTROL_PANEL_URL_SSL + '/users.xml -d \"'+params+'\"').read().strip() if result.find("<key>") != -1: self.get_api_key(result) self.curVars.device_key = "" elif result.find("Email has already been taken") != -1: self.rootO.show_alert("Email has already been taken", "That email address already exists! If you signed up previously, please go back and select the Existing User option.",False) return else: self.rootO.show_alert("Couldn't create user!", "There was a problem creating your account. Please make sure the email address you entered is valid, as well as your password.",False) return self.apply_control_panel_settings() self.run_prey() self.rootO.show_alert("Account created!", "Your account has been succesfully created and configured in Prey's Control Panel.\n\nPlease check your inbox now, you should have received a verification email.", True) @Slot(bool, result=bool) def get_existing_user(self, show_devices): email = self.curVars.email password = self.curVars.password print email+' '+password result = os.popen('curl -i -s -k --connect-timeout 10 '+ CONTROL_PANEL_URL_SSL + '/profile.xml -u '+email+":'"+password+"'").read().strip() if result.find('401 Unauthorized') != -1: self.rootO.show_alert("User does not exist", "Couldn't log you in. Remember you need to activate your account opening the link we emailed you.\n\nIf you forgot your password please visit preyproject.com.",False) return False if result.find("<user>") != -1: self.get_api_key(result) else: self.report_connection_issue(result) return False has_available_slots = self.user_has_available_slots(result) if not has_available_slots and not show_devices: self.rootO.show_alert("Not allowed", "It seems you've reached your limit for devices!\n\nIf you had previously added this PC, you should select the \"Device already exists\" option to select the device from a list of the ones you have already created.\n\nIf this is a new device, you can also upgrade to a Pro Account to increase your slot count and get access to additional features. For more information, please check\nhttp://preyproject.com/plans.",False) return False if show_devices: result = os.popen('curl -i -s -k --connect-timeout 10 '+ CONTROL_PANEL_URL_SSL + '/devices.xml -u '+email+":'"+password+"'").read().strip() if result.find("</devices>") != -1: return self.get_device_keys(result,has_available_slots) else: self.report_connection_issue(result) return False else: self.curVars.device_key = "" self.apply_control_panel_settings() self.exit_configurator() @Slot(int) def apply_device_settings(self,index): self.curVars.device_key = self.deviceKeys[index] self.apply_control_panel_settings() self.exit_configurator() def __init__(self, parent=None): super(MainWindow, self).__init__(parent) # Create the Qt Application self.app = QApplication(["Prey-Config"]) self.app.setWindowIcon(QIcon('')) self.view = QDeclarativeView() #self.setWindowTitle("Main Window") #get rootContext of QDeclarativeView self.context = self.view.rootContext() #make this class available to QML files as 'main' context self.context.setContextProperty('main', self) #create variables self.curVars = Vars() #make curVars available to QML files as 'vars' context self.context.setContextProperty('vars', self.curVars) # QML resizes to main window self.view.setResizeMode(QDeclarativeView.SizeRootObjectToView) # Renders './qml/main.qml' self.view.setSource(QUrl.fromLocalFile('./qml/main.qml')) #get rootObject self.rootO = self.view.rootObject() #connect quit signal self.view.engine().quit.connect(self.quit_app) #check for prey installation, write acess to config file, and configurationstatus if self.prey_exists(): if self.is_config_writable(): self.get_current_settings() if self.check_if_configured() == False: self.rootO.show_alert('Welcome!',"It seems this is the first time you run this setup. Please set up your reporting method now, otherwise Prey won't work!",False) #os.system('(/opt/cron/bin/crontab -l | tail -n+4 | grep -v prey; echo "*/30 * * * * aegis-exec -s /opt/prey/prey.sh > /var/log/prey.log") | /opt/cron/bin/crontab -') def quit_app(self): self.view.hide() self.app.exit()
class Application(QtGui.QDialog): __height = int(250) __width = int(200) __hostname = str('localhost') __portnumber = int(54321) ## the client socket __socket = QtNetwork.QTcpSocket() __seconds = int(0) __messages = int(0) __user = str("espen") def __init__(self, parent = None): super(Application, self).__init__(parent) self.handler = DocumentXmlHandler() ## Set values for the store/restore settings system QtCore.QCoreApplication.setOrganizationName("EMR") QtCore.QCoreApplication.setOrganizationDomain("code.rutger.no") QtCore.QCoreApplication.setApplicationName("QmlChatClient") ## create settings self.__settings = QtCore.QSettings() hostname = self.__settings.value("QmlChatClient/hostname") if hostname != None: self.__hostname = hostname portnumber = self.__settings.value("QmlChatClient/portnumber") if portnumber != None: self.__portnumber = portnumber ## Connect the socket's signals to our slots self.__socket.connected.connect(self.__socketConnected) self.__socket.disconnected.connect(self.__socketDisconnected) self.__socket.error.connect(self.__socketError) self.__socket.readyRead.connect(self.__readyRead) #self.__socket.stateChanged.connect(self.__socketStateChanged) userpassModel = UsernamePasswordModel() userpassModel.setHost(self.__hostname) userpassModel.setPort(int(self.__portnumber)) userpassModel.connectSignal.connect(self.__connectToSystem) userpassModel.cancelSignal.connect(self.quitSlot) self.loginView = QDeclarativeView() self.loginView.rootContext().setContextProperty("model", userpassModel) self.loginView.setSource(QUrl('qml/client/LoginDialog.qml')) self.loginView.setResizeMode(QDeclarativeView.SizeRootObjectToView) self.loggedInModel = LoggedInModel() self.loggedInModel.disconnectSignal.connect(self.__disconnectFromHost) self.loggedInModel.setHeight(self.__height) self.loggedInModel.setWidth(self.__width) self.loggedInModel.sendMessageSignal.connect(self.__sendMessage) self.loggedInView = QDeclarativeView() self.loggedInView.rootContext().setContextProperty("model", self.loggedInModel) self.loggedInView.setSource(QUrl('qml/client/RunningDialog.qml')) self.loggedInView.setResizeMode(QDeclarativeView.SizeRootObjectToView) self.stackedWidget = QtGui.QStackedWidget() self.stackedWidget.addWidget(self.loginView) self.stackedWidget.addWidget(self.loggedInView) self.stackedWidget.setCurrentWidget(self.loginView) self.stackedWidget.setWindowTitle('Qml Chat Client') self.stackedWidget.setGeometry(300, 300, self.__width, self.__height) self.stackedWidget.show() def __connectToSystem(self, hostname, portnumber): self.__hostname = hostname self.__portnumber = portnumber #print "ConnectToSystem hostname", self.__hostname, "portnumber", self.__portnumber ## Try to connect to the server try: self.__socket.connectToHost(self.__hostname, int(self.__portnumber)) except: text = 'Failed to connect to %s on port %d' % (self.__hostname, int(self.__portnumber)) print text ## remove file created above #os.unlink(self.__loginWidget.logfileName()) def quitSlot(self): print "quitSlot" exit() def __socketConnected(self): ## successfully logged in, write hostname and port number to settings self.__settings.setValue("ChatClient/hostname", self.__hostname) self.__settings.setValue("ChatClient/portnumber", self.__portnumber) ## Reset seconds and messages self.__seconds = 0 self.__messages = 0 ## Start timer that displays seconds and number of messages #self.__timer.start(1000) self.stackedWidget.setCurrentWidget(self.loggedInView) def __disconnectFromHost(self): ## Disconnect from server self.__socket.disconnectFromHost() def __socketDisconnected(self): ## we,re disconnected, stop the timer #self.__timer.stop() ## Create new file name - it will be displayed when current widget beocmes loginWidget in the next statement #self.__loginWidget.createFilename() ## Set login widget as current widget self.stackedWidget.setCurrentWidget(self.loginView) ## Clear dialog text self.loggedInModel.clear() ## Send the message def __sendMessage(self, text): print "sendMessage", text message = str('<chat><content user=\"%s\" type=\"message\"></content><message message=\"%s\"></message></chat>' % (self.__user, text)) self.__socket.write(message) ## Data is ready for reading def __readyRead(self): ## Read the size of data available, return if no data size = self.__socket.bytesAvailable() if size == 0: return ## Read data data = str(self.__socket.read(size)) ## Initialize xml reader reader = QtXml.QXmlSimpleReader() reader.setContentHandler(self.handler) reader.setErrorHandler(self.handler) ## xml input source xmlInputSource = QtXml.QXmlInputSource() xmlInputSource.setData(data) print 'DEBUG DATA', xmlInputSource.data() ## Parse xml file if reader.parse(xmlInputSource) == False: print "Pars xml error:", self.handler.errorString() return False ## skip empty strings if self.handler.message == "" or self.handler.message == '\n' or self.handler.message == '\l\c': print 'Empty string' return if self.handler.user == self.__user: data = str("%s: %s" % ("me", self.handler.message)) else: data = str("%s: %s" % (self.handler.user, self.handler.message)) #print "__readyRead:", data self.loggedInModel.setText(str(data)) self.loggedInModel.onTextChanged.emit(str(data)) ## Emit the write message signal #self.__writeMessageSignal.emit(data) ## Count the message self.__messages += 1 ## The state of the socket has changed def __socketStateChanged(self, state): print "MainWidget::socketStateChanged state", str(state) ## Manage socket errors def __socketError(self, error): QtGui.QMessageBox.critical(self, "Chat Client", "Socket Error: %s" % self.__socket.errorString()) return