예제 #1
0
class LoginController:
	def __init__(self):
		gui = Gtk.Builder()
		gui.add_from_file("../GUI/LoginScreen.glade")
		events = {"on_botIniciar_clicked": self.logIn,
			"on_botCrear_clicked": self.createEnterprise,
			"on_LoginScreen_delete_event": Gtk.main_quit,
			} 
		gui.connect_signals(events)
		self.Window = gui.get_object("LoginScreen")
		self.empresa = gui.get_object("getEmpresa")
		self.user = gui.get_object("getUser")
		self.password = gui.get_object("getPass")
		self.Window.set_title("Login")
		self.client = WebClient()
		self.listaEmpresas = self.client.getEmpresas()
		
		if(self.listaEmpresas):
			for i in self.listaEmpresas[0]:
				self.empresa.append_text(i)
			self.empresa.set_active(0)
	
	def logIn(self, button):
		user = self.user.get_text()
		password = md5(self.password.get_text()).hexdigest()
		empresa = self.empresa.get_active_text()
		if(user != '' and password != '' and empresa != '' and self.client.checkLogin(empresa, user, password)):
			self.Window.set_visible(False)
			startMainMenuController(self.client, empresa, user)
			self.Window.set_visible(True)
		else:
			startErrorController('Error en Inicio de Session')
			
	def createEnterprise(self, button):
		self.Window.set_visible(False)
		
		startEnterpriseController(self.client)
		
		if(self.listaEmpresas):
			for i in self.listaEmpresas[0]:
				self.empresa.remove(0)
			
		self.listaEmpresas = self.client.getEmpresas()
		
		if(self.listaEmpresas):
			for i in self.listaEmpresas[0]:
				self.empresa.append_text(i)
			self.empresa.set_active(0)
			
		self.empresa.set_active(0)
		self.Window.set_visible(True)
예제 #2
0
 def __init__(self, webClient, empresa):
     gui = Gtk.Builder()
     gui.add_from_file("../GUI/CrearUsuario.glade")
     events = {
         "on_botCrear_clicked": self.createUser,
         "on_CrearUsuario_delete_event": Gtk.main_quit,
     }
     gui.connect_signals(events)
     self.Window = gui.get_object("CrearUsuario")
     self.user = gui.get_object("getUser")
     self.password = gui.get_object("getPass")
     self.Window.set_title("Crear Usuario")
     self.empresa = empresa
     self.client = WebClient()
예제 #3
0
파일: Reporting.py 프로젝트: Davnit/ESMapV2
    def sendReport(self, url, key=None):
        data = {"geodata": json.dumps(self.getData(), separators=(',', ':'))}

        if key is not None and len(key) > 0:
            data["key"] = key

        ok, response = WebClient.postData(url, data)
        if ok:
            data = json.loads(response)
            status = data["status"]

            if status["success"]:
                match = True
                if "resolved" in status and status["resolved"] != len(
                        self.requests):
                    match = False

                if not match:
                    print("Reporting mismatch. Server resolved {0} locations.".
                          format(status["resolved"]))

                return True
            else:
                print("Geocode report failed. Reason:", status["message"])
        else:
            print("Geocode report submission failed. Reason:", str(response))

        return False
예제 #4
0
def getRemoteSources(sourceUrl):
    sources = {}

    # Request sources from remote server
    ok, response = WebClient.openUrl(sourceUrl, {"request": 1})
    if not ok:
        print("ERROR! Unable to obtain sources: " + str(response))
        return sources

    # Decode returned data and check status
    data = json.loads(response)

    status = data["status"]
    if not status["success"]:
        print("ERROR: Error getting sources: " + status["message"])
        return sources

    # Check for returned values
    if not isinstance(data["data"], dict):
        return sources

    # Parse returned values
    # Format: { id => [ tag, url, parser, interval ] }
    for srcID, sInfo in data["data"].items():
        src = CallSource(sInfo[0], sInfo[1], getParserPath(sInfo[2]))
        src.id = int(srcID)
        src.interval = int(sInfo[3])

        verifyParser(src.parser)
        sources[src.id] = src

    return sources
