Exemplo n.º 1
0
def do_search2() -> 'html':
    获取起点 = request.form['walk_origin']
    起点 = geocode(zmf_key, 获取起点)
    获取终点 = request.form['walk_disitination']
    终点 = geocode(zmf_key, 获取终点)
    步行规划 = walk(zmf_key,起点,终点)
    return render_template('result_walk.html',
                           the_walk=步行规划,
                           the_origin=获取起点,
                           the_disitination=获取终点,)
Exemplo n.º 2
0
def do_search4() -> 'html':
    获取车辆起点 = request.form['car_origin']
    bus_origin1 = geocode(zmf_key, 获取车辆起点)
    获取车辆终点 = request.form['car_zhongdian']
    car_disitination1 = geocode(zmf_key, 获取车辆终点)
    车辆规划 = car(zmf_key,bus_origin1,car_disitination1)
    return render_template('result_drive.html',
                           the_car=车辆规划,
                           thecar_origin=获取车辆起点,
                           thecar_disitination= 获取车辆终点,
                           )
Exemplo n.º 3
0
def do_search5() -> 'html':
    获取骑行起点 = request.form['cycle_origin']
    cycle_origin1 = geocode(zmf_key, 获取骑行起点)
    获取骑行终点 = request.form['cycle_zhongdian']
    cycle_disitination1 = geocode(zmf_key, 获取骑行终点)
    车辆规划 = cycle(zmf_key,cycle_origin1,cycle_disitination1)
    return render_template('result_riding.html',
                           the_cycle=车辆规划,
                           thecar_origin=获取骑行起点,
                           thecar_disitination= 获取骑行终点,
                           )
Exemplo n.º 4
0
def do_search3() -> 'html':
    获取公交起点 = request.form['bus_origin']
    bus_origin1 = geocode(zmf_key, 获取公交起点)
    获取公交终点 = request.form['bus_zhongdian']
    bus_city1=request.form['bus_city']
    bus_disitination1 = geocode(zmf_key, 获取公交终点)
    公交规划 = bus(zmf_key,bus_origin1,bus_disitination1,bus_city1)
    return render_template('result_bus.html',
                           the_bus=公交规划,
                           thebus_origin=获取公交起点,
                           thebus_disitination= 获取公交终点,
                           )
Exemplo n.º 5
0
def do_search6() -> 'html':
    获取货车起点 = request.form['huoche_origin']
    huoche_origin1 = geocode(zmf_key, 获取货车起点)
    获取货车终点 = request.form['huoche_zhongdian']
    huoche_disitination1 = geocode(zmf_key, 获取货车终点)
    huochesize1=request.form['huoche_size']
    货车规划 = truck(xu_key,huoche_origin1,huoche_disitination1,huochesize1,)
    return render_template('result_6.html',
                           the_huoche=货车规划,
                           thehuoche_origin=获取货车起点,
                           thehuoche_disitination= 获取货车终点,
                           )
Exemplo n.º 6
0
 def geocode(self):
     if self.manual_longitude is not None and self.manual_latitude is not None:
         self.longitude = self.manual_longitude
         self.latitude = self.manual_latitude
         return
     
     if self.lookup:
         coords = geo.geocode(self.lookup)
         if coords:
             (self.latitude, self.longitude) = coords
     else:
         coords = geo.geocode(self.postal)
         if coords:
             (self.latitude, self.longitude) = coords
Exemplo n.º 7
0
class Parse(object):
    search = {}
    
    def __init__(self, lati=None, longi=None, user = None ):
        self.search['search'] = data
        self.search['distance'] = 50

        if lati and longi:
            self.search.geo = [float(lati),float(longi)]
            try:
                address,zipcode = reverse_geocode(lati,longi)
            except Exception, e:
                log(  "Geosearch error {}".format( str(e) ) )
            else:
                search.zip = zipcode

        elif user and not user.is_anonymous:
            try:
                if user.location:
                    search['geo'] = user.location
                elif user.address:
                    location = geocode( user.address )
                    search.geo = [float(location['lat']), float(location['lng'])]
            except Exception, e:
                log ( 'User geo error {}'.format( str(e) ) )
Exemplo n.º 8
0
def geocode(db, table, key, addressList, x, y, q, a, i, t):
    '''
    db: sqlite databse path
    table: table name
    key: google api key
    addressList: addres fields list from the table
    x: where store longitude
    y: where store latitude
    q: where store quality
    a: where store formatted address,
    i: where store place_id
    t: where store type of place
    '''
    addColumns(db, table, [x, y, q, a, i, t])
    conn = sqlite3.connect(db)
    conn.row_factory = dict_factory
    c = conn.cursor()
    c.execute('select rowid, * from ' + table)
    results = c.fetchall()
    rows = []
    for r in results:
        add = ', '.join([r[k] or '' for k in addressList])
        xx, yy, qq, aa, ii, tt = geo.geocode(add, key)
        row = [{x: xx, y: yy, a: aa, q: qq, i: ii, t: tt}]
        update(db, table, row, {'rowid': r['rowid']})
    return
