Exemple #1
0
def check_new_mark(region, course, turn, n, gx, gy):
    if course is None:
        return "\nMark was not saved, invalid course"

    if not turn in TURNS:
        return "\nMark was not saved, invalid turn."

    if turn == "START" and region.key() != course.start_region.key():
        return "\nMark was not saved, the start mark must be in the region of the course."

    if len(course.marks) > 0 and n == 0:
        next_mark = Mark.get(course.marks[n + 1])
        if close(gx, gy, next_mark.gx, next_mark.gy):
            return "\nMark %d was not saved, it is too close to mark %d. Please try again." % (n, n + 1)
    elif len(course.marks) > 0 and len(course.marks) == n:
        last_mark = Mark.get(course.marks[n - 1])
        if close(gx, gy, last_mark.gx, last_mark.gy):
            return "\nMark %d was not saved, it is too close to mark %d. Please try again." % (n + 1, n)
    elif len(course.marks) > n > 0:
        last_mark = Mark.get(course.marks[n - 1])
        next_mark = Mark.get(course.marks[n + 1])
        if close(gx, gy, last_mark.gx, last_mark.gy):
            return "Mark %d was not saved, it is too close to mark %d. Please try again." % (n + 1, n)
        if close(gx, gy, next_mark.gx, next_mark.gy):
            return "Mark %d was not saved, it is too close to mark %d. Please try again." % (n, n - 1)
Exemple #2
0
 def post(self, mid):
     
     try:
         mark = Mark.get(id = mid)
     except:
         self.flash("此地址不存在")
         self.redirect("/user/marks")
         return
     
     nickname = self.get_argument("nickname", None)
     name = self.get_argument("name", None)
     relation = int(self.get_argument("relation", 0))
     gender = int(self.get_argument("gender", 0))
     day = self.get_argument("day", datetime.date.today() + datetime.timedelta(days=1))
     mobile = self.get_argument("mobile", None)
     
     if nickname and name and mobile and vmobile(mobile):
         user = self.get_current_user()
         mark.nickname = nickname
         mark.name = name
         mark.relation = relation
         mark.gender = gender
         mark.day = day
         mark.mobile = mobile
             
         try:
             Mark.get(id != mark.id, uid = user.uid, nickname = nickname)
             self.flash("此纪念日已存在")
         except:
             try:
                 mark.save()
                 self.flash("保存成功", 'sucess')
             except Exception, ex:
                 logging.error(ex)
                 self.flash("系统出错,请稍后重试")
Exemple #3
0
 def post(self, mid):
     
     try:
         mark = Mark.get(id = mid)
     except:
         self.flash("此地址不存在")
         self.redirect("/user/marks")
         return
     
     nickname = self.get_argument("nickname", None)
     name = self.get_argument("name", None)
     relation = int(self.get_argument("relation", 0))
     gender = int(self.get_argument("gender", 0))
     day = self.get_argument("day", datetime.date.today() + datetime.timedelta(days=1))
     mobile = self.get_argument("mobile", None)
     
     if nickname and name and mobile and vmobile(mobile):
         user = self.get_current_user()
         mark.nickname = nickname
         mark.name = name
         mark.relation = relation
         mark.gender = gender
         mark.day = day
         mark.mobile = mobile
             
         try:
             Mark.get(id != mark.id, uid = user.uid, nickname = nickname)
             self.flash("此纪念日已存在")
         except:
             try:
                 mark.save()
                 self.flash("保存成功", 'sucess')
             except Exception, ex:
                 logging.error(ex)
                 self.flash("系统出错,请稍后重试")
Exemple #4
0
def course_length(course):
    distance = 0.0
    marks = {}
    for i in range(len(course.marks) - 1):
        mark1 = marks.get(course.marks[i], None) or Mark.get(course.marks[i])
        mark2 = marks.get(course.marks[i + 1], None) or Mark.get(course.marks[i + 1])
        distance += dist(mark1.gx, mark1.gy, mark2.gx, mark2.gy)
    return distance
Exemple #5
0
    def get(self):
        user = self.get_current_user()

        page = int(self.get_argument("page", 1))
        pagesize = self.settings['admin_pagesize']

        mq = Mark.select().where(Mark.uid == user.id)
        total = mq.count()
        marks = mq.paginate(page, pagesize)

        self.render('user/mark.html',
                    marks=marks,
                    total=total,
                    page=page,
                    pagesize=pagesize,
                    mark=Mark(day=datetime.date.today() +
                              datetime.timedelta(days=1)))
