Exemple #1
0
def register(self, **kw):
    try:
        secret = request.args.get("secret")
        url = request.args.get("url")

        if sha1(secret).hexdigest() == SECRET_HASH and url:
            s = Setting.all().filter("name =", "update.url").get()
            if not s is None:
                s.value = url
                s.put()
            else:
                s = Setting(name="update.url", value=url)
                s.put()
            memcache.set(key="update.url", value=serialize_entities(url), time=CACHE_TIME * 24)
            logging.info("New url recieved: %s" % url)
        return Response("URL recieved.")
    except db.Timeout:
        msg = "\nUrl was not saved. The database timed out."
        logging.error(msg)
        return Response(msg, status=500)
    except CapabilityDisabledError:
        msg = "\nUrl was not saved. Database could not be written to."
        logging.error(msg)
        return Response(msg, status=500)
    except TransactionFailedError:
        msg = "\nUrl was not saved. Transaction failed."
        logging.error(msg)
        return Response(msg, status=500)
    except Exception, e:
        if DEBUG:
            print_exc()
        logging.error(str(e))
        return Response("\nUrl was not saved. %s." % e, status=500)
Exemple #2
0
def user():
    user_key = request.headers.get("X-SecondLife-Owner-Key")
    user_name = request.headers.get("X-SecondLife-Owner-Name")
    version = request.args.get("version")
    user_name_ = request.args.get("username")

    if user_name != user_name_:
        user_name = user_name_

    if not version or version < VERSION:
        send_update(user_name, user_key)
        if MANDATORY:
            return Response("Your Navigator is outdated, I'm sending you version %s." % VERSION, status=406)
        else:
            return Response("Your Navigator is outdated, I'm sending you version %s." % VERSION)

    user = User.get_or_insert(user_key, name=user_name)
    if not user is None:
        if user.name != user_name:
            user.name = user_name

        user.uuid = uuid4().hex
        user.put()
        memcache.set(key="user-%s" % user_key, value=serialize_entities(user), time=CACHE_TIME)
        return Response("Connected. Your navigator is up-to-date.")
    else:
        return Response("Unable to create a new user. Try rezzinga a new HUD.", status=500)
Exemple #3
0
def setstate():
    try:
        user_key = request.headers.get("X-SecondLife-Owner-Key")
        user = get_user(user_key)
        state = request.args.get("state")
        course_id = request.args.get("courseid")

        course = Course.get(Key(course_id))

        s = State(parent=user, course=course, state=state, started=datetime.now())
        s.put()
        memcache.set(key="state-%s" % user_key, value=serialize_entities(s), time=CACHE_TIME)
        return Response()
    except db.Timeout:
        msg = "\nState was not saved. The database timed out."
        logging.error(msg)
        return Response(msg, status=500)
    except CapabilityDisabledError:
        msg = "\nState was not saved. Database could not be written to."
        logging.error(msg)
        return Response(msg, status=500)
    except TransactionFailedError:
        msg = "\nState was not saved. Transaction failed."
        logging.error(msg)
        return Response(msg, status=500)
    except Exception, e:
        if DEBUG:
            print_exc()
        logging.error(str(e))
        return Response("\nState was not saved. %s." % e, status=500)