Exemplo n.º 9
0
def do_search7() -> 'html':
    didian=request.form['around_origin']
    周边1=geocode(zmf_key,didian)
    周边=around(zmf_key, 周边1)
    return render_template('result_zhoubian.html',
                           the_zhoubian=周边,
                           )
Exemplo n.º 10
0
def do_search1() -> 'html':
    # 获取颜色=request.form['color']
    # 获取颜色1=request.form['color01']
    用户输入的结构化地址 = request.form['geocode']
    经纬度坐标 = geocode(zmf_key, 用户输入的结构化地址)
    return render_template('result_bianma.html',
                           the_geo=经纬度坐标,)
Exemplo n.º 11
0
    def filter_geo(self, address_list, limit=10):
        geobox = self.get_argument_geobox(default=None)
        latlon = self.get_argument_latlon("latlon", None)
        if geobox:
            return Address.filter_geobox(address_list, geobox), geobox, latlon

        # Find geobox around the center that includes at least 10 matches
        if not latlon:
            lookup = self.get_argument("lookup", None)
            if lookup:
                latlon = geo.geocode(lookup)
                if not latlon:
                    self.messages.append(("WARNING", "Could not find address: '%s'." % lookup))
        if not latlon:
            return address_list.limit(limit), geobox, latlon

        address_list_2 = Address.order_distance(address_list, latlon)
        address_list_2 = address_list_2.limit(limit)
        max_dist = Address.max_distance(
            self.orm, address_list_2, latlon[0], latlon[1])
        max_dist *= 1.1

        scale = Address.scale(latlon[0])

        values = (
            latlon[0] - max_dist,
            latlon[0] + max_dist,
            max(latlon[1] - max_dist / max(scale, 0.01), -180),
            min(latlon[1] + max_dist / max(scale, 0.01), 180),
            )
        geobox = dict(zip(["latmin", "latmax", "lonmin", "lonmax"], values))
        return Address.filter_geobox(address_list, geobox), geobox, latlon
Exemplo n.º 12
0
def search():
    search = request.form.get('search')
    place = geocode(search)
    if place:
        return jsonify(
            place
        )  #redirect('/?lng={}&lat={}'.format(place[u'lng'], place[u'lat']))

    abort(404)
Exemplo n.º 13
0
def load_latlng():
    result = model.session.query(model.Address).filter(or_(model.Address.lat == '', model.Address.lng == '', model.Address.lat == None, model.Address.lng == None)).all()
    for adr in result:
        addr = []
        if (adr.lat == None or adr.lng == None):
            addr = [adr.street,adr.city,adr.state,adr.zipcode]
            format_addr = ",".join(addr) 
            lat,lng = geo.geocode(format_addr,"false")  
            adr.lat = lat
            adr.lng = lng
    model.session.commit()
Exemplo n.º 14
0
def signup():
    """ Signup a new user """

    form = SignUpForm(request.form)
    if not request.method == 'POST' or not form.validate():
        context = {'form': form}
        return render_template('signup.html', **context)

    username = form.username.data
    password = form.password.data
    email = form.email.data
    phone = form.phone.data
    address = form.address.data
    subscribe = form.subscribe.data
    duration = form.duration.data
    pay_method = form.pay_method.data

    # Check if they they exist already
    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        try:
            user = User.objects.get(email=email)
        except User.DoesNotExist:
            user = User(username=username, email=email)
            user.address = address
            user.phone = phone
            user.address = address
            user.subscribe = subscribe

            user.set_password(password)

            try:
                local = geocode(user.address)
                user.location = [float(local['lat']), float(local['lng'])]
            except Exception, e:
                pass

            try:
                user.save()
            except Exception, e:
                print e
            else:
                # Place holder until paid subscription enabled
                if pay_method == 'free':
                    duration = 2

                expires = datetime.today() + relativedelta(months=2)
                subscription = Subscription(user=user,
                                            expires=expires,
                                            active=True)
                subscription.save()
Exemplo n.º 15
0
def load_latlng():
    result = model.session.query(model.Address).filter(
        or_(model.Address.lat == '', model.Address.lng == '',
            model.Address.lat == None, model.Address.lng == None)).all()
    for adr in result:
        addr = []
        if (adr.lat == None or adr.lng == None):
            addr = [adr.street, adr.city, adr.state, adr.zipcode]
            format_addr = ",".join(addr)
            lat, lng = geo.geocode(format_addr, "false")
            adr.lat = lat
            adr.lng = lng
    model.session.commit()