예제 #5
0
파일: Geocoder.py 프로젝트: Davnit/ESMapV2
    def tryResolve(self, apiUrl, clientKey=None):
        global quota_exceeded, last_api_call

        # Build request parameters
        params = {"address": self.location}
        if clientKey is not None:
            params["key"] = clientKey

        # Convert filter to piped list
        #  key1:v1|key1:v2|key1:v3|key2:v1|key2:v2|etc
        comp = ""
        for k, v in self.filter.items():
            for item in v:
                comp += k + ":" + item + "|"
        if len(comp) > 0:
            params["components"] = comp[:-1]

        # Make the request
        ok, response = WebClient.openUrl(apiUrl, params)
        if not ok: return False

        last_api_call = datetime.now()

        # Parse results
        self.results = json.loads(response)
        if self.results["status"] in ["OK", "ZERO_RESULTS"]:
            self.resolved = True
        elif self.results["status"] == "OVER_QUERY_LIMIT":
            quota_exceeded = True
        return self.resolved
예제 #6
0
파일: Geocoder.py 프로젝트: Davnit/ESMapV2
def getRequests(sourceUrl):
    ok, response = WebClient.openUrl(sourceUrl, {"request": 3})
    if not ok:
        print("ERROR Unable to obtain geocode requests: " + str(response))
    else:
        # Decode the returned JSON and check the response status
        data = json.loads(response)

        status = data["status"]
        if not status["success"]:
            print("ERROR Obtaining geocode requests: " + status["message"])
        else:
            # Check if values were returned
            if isinstance(data["data"], dict):
                # Parse the returned values
                for id, location in data["data"].items():
                    if id in open_requests: continue  # Only add new requests

                    req = GeocodeRequest(id, location)
                    req.filter = {
                        "country": ["US"],
                        "administrative_area": ["Florida", "Orange County"]
                    }
                    open_requests[id] = req

    return open_requests.values()
예제 #7
0
class UserController:
	def __init__(self, webClient, empresa):
		gui = Gtk.Builder()
		gui.add_from_file("../GUI/CrearUsuario.glade")
		events = {"on_botCrear_clicked": self.createUser,
			"on_CrearUsuario_delete_event": Gtk.main_quit,
			} 
		gui.connect_signals(events)
		self.Window = gui.get_object("CrearUsuario")
		self.user = gui.get_object("getUser")
		self.password = gui.get_object("getPass")
		self.Window.set_title("Crear Usuario")
		self.empresa = empresa
		self.client = WebClient()
	
	def createUser(self, button):
		user = self.user.get_text()
		password = md5(self.password.get_text()).hexdigest()
		print user, password, self.empresa
		print self.client.crearUsuario(user, password, self.empresa)
예제 #8
0
class UserController:
    def __init__(self, webClient, empresa):
        gui = Gtk.Builder()
        gui.add_from_file("../GUI/CrearUsuario.glade")
        events = {
            "on_botCrear_clicked": self.createUser,
            "on_CrearUsuario_delete_event": Gtk.main_quit,
        }
        gui.connect_signals(events)
        self.Window = gui.get_object("CrearUsuario")
        self.user = gui.get_object("getUser")
        self.password = gui.get_object("getPass")
        self.Window.set_title("Crear Usuario")
        self.empresa = empresa
        self.client = WebClient()

    def createUser(self, button):
        user = self.user.get_text()
        password = md5(self.password.get_text()).hexdigest()
        print user, password, self.empresa
        print self.client.crearUsuario(user, password, self.empresa)
예제 #9
0
	def __init__(self, webClient, empresa):
		gui = Gtk.Builder()
		gui.add_from_file("../GUI/CrearUsuario.glade")
		events = {"on_botCrear_clicked": self.createUser,
			"on_CrearUsuario_delete_event": Gtk.main_quit,
			} 
		gui.connect_signals(events)
		self.Window = gui.get_object("CrearUsuario")
		self.user = gui.get_object("getUser")
		self.password = gui.get_object("getPass")
		self.Window.set_title("Crear Usuario")
		self.empresa = empresa
		self.client = WebClient()