Exemple #6
0
 def get(self, mid):
     try:
         mark = Mark.get(id = mid)
     except:
         self.flash("此地址不存在")
         self.redirect("/user/marks")
         return
     
     user = self.get_current_user()
     
     page = int(self.get_argument("page", 1))
     pagesize = self.settings['admin_pagesize']
     
     mq = Mark.select().where(Mark.uid == user.id)
     total = mq.count()
     marks = mq.paginate(page, pagesize)
     
     self.render('user/mark.html', marks = marks, total = total, page = page, pagesize = pagesize, mark = mark)
Exemple #7
0
def deactivate_course(course):
    dm = 0
    for mkey in course.marks:
        mark = Mark.get(mkey)
        dm += dec_mark(mark)
    course.deactivated = True
    course.parent().course_count -= 1
    course.put()
    return dm
Exemple #8
0
 def get(self, mid):
     try:
         mark = Mark.get(id = mid)
     except:
         self.flash("此地址不存在")
         self.redirect("/user/marks")
         return
     
     user = self.get_current_user()
     
     page = int(self.get_argument("page", 1))
     pagesize = self.settings['admin_pagesize']
     
     mq = Mark.select().where(Mark.uid == user.id)
     total = mq.count()
     marks = mq.paginate(page, pagesize)
     
     self.render('user/mark.html', marks = marks, total = total, page = page, pagesize = pagesize, mark = mark)
Exemple #9
0
 def get(self):
     user = self.get_current_user()
     
     page = int(self.get_argument("page", 1))
     pagesize = self.settings['admin_pagesize']
     
     mq = Mark.select().where(Mark.uid == user.id)
     total = mq.count()
     marks = mq.paginate(page, pagesize)
     
     self.render('user/mark.html', marks = marks, total = total, page = page, pagesize = pagesize, mark = Mark(day = datetime.date.today() + datetime.timedelta(days=1)))