Exemplo n.º 16
0
    def set_location(self, zip, miles=None):
        self.zip = zip
        if miles:
            if miles == 'unlimited':
                del self.geo
                self.save()
                return None
            else:
                self.distance = miles

        try:
            location = geocode(zip)
            self.geo = [float(location['lat']), float(location['lng'])]
        except Exception, e:
            return None
Exemplo n.º 17
0
def add():
    """ Add a new event
    """
    form = EventForm(request.form)
    if request.method == 'POST' and form.validate():

        data = dict(name=form.name.data,
                    sport=form.sport.data,
                    level=form.level.data,
                    where=form.where.data,
                    contact=current_user.id)

        day = str(form.day.data) + " " + str(form.time.data)

        e = Event.objects(**data).modify(upsert=True,
                                         new=True,
                                         set__modified=datetime.now())

        e.when = arrow.get(day, 'YYYY-MM-DD HH:mm:ss').datetime
        e.fees = form.fees.data
        e.restrictions = form.restrictions.data
        e.comments = form.comments.data

        e.will_host = True if form.will_host.data else False
        e.will_travel = True if form.will_travel.data else False
        e.text = True if form.text.data else False
        e.email = True if form.email.data else False
        e.call = True if form.call.data else False

        location = geocode(data['where'])
        if location:
            e.location = [location['lng'], location['lat']]
        else:
            e.location = current_user.location

        try:
            e.save()
        except Exception as err:
            logging.error("Exception {} trying to save event {}".format(
                str(err), e))

        else:
            return redirect('/')

    sport = {sport: 'True' for sport in current_user.sports}
    context = {'form': form, 'sports': sport}
    content = render_template('event.html', **context)
    return content
Exemplo n.º 18
0
 def get_geobox(self):
     geobox = self.get_argument_geobox(default=None)
     if geobox:
         return geobox
     latlon = self.get_argument_latlon("latlon", None)
     distance = self.get_argument_float("distance", 25)
     if not latlon:
         lookup = self.get_argument("lookup", None)
         if lookup:
             latlon = geo.geocode(lookup)
             if not latlon:
                 self.messages.append(("WARNING", "Could not find address: '%s'." % lookup))
                 return None
     if not latlon:
         return None
     return Address.geobox(latlon[0], latlon[1], distance)
Exemplo n.º 19
0
def validate_address(street, city, state, zipcode):
    """
    Validate an address with Google
    """
    # Look for any sub addresses like Apt, Building .. and dump them
    sub_address = parse_address(street)
    if sub_address and sub_address != street:
        address = sub_address
    else:
        address = street

    address += " " + city + " " + state + " " + zipcode
    try:
        local = geocode(address)
    except Exception, e:
        return None
Exemplo n.º 20
0
def selective_geocode(rough_address: str) -> dict:
    """ Gets the average GPS coordinates of the rough address interval """
    lat_results = []; lon_results = []
    found = re.findall(r"\d+~\d+", rough_address)
    if not found:
        raise geo.AddressError(geo.__name__, rough_address)
    bound = [int(i) for i in found[0].split('~')]
    if bound[0] > bound[1]:
        raise geo.AddressError(geo.__name__, rough_address)
    interval = int((bound[1] - bound[0] + 1) / settings.GEO_SAMPLES)
    samples = [i for i in range(bound[0], bound[1] + 1, interval)]
    for sample in samples:
        query_address = rough_address.replace(found[0], str(sample))
        gps_coordinates = geo.geocode(query_address, culture='zh-TW')["GPS"]
        if gps_coordinates["lat"] and gps_coordinates["lon"]:
            lat_results.append(gps_coordinates["lat"])
            lon_results.append(gps_coordinates["lon"])
    return {"lat": lat_results, "lon": lon_results}
Exemplo n.º 21
0
def signup():
    """ Signup a new user 
    """
    form = SignUpForm(request.form)
    if request.method == 'POST' and form.validate():

        first_name = form.first_name.data
        last_name = form.last_name.data
        username = form.username.data
        password = form.password.data
        preference = form.preference.data
        phone = form.phone.data
        address = form.address.data

        # Check if they they exist already
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            user = User(username=username)
            user.first_name = first_name
            user.last_name = last_name
            user.address = address
            user.phone = phone
            user.address = address
            user.preference = preference
            user.set_password(password)

            try:
                local = geocode(user.address)
                user.location = [float(local['lat']), float(local['lng'])]
            except Exception as e:
                pass

            try:
                user.save()
            except Exception as e:
                print(e)
        else:
            form.username.errors = "User already exists"

    context = {'form': form}
    content = render_template('signup.html', **context)
    return content