Exemple #4
0
def updatestate():
    try:
        user_key = request.headers.get("X-SecondLife-Owner-Key")
        user = get_user(user_key)
        button = int(request.args.get("button", 0))

        s = get_state(user)
        if not s is None and button:
            lm = len(s.course.marks)
            if button == PREVIOUS and s.mark > 0:
                s.mark -= 1
            elif button == NEXT and s.mark < lm - 1:
                s.mark += 1

            s.started = datetime.now()
            s.put()
            memcache.set(key="state-%s" % user_key, value=serialize_entities(s), time=CACHE_TIME)
            mark = Mark.get(s.course.marks[s.mark])
            turn = s.course.turns[s.mark]
            if mark.name:
                msg = "\n%s\nMark %d of %d. %s\n%s" % (
                    mark.name,
                    s.mark + 1,
                    lm,
                    TURNSD[turn] if turn in TURNSD else "missing turn",
                    mark.comment if mark.comment else "",
                )
            else:
                msg = "\nMark %d of %d. %s\n%s" % (
                    s.mark + 1,
                    lm,
                    TURNSD[turn] if turn in TURNSD else "missing turn",
                    mark.comment if mark.comment else "",
                )
            return Response(",".join((str(s.mark), str(mark.x), str(mark.y), mark.region.name, turn, msg)))
        else:
            return Response(status=204)
    except db.Timeout:
        msg = "\nState was not updated. The database timed out."
        logging.error(msg)
        return Response(msg, status=500)
    except CapabilityDisabledError:
        msg = "\nState was not updated. Database could not be written to."
        logging.error(msg)
        return Response(msg, status=500)
    except TransactionFailedError:
        msg = "\nState was not updated. Transaction failed."
        logging.error(msg)
        return Response(msg, status=500)
    except Exception, e:
        if DEBUG:
            print_exc()
        logging.error(str(e))
        return Response("\nState was not updated. %s." % e, status=500)
Exemple #5
0
def regioncourses():
    region_name, _, _ = get_region(request.headers.get("X-SecondLife-Region"))
    user_key = request.headers.get("X-SecondLife-Owner-Key")
    user = get_user(user_key)
    region = Region.get_by_key_name(region_name)

    if not region is None:
        query = BlacklistUser.all(keys_only=True)
        query.ancestor(user)
        bl_users = [n for n in query]

        query = BlacklistCourse.all(keys_only=True)
        query.ancestor(user)
        bl_courses = [n for n in query]

        all_courses = []
        query = Course.all()
        query.ancestor(region.key())
        query.filter("saved =", True)
        query.filter("deactivated =", False)
        query.filter("public =", False)
        query.filter("user ="******"name")
        for course in query:
            all_courses.append(
                "%s (%s by %s, private);%s" % (course.name, course.type.lower(), course.user.name, str(course.key()))
            )

        courses = deserialize_entities(memcache.get("regioncourses-%s" % region_name))
        if courses is None:
            query = Course.all()
            query.ancestor(region.key())
            query.filter("saved =", True)
            query.filter("deactivated =", False)
            query.filter("public =", True)
            query.order("name")
            courses = [course for course in query]
            memcache.set(key="regioncourses-%s" % region_name, value=serialize_entities(courses), time=CACHE_TIME * 6)

        for course in courses:
            if course.user.key() not in bl_users and course.key() not in bl_courses:
                all_courses.append(
                    "%s (%s by %s);%s" % (course.name, course.type.lower(), course.user.name, str(course.key()))
                )

        if all_courses:
            return Response(";".join(all_courses))

    msg = "\nThere are no courses for region %s." % region_name
    regions = Region.all().filter("course_count >", 0).order("-course_count").fetch(10)
    msg += "\nTry one of these regions instead:\n" + "\n".join(["http://" + quote(sl_url % r.name) for r in regions])
    return Response(msg, status=406)
Exemple #6
0
def getstate():
    user_key = request.headers.get("X-SecondLife-Owner-Key")
    user = get_user(user_key)

    s = get_state(user)
    if not s is None:
        state = "editing" if s.state == "EDIT" else "sailing"
        msg = "\nYou were %s course %s from region %s a while ago, would you like to continue?" % (
            state,
            s.course.name,
            s.course.start_region.name,
        )
        memcache.set(key="state-%s" % user_key, value=serialize_entities(s), time=CACHE_TIME)
        return Response(";".join((msg, s.state, s.course.name, str(s.mark), str(s.course.key()))))
    else:
        return Response(status=204)