Exemple #10
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 #11
0
def savecourse():
    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"))
        region = Region.get_or_insert(region_name, name=region_name, cx=cx, cy=cy)

        course = deserialize_entities(memcache.get("course-" + 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)

        course.end_region = region
        marks = []
        for key in course.marks:
            mark = Mark.get(key)
            mark.saved = True
            marks.append(mark)
        db.put(marks)

        course.length = course_length(course)
        course.saved = True
        course.put()
        memcache.delete("course-" + user.key().name())
        return Response("\nCourse %s saved." % course.name)
    except db.Timeout:
        msg = "New course failed. The database timed out."
        logging.error(msg, status=500)
        return Response(msg)
    except CapabilityDisabledError:
        msg = "New course failed. Database could not be written to."
        logging.error(msg)
        return Response(msg, status=500)
    except TransactionFailedError:
        msg = "New course failed. Transaction failed."
        logging.error(msg)
        return Response(msg, status=500)
    except Exception, e:
        logging.error(str(e))
        if DEBUG:
            print_exc()
        return Response("New course failed.", status=500)
Exemple #12
0
 def get(self, mid):
     user = self.get_current_user()
     Mark.delete().where(Mark.uid == user.id, Mark.id == mid).execute()
     self.flash("删除成功")
     self.redirect("/user/marks")
Exemple #13
0
 def get(self, mid):
     user = self.get_current_user()
     Mark.delete().where(Mark.uid == user.id, Mark.id == mid).execute()
     self.flash("删除成功")
     self.redirect("/user/marks")
Exemple #14
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 #15
0
def edit():
    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"))
        region = Region.get_or_insert(region_name, cx=cx, cy=cy)
        course_key = request.args.get("coursekey")
        action = request.args.get("action")
        course_name = request.args.get("coursename")
        mark_name = request.args.get("markname")
        mark = request.args.get("mark")
        turn = request.args.get("turn")
        comment = request.args.get("comment")

        if action in ("REPLM", "ADDM") and mark:
            x, y, _ = vector2floats(mark)
            gx = cx + x
            gy = cy + y

        course = Course.get(Key(course_key))
        if course is None or course.user.key() != user.key():
            return Response("\nSomething went wrong, course was not modified.")

        now = datetime.now()
        state = get_state(user)
        if state is None:
            raise ValueError("State missing!")

        memcache.delete("regioncourses-%s" % region_name)
        memcache.delete("course-%s" % course_key)
        i = state.mark
        if action == "DELC":
            deleted = deactivate_course(course)
            return Response("Course %s deleted. %d unused marks deleted." % (course.name, deleted))
        elif action == "RENC" and course_name:
            old_name = course.name
            course.name = course_name.strip()
            course.last_modified = now
            course.put()
            return Response("\nCourse %s was renamed to %s." % (old_name, course.name))
        elif action == "TPP":
            course.public = not course.public
            course.last_modified = now
            course.put()
            return Response("Course %s is now %s." % (course.name, "public" if course.public else "private"))
        elif action == "REPLM":
            msg = check_new_mark(region, course, turn, i, gx, gy)
            if msg:
                return Response(msg, status=406)

            mark = Mark.get(course.marks[i])
            mark.x = x
            mark.y = y
            mark.gx = gx
            mark.gy = gy
            mark.put()

            course.turns[i] = turn
            course.length = course_length(course)
            course.last_modified = now
            course.put()
            return Response("\nMark %d was replaced by a new mark." % (i + 1))
        elif action == "DELM":
            if len(course.marks) == MIN_COURSE_LENGTH:
                return Response(
                    "\nYou cannot delete a mark from a %d mark course, you can only replace them." % MIN_COURSE_LENGTH
                )
            elif 1 <= i < len(course.marks):
                mark = Mark.get(course.marks[i])
                del course.marks[i]
                del course.turns[i]
                dec_mark(mark)
                course.length = course_length(course)
                course.last_modified = now
                course.put()
                return Response("\nMark %d of course %s was deleted." % (i + 1, course.name))
            else:
                return Response("\nYou cannot delete the start/end mark, you can only replace them.")
        elif action == "ADDM":
            msg = check_new_mark(region, course, turn, i, gx, gy)
            if msg:
                return Response(msg, status=406)

            if 0 <= i < len(course.marks):
                mark = Mark(region=region, x=x, y=y, gx=gx, gy=gy, parent=user.key())
                mark.put()
                course.marks.insert(i + 1, mark.key())
                course.turns.insert(i + 1, turn)
                course.length = course_length(course)
                course.last_modified = now
                course.put()
                return Response("\nA %s mark was placed after mark %d of course %s." % (turn, i + 1, course.name))
            else:
                return Response("\nYou cannot add a mark after the finish mark.")
        elif action == "ANNC":
            course.comment = comment[:499]
            course.last_modified = now
            course.put()
            if len(comment) < 500:
                return Response("\nA comment was added to course %s." % course.name)
            else:
                return Response("\nThe comment was truncated to 500 characters and added to course %s." % course.name)
        elif action == "GMN" and mark_name:
            mark = Mark.get(course.marks[i])
            old_name = mark.name
            mark.name = mark_name.strip()
            mark.put()
            if old_name:
                return Response("\Mark %s was renamed to %s." % (old_name, mark.name))
            else:
                return Response("\nMark %d was named %s" % (i, mark.name))
        elif action == "ANNM":
            mark = Mark.get(course.marks[i])
            mark.comment = comment[:499]
            mark.put()
            if len(comment) < 500:
                return Response("\nA comment was added to mark %d of course %s." % (i + 1, course.name))
            else:
                return Response(
                    "\nThe comment was truncated to 500 characters and added to mark %d of course %s."
                    % (i + 1, course.name)
                )
    except db.Timeout:
        msg = "\nCourse was not modified. The database timed out."
        logging.error(msg)
        return Response(msg, status=500)
    except CapabilityDisabledError:
        msg = "\nCourse was not modified. Database could not be written to."
        logging.error(msg)
        return Response(msg, status=500)
    except TransactionFailedError:
        msg = "\nCourse was not modified. Transaction failed."
        logging.error(msg)
        return Response(msg, status=500)
    except Exception, e:
        if DEBUG:
            print_exc()
        logging.error(e)
        return Response("\nCourse was not modified. %s." % e, status=500)
Exemple #16
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)