Exemplo n.º 22
0
    search.distance = 50
    if lati and longi:
        search.geo = [float(lati),float(longi)]
        try:
            address,zipcode = reverse_geocode(lati,longi)
        except Exception, e:
            log(  "Geosearch error {}".format( str(e) ) )
        else:
            search.zip = zipcode
    elif user:
        if not user.is_anonymous():
            try:
                if user.location:
                    search.geo = user.location
                elif user.address:
                    location = geocode( user.address )
                    search.geo = [float(location['lat']), float(location['lng'])]
            except Exception, e:
                log ( 'User geo error {}'.format( str(e) ) )

    # Break up the request
    #data = data.replace('-',' - ')
    words  = word_tokenize(data)
    get_properties( data )
    #tags   = pos_tag(words)
    #chunks = ne_chunk(tags)

    dollars          = False
    last_number      = None
    preceeding_word  = None
    preposition      = None
Exemplo n.º 23
0
def checkin(request):
    logger = logging.getLogger('django')
    logger.debug('WWW Query: %s', request.body)

    if settings.USE_CERTIFICATE == True:
        # Get the certificate fingerprint
        try:
            bio = BIO.MemoryBuffer(base64.b64decode(request.META['HTTP_MDM_SIGNATURE']))
            p7 = SMIME.PKCS7(m2.pkcs7_read_bio_der(bio._ptr()), 1)
            stk = X509.X509_Stack()
            sk3 = p7.get0_signers(stk)
            cert = sk3.pop()
            fingerprint = cert.get_fingerprint('md5')
            if len(fingerprint) == 31:
                fingerprint = '0' + fingerprint
        except:
            fingerprint = None

        logger.debug('Fingerprint: %s', fingerprint)
        # If no certificate supplied, permission denied.
        if fingerprint == None and settings.REQUIRE_CERTIFICATE == True:
            return HttpResponseForbidden()

        # If no certificate found, permission denied.
        certificate = Certificate.objects.filter(md5=fingerprint).first()
        if certificate == None and settings.REQUIRE_CERTIFICATE == True:
            return HttpResponseForbidden()

        # If certificate does not match device, permission denied.
        # TODO
    else:
        certificate = None

    # Prepare handling of checkin request and response commands.
    responseData = plistlib.writePlistToString(dict())
    standard_commands.initialize()

    try:
        plist = plistlib.readPlistFromString(request.body)
    except:
        plist = dict()

    if 'MessageType' in plist:
        if plist['MessageType'] == 'Authenticate':
            if 'UserID' in plist:
                return HttpResponseBadRequest('User binding not currently supported')

            device = Device.objects.filter(udid=plist['UDID']).first()
            if device == None:
                device = Device(udid=plist['UDID'], push_topic=plist['Topic'])
            device.last_checkin = datetime.now()
            device.last_notification = datetime.now()
            device.save()
            if certificate != None:
                certificate.device = device
                certificate.save()

            try:
                group = DeviceGroup.objects.filter(uuid=settings.DEFAULT_DEVICE_GROUP).first()
                group.devices.add(device)
                group.save()
            except:
                pass

        elif plist['MessageType'] == 'TokenUpdate':
            if 'UserID' in plist:
                return HttpResponseBadRequest('User binding not currently supported')

            device = Device.objects.get(udid=plist['UDID'])
            device.push_topic = plist['Topic']
            device.push_token = plist['Token'].asBase64(maxlinelength=8000)
            device.push_magic = plist['PushMagic']
            device.last_checkin = datetime.now()
            device.save()

            DeviceCommand.NewDeviceInformation(device)
            DeviceCommand.NewProfileList(device)
            DeviceCommand.NewInstalledApplicationList(device)
            push.push_notification(device)
        elif plist['MessageType'] == 'CheckOut':
            if 'UserID' in plist:
                return HttpResponseBadRequest('User binding not currently supported')

            Device.objects.get(udid=plist['UDID']).delete()
        else:
            print 'Unknown message type: ' + plist['MessageType']
            print plist
    elif 'Status' in plist:
        responseData = ''

        # Update device checkin time
        device = Device.objects.get(udid=plist['UDID'])
        device.last_checkin = datetime.now()
        device.save()

        # Update device location if it has been 15 minutes since last.
        since = datetime.now() - timedelta(minutes=15)
        location = DeviceCheckin.objects.filter(device=device).order_by('-end_date').first()
        if location and location.ip == request.META['REMOTE_ADDR']:
            location.end_date = datetime.now()
            location.save()
        else:
            location = DeviceCheckin(device=device)
            location.start_date = datetime.now()
            location.end_date = datetime.now()
            location.ip = request.META['REMOTE_ADDR']
            loc = geo.geocode(request.META['REMOTE_ADDR'])
            location.latitude = loc['latitude']
            location.longitude = loc['longitude']
            location.country_code = loc['country_code']
            location.region_code = loc['region_code']
            location.city = loc['city']
            if 'country_name' in loc:
                location.country_name = loc['country_name']
            if 'region_name' in loc:
                location.region_name = loc['region_name']
            location.save()

        if plist['Status'] == 'Acknowledged':
            cmd = DeviceCommand.objects.get(uuid=plist['CommandUUID'])
            cmd.status = DeviceCommand.SUCCESS
            cmd.date_completed = datetime.now()
            cmd.save()
            commands.handleCommandResponse(cmd, plist)
        elif plist['Status'] == 'Error' or plist['Status'] == 'CommandFormatError':
            cmd = DeviceCommand.objects.get(uuid=plist['CommandUUID'])
            cmd.status = DeviceCommand.FAILED
            cmd.date_completed = datetime.now()
            cmd.save()
        elif plist['Status'] == 'NotNow':
            cmd = DeviceCommand.objects.get(uuid=plist['CommandUUID'])
            cmd.status = DeviceCommand.PENDING
            cmd.attempts = 0
            cmd.save()

        if plist['Status'] == 'Idle' or plist['Status'] == 'Acknowledged':
            # Look for the next command, mark as failed if too many attempts.
            cmd = DeviceCommand.objects.filter(device=device, status__in=[DeviceCommand.PENDING, DeviceCommand.RUNNING]).first()
            while cmd and cmd.attempts >= 3:
                cmd.status = DeviceCommand.FAILED
                cmd.save()
                cmd = DeviceCommand.objects.filter(device=device, status__in=[DeviceCommand.PENDING, DeviceCommand.RUNNING]).first()

            # Run the next command.
            if cmd:
                data = commands.dataForCommand(cmd)
                responseData = plistlib.writePlistToString(data)
                cmd.status = DeviceCommand.RUNNING
                cmd.attempts += 1
                cmd.save()

    logger.debug('WWW Result: %s', responseData)

    response = HttpResponse(responseData, content_type = 'application/xml; charset=UTF-8')
    response['Content-Length'] = len(responseData)
    return response