예제 #10
0
def resync():
    if not c.UseRemoteServer or len(c.DataUrl) == 0:
        raise Exception("Cannot resync when using local data.")

    print("Syncing with server: {0}".format(c.DataUrl.split("://")[1].split("/")[0]))

    sources = Sources.getRemoteSources(c.DataUrl)
    active = { }

    # Get current call list from server
    ok, response = WebClient.openUrl(c.DataUrl, { "request": 2 })
    if ok:
        data = json.loads(response)
        status = data["status"]

        if status["success"]:
            if isinstance(data["data"], dict):
                # Format: data => source: { cid => [ category, location, meta ] }
                for srcID, calls in data["data"].items():
                    isrc = int(srcID)
                    if not isrc in sources: continue
                    
                    src = sources[isrc]
                    active[src.id] = [ ]

                    for cID, call in calls.items():
                        # Create a call object to represent this item
                        callObj = Calls.CallData(json.loads(call[2]))
                        callObj.category = call[0]
                        callObj.location = call[1]
                        callObj.key = cID
                        callObj.source = src
            
                        active[src.id].append(callObj)
                        print("\t{0}: {1}".format(src.tag, callObj.getShortDisplayString()))
            else:
                print("\t... No calls active.")

        else:
            print("\t...", status["message"])
    else:
        print("\t... failed: " + str(response))

    return sources, active
예제 #11
0
	def __init__(self):
		gui = Gtk.Builder()
		gui.add_from_file("../GUI/LoginScreen.glade")
		events = {"on_botIniciar_clicked": self.logIn,
			"on_botCrear_clicked": self.createEnterprise,
			"on_LoginScreen_delete_event": Gtk.main_quit,
			} 
		gui.connect_signals(events)
		self.Window = gui.get_object("LoginScreen")
		self.empresa = gui.get_object("getEmpresa")
		self.user = gui.get_object("getUser")
		self.password = gui.get_object("getPass")
		self.Window.set_title("Login")
		self.client = WebClient()
		self.listaEmpresas = self.client.getEmpresas()
		
		if(self.listaEmpresas):
			for i in self.listaEmpresas[0]:
				self.empresa.append_text(i)
			self.empresa.set_active(0)
예제 #12
0
파일: Reporting.py 프로젝트: Davnit/ESMapV2
    def sendReport(self, url, key=None):
        data = {"calldata": json.dumps(self.getData(), separators=(',', ':'))}

        if key is not None and len(key) > 0:
            data["key"] = key

        # Submit data
        ok, response = WebClient.postData(url, data)
        if ok:
            data = json.loads(response)
            status = data["status"]

            # If the server accepted the report, compare the results
            if status["success"]:
                match = True
                if status["added"] != len(self.added): match = False
                if status["expired"] != len(self.expired): match = False
                if status["updated"] != len(self.updated): match = False

                # Did the server accept all of the changes?
                if not match:
                    msg = "Reporting mismatch. Server added {0}/{1} rows, expired {2}/{3}, updated {4}/{5}."
                    print(
                        msg.format(status["added"],
                                   len(self.added), status["expired"],
                                   len(self.expired), status["updated"],
                                   len(self.updated)))
                else:
                    return True
            else:
                print("Report failed. Reason: " + status["message"])
        else:
            print("Report submission failed. Reason:", str(response))

        # default fail
        return False