Exemple #7
0
        def txn():
            region = Region.get_by_key_name(region_name)
            if region is None:
                region = Region(key_name=region_name, name=region_name, cx=cx, cy=cy)
                region.put()

            course = Course(
                name=course_name,
                parent=region.key(),
                start_region=region,
                user=user.key(),
                public=access == "PUBLIC",
                type=type,
            )

            course.put()
            memcache.set(key="course-%s" % user_key, value=serialize_entities(course), time=CACHE_TIME)
Exemple #8
0
def course():
    course_key = request.args.get("courseid")
    region_name, _, _ = get_region(request.headers.get("X-SecondLife-Region"))
    region = Region.get_by_key_name(region_name)

    if not region is None and course_key:
        course = deserialize_entities(memcache.get("course-%s" % course_key))
        if course is None:
            course = Course.get(course_key)
            memcache.set(key="course-%s" % course_key, value=serialize_entities(course), time=CACHE_TIME)
        if not course is None:
            if course.comment:
                return Response("\nAbout this course:\n" + course.comment)
            else:
                return Response()
        else:
            return Response("\nCourse not found.", status=404)
    else:
        return Response("\nCourse not found.", status=404)
Exemple #9
0
def send_update(user_name, user_key):
    try:
        url = deserialize_entities(memcache.get("update.url"))
        if url is None:
            url = Setting.all().filter("name =", "update.url").get()
            memcache.set(key="update.url", value=serialize_entities(url), time=CACHE_TIME * 24)
        result = urlfetch.fetch(
            url,
            payload=urlencode([("userkey", user_key), ("product", PRODUCT), ("version", VERSION)]),
            method=urlfetch.POST,
        )
        if result.status_code == 200:
            logging.info("Update %s sent to %s" % (VERSION, user_name))
        else:
            logging.error(
                "Update %s for user %s, %s failed with status_code %d."
                % (VERSION, user_name, user_key, result.status_code)
            )
    except Exception:
        if DEBUG:
            print_exc()
        logging.error("Update %s for user %s, %s failed." % (VERSION, user_name, user_key))
Exemple #10
0
def export(mine=0, uuid=""):
    user_key = request.headers.get("X-SecondLife-Owner-Key")
    user = get_user(user_key) if not user_key is None else None

    if not user is None:
        csv = deserialize_entities(memcache.get("csv-user_key-%d-%s" % (mine, user_key)))
        if not csv is None:
            #            logging.info("csv-user_key-%d-%s" % (mine, user_key))
            #            logging.info("using cache: user_key")
            return Response(url_for("export", _external=True, mine=str(mine), uuid=user.uuid))

    if uuid:
        csv = deserialize_entities(memcache.get("csv-uuid-%d-%s" % (mine, uuid)))
        if not csv is None:
            #            logging.info("csv-uuid-%d-%s" % (mine, uuid))
            #            logging.info("using cache: uuid")
            return Response(csv, mimetype="application/excel")
        else:
            return Response(status=204)

    #    logging.info("not using cache: %d %s" % (mine, uuid))

    query = Course.all()
    query.filter("saved =", True)
    query.filter("deactivated =", False)
    if mine:
        query.filter("user = "******"public =", True)

    marks = {}
    buffer = StringIO()
    w = writer(buffer, delimiter=";")
    w.writerow(
        (
            "Region",
            "Name",
            "Comment",
            "Creator",
            "Creator key",
            "Created",
            "Last modified",
            "Public",
            "Type",
            "Mark: Region, Turn, Name, Comment, Local x, Local y, Global x, Gobal y, Created",
        )
    )

    for course in query:
        row = [
            course.start_region.name,
            course.name,
            course.comment,
            course.user.name,
            course.user.key().name(),
            course.created.strftime("%Y-%m-%d %H:%M:%S"),
            course.last_modified.strftime("%Y-%m-%d %H:%M:%S"),
            "Yes" if course.public else "No",
            course.type.capitalize(),
        ]

        for i, mkey in enumerate(course.marks):
            if mkey in marks:
                mark = marks[mkey]
            else:
                mark = Mark.get(mkey)
                marks[mark.key()] = mark
            row.append(
                ",".join(
                    (
                        mark.region.name,
                        course.turns[i],
                        mark.name or "",
                        mark.comment or "",
                        str(mark.x),
                        str(mark.y),
                        str(mark.gx),
                        str(mark.gy),
                        mark.created.strftime("%Y-%m-%d %H:%M:%S"),
                    )
                )
            )
        w.writerow(row)

    value = serialize_entities(buffer.getvalue())
    memcache.set_multi(
        {"user_key-%d-%s" % (mine, user_key): value, "uuid-%d-%s" % (mine, user.uuid): value},
        key_prefix="csv-",
        time=CACHE_TIME * 24,
    )

    #    logging.info(url_for("export", _external=True, mine=str(mine), uuid=user.uuid))
    return Response(url_for("export", _external=True, mine=str(mine), uuid=user.uuid))