Exemplo n.º 24
0
		continue
	
	name2addr[row["name"]] = row["address"]
	if row["lng"] and row["lat"]:
		name2pos[row["name"]] = (row["lng"], row["lat"])

rows = []
for row in csv.DictReader(codecs.open(sys.argv[1], encoding="UTF-8")):
	name = row["name"]
	addr = name2addr.get(name)
	pos = name2pos.get(name)
	
	if addr and pos:
		pass
	else:
		results = geo.geocode(name2addr.get(name, name))
		if geo.resolved(results):
			r = results[0]
			if not pos:
				pos = (r["geometry"]["location"]["lng"], r["geometry"]["location"]["lat"])
			
			if not addr:
				addr = r["formatted_address"]
		elif results:
			for r in results:
				logging.error("{0},{1}".format(name, r["formatted_address"]))
		else:
			logging.error([name, name2addr.get(name)])
	
	if addr and pos:
		row["住所"] = addr
Exemplo n.º 25
0
def add(request):
    def submit_form(form):
        return render_to_response("add.html", {"form": form}, context_instance=RequestContext(request))

    if request.method == "GET":
        if not request.user.is_authenticated():
            pass  # Ask the user if the want to sign on

        data = {}
        if "url" in request.GET:
            data.update({"url": request.GET["url"]})

        day = datetime.today()
        if "day" in request.GET:
            if request.GET["day"] != "":
                day = request.GET["day"]  # Javascript hands you Tue May 20 1990
                data.update({"date": day})
            else:
                data.update({"date": day.strftime("%a %b %d %Y")})
        else:
            data.update({"date": day.strftime("%a %b %d %Y")})

        start_time = datetime.today()
        start_time = start_time.strftime("%H:%M")
        if "start_time" in request.GET:
            if request.GET["start_time"] != "":
                start_time = request.GET["start_time"]

        data.update({"start_time": start_time})

        if "end_time" in request.GET:
            end_time = request.GET["end_time"]
            if end_time != "null":
                data.update({"end_time": end_time})

        data.update({"mail": "outlook"})

        form = EventForm(data)
        return submit_form(form)

    # Form was returned with data
    if request.method == "POST":
        form = EventForm(request.POST)
        if not form.is_valid():
            return submit_form(form)

        title = form.cleaned_data["title"]
        date = form.cleaned_data["date"]
        start_time = form.cleaned_data["start_time"]
        end_time = form.cleaned_data["end_time"]
        url = form.cleaned_data["url"]
        describe = form.cleaned_data["describe"]
        address = form.cleaned_data["address"]
        mail = form.cleaned_data["mail"]

        latitude = None
        longitude = None

        if address != u"":
            local = geocode(address)
            if local != None:
                if "address" in local:
                    address = local["address"]

                if "latitude" in local and "longitude" in local:
                    latitude = local["latitude"]
                    longitude = local["longitude"]

        # If they move the pointer to be more specific override address
        """
        if form.data['lati'] and form.data['lngi']:
            latitude = form.data['lati']
            longitude = form.data['lngi']
        """
        event = EventModel(
            title=title,
            date=date,
            start_time=start_time,
            end_time=end_time,
            address=address,
            longitude=longitude,
            latitude=latitude,
            description=describe,
            url=url,
        )
        # Save this event
        event.save()

        # Make sure you save the event before connecting it to a user
        if request.user.is_authenticated():
            event.connect(request.user)

        # Ical or Outlook iCal file
        if mail == "outlook" or mail == "ical":
            # Create the iCal file
            cal = Calendar()
            cal.add("version", "2.0")
            cal.add("prodid", "-//Microsoft Corporation//Windows Calendar 1.0//EN")
            cal.add("method", "PUBLISH")

            event = Event()
            event.add("summary", describe)
            if start_time != None:
                dt = datetime.combine(date, start_time)
            else:
                dt = date
            event.add("dtstart", dt)
            event.add("dtstamp", dt)

            if end_time != None:
                de = datetime.combine(date, end_time)
                event.add("dtend", de)

            g = (latitude, latitude)
            event.add("geo", g)
            event.add("location", address)

            uid = date.isoformat() + "@wenzit.net"
            event.add("UID", uid)
            event.add("url", url)
            cal.add_component(event)

            f = open("schedule.ics", "wb")
            f.write(cal.as_string())
            f.close()

            response = HttpResponse(cal.as_string(), mimetype="text/calendar")
            response["Content-Disposition"] = "attachment; filename=schedule.ics"

            return response

        # Send the event to google
        elif mail == "google":
            response = "http://www.google.com/calendar/event?action=TEMPLATE"
            response += "&text=" + urllib.quote_plus(title)

            if start_time != None:
                ds = datetime.combine(date, start_time)
            else:
                ds = date

            if end_time != None:
                de = datetime.combine(date, end_time)
                response += "&dates=" + vDatetime(ds).ical() + "/" + vDatetime(de).ical()
            else:
                response += "&dates=" + vDatetime(ds).ical()

            response += "&details=" + urllib.quote_plus(title)
            response += "&location=" + urllib.quote_plus(address)
            response += "&sprop=" + urllib.quote_plus(url)
            return HttpResponseRedirect(response)

        # Send the event to Yahoo
        if mail == "yahoo":
            response = "http://calendar.yahoo.com/?v=60"
            response += "&TITLE=" + urllib.quote_plus(title)

            ds = datetime.combine(date, start_time)
            if end_time:
                de = datetime.combine(date, end_time)
                dur = de - ds
                hrs, left = divmod(dur.seconds, 3600)
                mins, secs = divmod(left, 60)
                dur = "%02d%02d" % (hrs, mins)
            else:
                dur = ""

            response += "&ST=" + vDatetime(ds).ical()
            response += "&DUR=" + dur

            response += "&in_loc=" + urllib.quote_plus(address)
            response += "&DESC=" + urllib.quote_plus(title)
            response += "&URL=" + urllib.quote_plus(url)
            return HttpResponseRedirect(response)