예제 #13
0
def event_loop():
    global shoe_uid
    while 1:
        line = readline()
        print "got line: '{0}'".format(line)
        if (line == "request challenge"):
            shoe_uid = readline()
            perm_pk = readline()
            temp_pk = readline()
            if (shoe_uid[0] != 'a' or perm_pk[0] != 'a' or temp_pk[0] != 'a'):
                print "got garbage"
                sendline("discard")
            else:
                print "request challenge: {0} {1} {2}".format(
                    shoe_uid, perm_pk, temp_pk)
                webclient.requestChallenge(shoe_uid, perm_pk, temp_pk)
                if (webclient.permChallenge != ""
                        and webclient.tempChallenge != ""):
                    sendline(webclient.permChallenge)
                    sendline(webclient.tempChallenge)
                else:
                    sendline("discard")
        elif (line == "send response"):
            #perm_response = readline()
            #temp_response = readline()
            # cheating a little here...
            perm_response = webclient.permChallenge
            temp_response = webclient.tempChallenge
            print "send response: '{0}' '{1}' '{2}'".format(
                shoe_uid, perm_response, temp_response)
            webclient.sendResponse(shoe_uid, perm_response, temp_response)
        elif (line == "shoe disconnected"):
            shoe_uid = "ERROR"
            print "shoe disconnected"
            webclient.logout()
        elif (line == "log"):
            print "log: {0}".format(readline())
예제 #14
0
            #temp_response = readline()
            # cheating a little here...
            perm_response = webclient.permChallenge
            temp_response = webclient.tempChallenge
            print "send response: '{0}' '{1}' '{2}'".format(
                shoe_uid, perm_response, temp_response)
            webclient.sendResponse(shoe_uid, perm_response, temp_response)
        elif (line == "shoe disconnected"):
            shoe_uid = "ERROR"
            print "shoe disconnected"
            webclient.logout()
        elif (line == "log"):
            print "log: {0}".format(readline())


if __name__ == "__main__":
    if (len(sys.argv) != 2):
        print "Usage: client.py <serial port>"
        print "Run list_ports.py for a list of serial ports."
        exit(0)

    try:
        ser = serial.Serial(sys.argv[1], 9600, timeout=0)
    except serial.serialutil.SerialException:
        print "Device not found: {0}".format(sys.argv[1])
        exit(0)

    webclient.connect()
    print "{0}/newSession/{1}".format(webclient.baseUrl, webclient.myToken)
    event_loop()
예제 #15
0
def check(source):
    # Confirm that the source can be checked and parsed
    if not canCheck(source):
        return False

    # Retrieve the page contents
    ok, data = WebClient.openUrl(source.url)
    if not ok:
        print("ERROR! Failed to open source {0}: {1}".format(source.tag, data))
        return False

    results = []  # Provides a place for the parser script to store data
    replacements = {
    }  # Dictionary of localized location elements to be replaced.

    # Compile and run the parser script
    try:
        exec(compile(open(source.parser, 'rb').read(), source.parser, 'exec'))
    except Exception as ex:
        print("ERROR! Problem occurred while parsing source {0}: {1}".format(
            source.tag, ex))
        return False

    # Update the last_update time
    source.last_update = datetime.now()

    # Create call objects from the parser results and tag them
    calls = []
    for r in results:
        c = Calls.CallData(r["meta"])
        c.source = source
        c.key = r["key"]
        c.category = r["category"]

        # Do localized location replacements
        if len(replacements) > 0:
            location = []
            for element in r["location"].split(
            ):  # For each part of the location
                found = False

                for find, replace in replacements.items(
                ):  # Check for each replacement
                    if element.upper() == find.upper():
                        found = True
                        location.append(replace)
                        break

                # If nothing to be replaced was found just add the element
                if not found:
                    location.append(element)

            c.location = " ".join(location)
        else:
            c.location = r["location"]

        # Check for provided coordinates
        if ("geo_lat" in r) and ("geo_lng" in r):
            c.coords = [r["geo_lat"], r["geo_lng"]]

        calls.append(c)

    return calls
예제 #16
0
from WebClient import *
from GeoInfoFormatter import GeoInfo
import geopandas as gpd

searchList = ['喜茶', '益禾堂', '蜜雪冰城']

for keyword in searchList:
    webClient = WebClient(keyword, '0755')
    webClient.searchAll()
    locationList = webClient.getResult()
    geoInfo: GeoInfo = GeoInfo()
    geoInfo.addLocationList(locationList)
    gdf = geoInfo.getGeoDataFrame()
    gdf.to_file('data/{}.shp'.format(keyword))