Exemple #11
0
def addmark():
    try:
        user_key = request.headers.get("X-SecondLife-Owner-Key")
        user = get_user(user_key)
        region_name, cx, cy = get_region(request.headers.get("X-SecondLife-Region"))
        x, y = get_position(request.headers.get("X-SecondLife-Local-Position"))
        turn = request.args.get("turn")
        n = int(request.args.get("n", 0))

        course = deserialize_entities(memcache.get("course-%s" % user_key))
        if course is None:
            query = Course.all()
            query.filter("user ="******"saved =", False)
            query.filter("deactivated =", False)
            course = query.get()
            if not course:
                return Response("Course was not saved, something went wrong.", status=406)

        gx = cx + x
        gy = cy + y
        region = Region.get_or_insert(region_name, name=region_name, cx=cx, cy=cy)
        msg = check_new_mark(region, course, turn, n, gx, gy)
        if msg:
            return Response(msg, status=406)

        marks = deserialize_entities(memcache.get("marks-%s" % user_key))
        if marks is None:
            query = Mark.all()
            query.ancestor(user.key())
            query.filter("region =", region)
            query.filter("deactivated =", False)
            marks = [m for m in query]
            memcache.set(key="marks-%s" % user_key, value=serialize_entities(marks), time=CACHE_TIME)

        close_marks = sorted(
            [(m, dist(gx, gy, m.gx, m.gy)) for m in marks if close(gx, gy, m.gx, m.gy)], key=lambda o: o[1]
        )

        if close_marks:
            mark = close_marks[0][0]
            mark.used += 1
            mark.put()
        else:
            mark = Mark(region=region, x=x, y=y, gx=gx, gy=gy, parent=user.key())
            mark.put()
        course.marks.append(mark.key())
        course.turns.append(turn)
        course.put()

        if not marks is None:
            marks.append(mark)
        else:
            marks = [mark]
        memcache.set(key="marks-%s" % user_key, value=serialize_entities(marks), time=CACHE_TIME)
        memcache.set(key="course-%s" % user_key, value=serialize_entities(course), time=CACHE_TIME)

        if turn == "START":
            s = "\nStart mark saved. Go to the next mark and click the HUD."
        elif turn == "FINISH":
            s = "\nFinish mark saved."
        else:
            s = "\nMark %d saved. Go to the next mark and click the HUD." % len(course.marks)

        if close_marks:
            d = dist(gx, gy, mark.gx, mark.gy)
            return Response(s + " This mark was merged with a predefined mark %.1fm. away." % round(d, 1))
        else:
            return Response(s)
    except db.Timeout:
        msg = "\nMark was not saved. The database timed out."
        logging.error(msg)
        return Response(msg, status=500)
    except CapabilityDisabledError:
        msg = "\nMark was not saved. Database could not be written to."
        logging.error(msg)
        return Response(msg, status=500)
    except TransactionFailedError:
        msg = "\nMark was not saved. Transaction failed."
        logging.error(msg)
        return Response(msg, status=500)
    except Exception, e:
        if DEBUG:
            print_exc()
        logging.error(e)
        return Response("\nMark was not saved. %s." % e, status=500)