Exemplo n.º 26
0
def checkin(request):
    logger = logging.getLogger('django')
    logger.debug('WWW Query: %s', request.body)

    if settings.USE_CERTIFICATE == True:
        # Get the certificate fingerprint
        try:
            bio = BIO.MemoryBuffer(
                base64.b64decode(request.META['HTTP_MDM_SIGNATURE']))
            p7 = SMIME.PKCS7(m2.pkcs7_read_bio_der(bio._ptr()), 1)
            stk = X509.X509_Stack()
            sk3 = p7.get0_signers(stk)
            cert = sk3.pop()
            fingerprint = cert.get_fingerprint('md5')
            if len(fingerprint) == 31:
                fingerprint = '0' + fingerprint
        except:
            fingerprint = None

        logger.debug('Fingerprint: %s', fingerprint)
        # If no certificate supplied, permission denied.
        if fingerprint == None and settings.REQUIRE_CERTIFICATE == True:
            return HttpResponseForbidden()

        # If no certificate found, permission denied.
        certificate = Certificate.objects.filter(md5=fingerprint).first()
        if certificate == None and settings.REQUIRE_CERTIFICATE == True:
            return HttpResponseForbidden()

        # If certificate does not match device, permission denied.
        # TODO
    else:
        certificate = None

    # Prepare handling of checkin request and response commands.
    responseData = plistlib.writePlistToString(dict())
    standard_commands.initialize()

    try:
        plist = plistlib.readPlistFromString(request.body)
    except:
        plist = dict()

    if 'MessageType' in plist:
        if plist['MessageType'] == 'Authenticate':
            if 'UserID' in plist:
                return HttpResponseBadRequest(
                    'User binding not currently supported')

            device = Device.objects.filter(udid=plist['UDID']).first()
            if device == None:
                device = Device(udid=plist['UDID'], push_topic=plist['Topic'])
            device.last_checkin = datetime.now()
            device.last_notification = datetime.now()
            device.save()
            if certificate != None:
                certificate.device = device
                certificate.save()

            try:
                group = DeviceGroup.objects.filter(
                    uuid=settings.DEFAULT_DEVICE_GROUP).first()
                group.devices.add(device)
                group.save()
            except:
                pass

        elif plist['MessageType'] == 'TokenUpdate':
            if 'UserID' in plist:
                return HttpResponseBadRequest(
                    'User binding not currently supported')

            device = Device.objects.get(udid=plist['UDID'])
            device.push_topic = plist['Topic']
            device.push_token = plist['Token'].asBase64(maxlinelength=8000)
            device.push_magic = plist['PushMagic']
            device.last_checkin = datetime.now()
            device.save()

            DeviceCommand.NewDeviceInformation(device)
            DeviceCommand.NewProfileList(device)
            DeviceCommand.NewInstalledApplicationList(device)
            push.push_notification(device)
        elif plist['MessageType'] == 'CheckOut':
            if 'UserID' in plist:
                return HttpResponseBadRequest(
                    'User binding not currently supported')

            Device.objects.get(udid=plist['UDID']).delete()
        else:
            print 'Unknown message type: ' + plist['MessageType']
            print plist
    elif 'Status' in plist:
        responseData = ''

        # Update device checkin time
        device = Device.objects.get(udid=plist['UDID'])
        device.last_checkin = datetime.now()
        device.save()

        # Update device location if it has been 15 minutes since last.
        since = datetime.now() - timedelta(minutes=15)
        location = DeviceCheckin.objects.filter(
            device=device).order_by('-end_date').first()
        if location and location.ip == request.META['REMOTE_ADDR']:
            location.end_date = datetime.now()
            location.save()
        else:
            location = DeviceCheckin(device=device)
            location.start_date = datetime.now()
            location.end_date = datetime.now()
            location.ip = request.META['REMOTE_ADDR']
            loc = geo.geocode(request.META['REMOTE_ADDR'])
            location.latitude = loc['latitude']
            location.longitude = loc['longitude']
            location.country_code = loc['country_code']
            location.region_code = loc['region_code']
            location.city = loc['city']
            if 'country_name' in loc:
                location.country_name = loc['country_name']
            if 'region_name' in loc:
                location.region_name = loc['region_name']
            location.save()

        if plist['Status'] == 'Acknowledged':
            cmd = DeviceCommand.objects.get(uuid=plist['CommandUUID'])
            cmd.status = DeviceCommand.SUCCESS
            cmd.date_completed = datetime.now()
            cmd.save()
            commands.handleCommandResponse(cmd, plist)
        elif plist['Status'] == 'Error' or plist[
                'Status'] == 'CommandFormatError':
            cmd = DeviceCommand.objects.get(uuid=plist['CommandUUID'])
            cmd.status = DeviceCommand.FAILED
            cmd.date_completed = datetime.now()
            cmd.save()
        elif plist['Status'] == 'NotNow':
            cmd = DeviceCommand.objects.get(uuid=plist['CommandUUID'])
            cmd.status = DeviceCommand.PENDING
            cmd.attempts = 0
            cmd.save()

        if plist['Status'] == 'Idle' or plist['Status'] == 'Acknowledged':
            # Look for the next command, mark as failed if too many attempts.
            cmd = DeviceCommand.objects.filter(
                device=device,
                status__in=[DeviceCommand.PENDING,
                            DeviceCommand.RUNNING]).first()
            while cmd and cmd.attempts >= 3:
                cmd.status = DeviceCommand.FAILED
                cmd.save()
                cmd = DeviceCommand.objects.filter(
                    device=device,
                    status__in=[DeviceCommand.PENDING,
                                DeviceCommand.RUNNING]).first()

            # Run the next command.
            if cmd:
                data = commands.dataForCommand(cmd)
                responseData = plistlib.writePlistToString(data)
                cmd.status = DeviceCommand.RUNNING
                cmd.attempts += 1
                cmd.save()

    logger.debug('WWW Result: %s', responseData)

    response = HttpResponse(responseData,
                            content_type='application/xml; charset=UTF-8')
    response['Content-Length'] = len(responseData)
    return response
Exemplo n.º 27
0
    for keyword in article['keywords']:

        country_id = None
        level_1_id = None
        level_2_id = None
        locality_id = None

        if keyword['name'] == 'glocations':

            print
            print keyword['value']

            try:

                location = geocode(keyword['value'])

            except Exception, e:

                print article_id, title, e
                continue

            print location
            print

            if location['country']:

                country = db.select('countries',
                                    vars={
                                        'name': location['country']
                                    },
Exemplo n.º 28
0
def add(request):
    def submit_form(form):
        return render_to_response('add.html', {'form': form},
                                  context_instance=RequestContext(request))

    if request.method == 'GET':
        if not request.user.is_authenticated():
            pass  # Ask the user if the want to sign on

        data = {}
        if 'url' in request.GET:
            data.update({'url': request.GET['url']})

        day = datetime.today()
        if 'day' in request.GET:
            if request.GET['day'] != "":
                day = request.GET[
                    'day']  # Javascript hands you Tue May 20 1990
                data.update({'date': day})
            else:
                data.update({'date': day.strftime('%a %b %d %Y')})
        else:
            data.update({'date': day.strftime('%a %b %d %Y')})

        start_time = datetime.today()
        start_time = start_time.strftime('%H:%M')
        if 'start_time' in request.GET:
            if request.GET['start_time'] != '':
                start_time = request.GET['start_time']

        data.update({'start_time': start_time})

        if 'end_time' in request.GET:
            end_time = request.GET['end_time']
            if end_time != 'null':
                data.update({'end_time': end_time})

        data.update({'mail': 'outlook'})

        form = EventForm(data)
        return submit_form(form)

    # Form was returned with data
    if request.method == 'POST':
        form = EventForm(request.POST)
        if not form.is_valid():
            return submit_form(form)

        title = form.cleaned_data['title']
        date = form.cleaned_data['date']
        start_time = form.cleaned_data['start_time']
        end_time = form.cleaned_data['end_time']
        url = form.cleaned_data['url']
        describe = form.cleaned_data['describe']
        address = form.cleaned_data['address']
        mail = form.cleaned_data['mail']

        latitude = None
        longitude = None

        if address != u'':
            local = geocode(address)
            if local != None:
                if 'address' in local:
                    address = local['address']

                if 'latitude' in local and 'longitude' in local:
                    latitude = local['latitude']
                    longitude = local['longitude']

        # If they move the pointer to be more specific override address
        """
        if form.data['lati'] and form.data['lngi']:
            latitude = form.data['lati']
            longitude = form.data['lngi']
        """
        event = EventModel(title=title,
                           date=date,
                           start_time=start_time,
                           end_time=end_time,
                           address=address,
                           longitude=longitude,
                           latitude=latitude,
                           description=describe,
                           url=url)
        # Save this event
        event.save()

        # Make sure you save the event before connecting it to a user
        if request.user.is_authenticated():
            event.connect(request.user)

        # Ical or Outlook iCal file
        if mail == 'outlook' or mail == 'ical':
            # Create the iCal file
            cal = Calendar()
            cal.add('version', '2.0')
            cal.add('prodid',
                    '-//Microsoft Corporation//Windows Calendar 1.0//EN')
            cal.add('method', 'PUBLISH')

            event = Event()
            event.add('summary', describe)
            if start_time != None:
                dt = datetime.combine(date, start_time)
            else:
                dt = date
            event.add('dtstart', dt)
            event.add('dtstamp', dt)

            if end_time != None:
                de = datetime.combine(date, end_time)
                event.add('dtend', de)

            g = (latitude, latitude)
            event.add('geo', g)
            event.add('location', address)

            uid = date.isoformat() + '@wenzit.net'
            event.add('UID', uid)
            event.add('url', url)
            cal.add_component(event)

            f = open('schedule.ics', 'wb')
            f.write(cal.as_string())
            f.close()

            response = HttpResponse(cal.as_string(), mimetype='text/calendar')
            response[
                'Content-Disposition'] = 'attachment; filename=schedule.ics'

            return response

        # Send the event to google
        elif mail == 'google':
            response = "http://www.google.com/calendar/event?action=TEMPLATE"
            response += "&text=" + urllib.quote_plus(title)

            if start_time != None:
                ds = datetime.combine(date, start_time)
            else:
                ds = date

            if end_time != None:
                de = datetime.combine(date, end_time)
                response += "&dates=" + vDatetime(ds).ical()+ \
                            '/'+vDatetime(de).ical()
            else:
                response += "&dates=" + vDatetime(ds).ical()

            response += "&details=" + urllib.quote_plus(title)
            response += "&location=" + urllib.quote_plus(address)
            response += "&sprop=" + urllib.quote_plus(url)
            return HttpResponseRedirect(response)

        # Send the event to Yahoo
        if mail == 'yahoo':
            response = 'http://calendar.yahoo.com/?v=60'
            response += '&TITLE=' + urllib.quote_plus(title)

            ds = datetime.combine(date, start_time)
            if end_time:
                de = datetime.combine(date, end_time)
                dur = de - ds
                hrs, left = divmod(dur.seconds, 3600)
                mins, secs = divmod(left, 60)
                dur = '%02d%02d' % (hrs, mins)
            else:
                dur = ''

            response += '&ST=' + vDatetime(ds).ical()
            response += '&DUR=' + dur

            response += '&in_loc=' + urllib.quote_plus(address)
            response += '&DESC=' + urllib.quote_plus(title)
            response += '&URL=' + urllib.quote_plus(url)
            return HttpResponseRedirect(response)