Exemplo n.º 1
0
def add_region():
    session = dbconnect()
    request_dict = request.get_json()
    try:
        region_instance = Region()
        region_instance.region_name = request_dict["Region"]
        session.add(region_instance)
        session.commit()
        return jsonify(region_instance.id)
    except exc.IntegrityError:
        session.rollback()
        return "already exists", 400
Exemplo n.º 2
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)
Exemplo n.º 3
0
class TestRegion(unittest.TestCase):

    def setUp(self):
        self.id = 'norcal'
        self.display_name = 'Norcal'
        self.ranking_num_tourneys_attended=2
        self.ranking_activity_day_limit=60
        self.tournament_qualified_day_limit=999
        self.region = Region(id=self.id, display_name=self.display_name,
                             ranking_num_tourneys_attended=self.ranking_num_tourneys_attended,
                             ranking_activity_day_limit=self.ranking_activity_day_limit,
                             tournament_qualified_day_limit=self.tournament_qualified_day_limit)
        self.region_json_dict = {
            '_id': self.id,
            'display_name': self.display_name,
            'ranking_num_tourneys_attended': self.ranking_num_tourneys_attended,
            'ranking_activity_day_limit': self.ranking_activity_day_limit,
            'tournament_qualified_day_limit': self.tournament_qualified_day_limit
        }

    def test_dump(self):
        self.assertEqual(self.region.dump(context='db'), self.region_json_dict)

    def test_load(self):
        region = Region.load(self.region_json_dict, context='db')
        self.assertEqual(region.id, self.id)
        self.assertEqual(region.display_name, self.display_name)
Exemplo n.º 4
0
class TestRegion(unittest.TestCase):
    def setUp(self):
        self.id = 'norcal'
        self.display_name = 'Norcal'
        self.ranking_num_tourneys_attended = 2
        self.ranking_activity_day_limit = 60
        self.tournament_qualified_day_limit = 999
        self.region = Region(
            id=self.id,
            display_name=self.display_name,
            ranking_num_tourneys_attended=self.ranking_num_tourneys_attended,
            ranking_activity_day_limit=self.ranking_activity_day_limit,
            tournament_qualified_day_limit=self.tournament_qualified_day_limit)
        self.region_json_dict = {
            '_id': self.id,
            'display_name': self.display_name,
            'ranking_num_tourneys_attended':
            self.ranking_num_tourneys_attended,
            'ranking_activity_day_limit': self.ranking_activity_day_limit,
            'tournament_qualified_day_limit':
            self.tournament_qualified_day_limit
        }

    def test_dump(self):
        self.assertEqual(self.region.dump(context='db'), self.region_json_dict)

    def test_load(self):
        region = Region.load(self.region_json_dict, context='db')
        self.assertEqual(region.id, self.id)
        self.assertEqual(region.display_name, self.display_name)
Exemplo n.º 5
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)
Exemplo n.º 6
0
 def setUp(self):
     self.id = 'norcal'
     self.display_name = 'Norcal'
     self.ranking_num_tourneys_attended = 2
     self.ranking_activity_day_limit = 60
     self.tournament_qualified_day_limit = 999
     self.region = Region(
         id=self.id,
         display_name=self.display_name,
         ranking_num_tourneys_attended=self.ranking_num_tourneys_attended,
         ranking_activity_day_limit=self.ranking_activity_day_limit,
         tournament_qualified_day_limit=self.tournament_qualified_day_limit)
     self.region_json_dict = {
         '_id': self.id,
         'display_name': self.display_name,
         'ranking_num_tourneys_attended':
         self.ranking_num_tourneys_attended,
         'ranking_activity_day_limit': self.ranking_activity_day_limit,
         'tournament_qualified_day_limit':
         self.tournament_qualified_day_limit
     }
Exemplo n.º 7
0
    def test_get_all_regions(self):
        # add another region
        region = Region(id='newregion', display_name='New Region')
        Dao.insert_region(region,
                          self.mongo_client,
                          database_name=DATABASE_NAME)

        regions = Dao.get_all_regions(self.mongo_client,
                                      database_name=DATABASE_NAME)
        self.assertEquals(len(regions), 3)
        self.assertEquals(regions[0], region)
        self.assertEquals(regions[1], self.region_1)
        self.assertEquals(regions[2], self.region_2)
Exemplo n.º 8
0
def load_regions():
    """Load regions, i.e. states, for user addresses"""

    print "Regions"
    Region.query.delete()

    for row in open("data/regionsdata"):
        row = row.strip()
        abbr, full = row.split("|")

        a = Region(abbr=abbr, full=full)

        db.session.add(a)

    db.session.commit()
Exemplo n.º 9
0
def getblacklistedcourses():
    user_key = request.headers.get("X-SecondLife-Owner-Key")
    user = get_user(user_key)
    region_name, _, _ = get_region(request.headers.get("X-SecondLife-Region"))
    region = Region.get_by_key_name(region_name)

    query = BlacklistCourse.all()
    query.ancestor(user)
    query.filter("region =", region)
    result = sorted(["%s (by %s)" % (n.course.name, n.course.user.name) for n in query])

    if result:
        return Response("\nBlacklisted courses:\n" + "\n".join(result))
    else:
        return Response("\nYour course blacklist is empty.")
Exemplo n.º 10
0
 def get_region_data(self):
     start_offset = 8
     while True:
         end_offset = start_offset + self.buf[start_offset:-1].find(b'\x00')
         if not len(self.buf[start_offset:end_offset]) > 1:
             break
         record_content = self.buf[start_offset:end_offset].decode()
         province, city, zip_code, area_code = record_content.split('|')
         r = Region(province=province, city=city,
                    zip_code=zip_code, area_code=area_code)
         self.session.add(r)
         self.session.commit()
         self.mapping[start_offset] = r.id
         start_offset = end_offset + 1
     self._save_mapping()
Exemplo n.º 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)
Exemplo n.º 12
0
def load_regions():
    """Load all regions."""

    regions_file = open("./seed_data/map.txt")

    for row in regions_file:
        regions_info = row.strip().split("\t")

        cuisine, region_name = regions_info[0], regions_info[1]

        if regions_info[1] == None:
            regions_info = NULL

        region = Region(name=region_name) 
        db.session.add(region)
    
    db.session.commit()  
Exemplo n.º 13
0
 def setUp(self):
     self.id = 'norcal'
     self.display_name = 'Norcal'
     self.ranking_num_tourneys_attended=2
     self.ranking_activity_day_limit=60
     self.tournament_qualified_day_limit=999
     self.region = Region(id=self.id, display_name=self.display_name,
                          ranking_num_tourneys_attended=self.ranking_num_tourneys_attended,
                          ranking_activity_day_limit=self.ranking_activity_day_limit,
                          tournament_qualified_day_limit=self.tournament_qualified_day_limit)
     self.region_json_dict = {
         '_id': self.id,
         'display_name': self.display_name,
         'ranking_num_tourneys_attended': self.ranking_num_tourneys_attended,
         'ranking_activity_day_limit': self.ranking_activity_day_limit,
         'tournament_qualified_day_limit': self.tournament_qualified_day_limit
     }
Exemplo n.º 14
0
def display_region_graph():
    """displays region information page"""

    last_region_id = 34

    start_at = randint(1, last_region_id - SHOW_NUMBER)
    stop_before = start_at + SHOW_NUMBER

    region_data = Region.get_region_data(start_at=start_at,
                                         stop_before=stop_before)

    rough_regions = db.session.query(Region.region, Region.region_id).all()
    all_regions = {}
    for region, region_id in rough_regions:
        all_regions[region] = region_id

    return render_template("region.html", region_data=region_data,
                           all_regions=all_regions)
Exemplo n.º 15
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)
Exemplo n.º 16
0
def load_regions():
    """Load grid regions into database."""

    print "\n Regions \n"

    # Read region file and insert data
    for row in open("seed-data/regions.csv"):
        row = row.rstrip()
        region_id, name, lb_co2e_mega_wh = row.split(",")

        region = Region(region_id=region_id,
                        name=name,
                        lb_co2e_mega_wh=lb_co2e_mega_wh)

        # Add to the session so the data will be stored
        db.session.add(region)

    # Commit the changes to the database
    db.session.commit()
Exemplo n.º 17
0
def mycourses():
    user_key = request.headers.get("X-SecondLife-Owner-Key")
    user = get_user(user_key)
    region_name, _, _ = get_region(request.headers.get("X-SecondLife-Region"))
    region = Region.get_by_key_name(region_name)

    courses = []
    if not region is None:
        query = Course.all()
        query.ancestor(region)
        query.filter("user ="******"saved =", True)
        query.filter("deactivated =", False)

        for course in query:
            courses.append("%s (%s by %s);%s" % (course.name, course.type.lower(), course.user.name, str(course.key())))
    logging.info(courses)
    if courses:
        return Response(";".join(courses))
    else:
        return Response("\nYou have no courses in region %s." % region_name, status=406)
Exemplo n.º 18
0
def blacklistcourse():
    try:
        user_key = request.headers.get("X-SecondLife-Owner-Key")
        user = get_user(user_key)
        course_id = request.args.get("courseid")
        region_name, _, _ = get_region(request.headers.get("X-SecondLife-Region"))
        region = Region.get_by_key_name(region_name)

        course = Course.get(Key(course_id))

        query = BlacklistCourse.all()
        query.ancestor(user)
        query.filter("course =", course.key())
        bl_course = query.get()

        if bl_course is None:
            blc = BlacklistCourse(parent=user, course=course, region=region)
            blc.put()
            return Response("\nCourse `%s` was added to your blacklist." % course.name)
        else:
            bl_course.delete()
            return Response("\nCourse `%s` was removed from your blacklist." % course.name)
    except db.Timeout:
        msg = "\nCourse was not blacklisted. The database timed out."
        logging.error(msg)
        return Response(msg, status=500)
    except CapabilityDisabledError:
        msg = "\nCourse was not blacklisted. Database could not be written to."
        logging.error(msg)
        return Response(msg, status=500)
    except TransactionFailedError:
        msg = "\nCourse was not blacklisted. Transaction failed."
        logging.error(msg)
        return Response(msg, status=500)
    except Exception, e:
        if DEBUG:
            print_exc()
        logging.error(str(e))
        return Response("\nCourse was not blacklisted. %s." % e, status=500)
Exemplo n.º 19
0
    def setUp(self):
        self.mongo_client.drop_database(DATABASE_NAME)

        self.player_1_id = ObjectId()
        self.player_2_id = ObjectId()
        self.player_3_id = ObjectId()
        self.player_4_id = ObjectId()
        self.player_5_id = ObjectId()
        self.player_1 = Player(name='gaR',
                               aliases=['gar', 'garr'],
                               ratings={
                                   'norcal': Rating(),
                                   'texas': Rating()
                               },
                               regions=['norcal', 'texas'],
                               id=self.player_1_id)
        self.player_2 = Player(name='sfat',
                               aliases=['sfat', 'miom | sfat'],
                               ratings={'norcal': Rating()},
                               regions=['norcal'],
                               id=self.player_2_id)
        self.player_3 = Player(name='mango',
                               aliases=['mango', 'gar'],
                               ratings={'norcal': Rating(mu=2, sigma=3)},
                               regions=['socal'],
                               id=self.player_3_id)
        self.player_4 = Player(name='shroomed',
                               aliases=['shroomed'],
                               ratings={'norcal': Rating()},
                               regions=['norcal'],
                               id=self.player_4_id)
        self.player_5 = Player(name='pewpewu',
                               aliases=['pewpewu'],
                               ratings={'norcal': Rating()},
                               regions=['norcal', 'socal'],
                               id=self.player_5_id)

        self.merge_player_1 = Player(name='CLGsFaT',
                                     aliases=['clg | sfat'],
                                     ratings={'norcal': Rating()},
                                     regions=['norcal'],
                                     id=ObjectId())

        # only includes players 1-3
        self.players = [self.player_1, self.player_2, self.player_3]

        self.tournament_id_1 = ObjectId()
        self.tournament_type_1 = 'tio'
        self.tournament_raw_id_1 = ObjectId()
        self.tournament_date_1 = datetime(2013, 10, 16)
        self.tournament_name_1 = 'tournament 1'
        self.tournament_players_1 = [
            self.player_1_id, self.player_2_id, self.player_3_id,
            self.player_4_id
        ]
        self.tournament_matches_1 = [
            Match(winner=self.player_1_id, loser=self.player_2_id),
            Match(winner=self.player_3_id, loser=self.player_4_id)
        ]
        self.tournament_regions_1 = ['norcal']

        # tournament 2 is earlier than tournament 1, but inserted after
        self.tournament_id_2 = ObjectId()
        self.tournament_type_2 = 'challonge'
        self.tournament_raw_id_2 = ObjectId()
        self.tournament_date_2 = datetime(2013, 10, 10)
        self.tournament_name_2 = 'tournament 2'
        self.tournament_players_2 = [
            self.player_5_id, self.player_2_id, self.player_3_id,
            self.player_4_id
        ]
        self.tournament_matches_2 = [
            Match(winner=self.player_5_id, loser=self.player_2_id),
            Match(winner=self.player_3_id, loser=self.player_4_id)
        ]
        self.tournament_regions_2 = ['norcal', 'texas']

        self.tournament_1 = Tournament(id=self.tournament_id_1,
                                       name=self.tournament_name_1,
                                       type=self.tournament_type_1,
                                       date=self.tournament_date_1,
                                       regions=self.tournament_regions_1,
                                       raw_id=self.tournament_raw_id_1,
                                       players=self.tournament_players_1,
                                       matches=self.tournament_matches_1)

        self.tournament_2 = Tournament(id=self.tournament_id_2,
                                       name=self.tournament_name_2,
                                       type=self.tournament_type_2,
                                       date=self.tournament_date_2,
                                       regions=self.tournament_regions_2,
                                       raw_id=self.tournament_raw_id_2,
                                       players=self.tournament_players_2,
                                       matches=self.tournament_matches_2)

        self.tournament_ids = [self.tournament_id_1, self.tournament_id_2]
        self.tournaments = [self.tournament_1, self.tournament_2]

        self.pending_tournament_id_1 = ObjectId()
        self.pending_tournament_type_1 = 'tio'
        self.pending_tournament_raw_id_1 = ObjectId()
        self.pending_tournament_date_1 = datetime(2013, 10, 11)
        self.pending_tournament_name_1 = 'pending tournament 1'
        self.pending_tournament_players_1 = [
            self.player_1.name, self.player_2.name, self.player_3.name,
            self.player_4.name
        ]
        self.pending_tournament_matches_1 = [
            AliasMatch(winner=self.player_1.name, loser=self.player_2.name),
            AliasMatch(winner=self.player_3.name, loser=self.player_4.name)
        ]
        self.pending_tournament_regions_1 = ['norcal']

        self.pending_tournament_1 = PendingTournament(
            id=self.pending_tournament_id_1,
            name=self.pending_tournament_name_1,
            type=self.pending_tournament_type_1,
            date=self.pending_tournament_date_1,
            regions=self.pending_tournament_regions_1,
            raw_id=self.pending_tournament_raw_id_1,
            players=self.pending_tournament_players_1,
            matches=self.pending_tournament_matches_1)

        self.pending_tournaments = [self.pending_tournament_1]

        self.ranking_entry_1 = RankingEntry(rank=1,
                                            player=self.player_1_id,
                                            rating=20)
        self.ranking_entry_2 = RankingEntry(rank=2,
                                            player=self.player_2_id,
                                            rating=19)
        self.ranking_entry_3 = RankingEntry(rank=3,
                                            player=self.player_3_id,
                                            rating=17.5)
        self.ranking_entry_4 = RankingEntry(rank=3,
                                            player=self.player_4_id,
                                            rating=16.5)

        self.ranking_time_1 = datetime(2013, 4, 20)
        self.ranking_time_2 = datetime(2013, 4, 21)
        self.ranking_1 = Ranking(id=ObjectId(),
                                 region='norcal',
                                 time=self.ranking_time_1,
                                 tournaments=self.tournament_ids,
                                 ranking=[
                                     self.ranking_entry_1,
                                     self.ranking_entry_2, self.ranking_entry_3
                                 ])
        self.ranking_2 = Ranking(id=ObjectId(),
                                 region='norcal',
                                 time=self.ranking_time_2,
                                 tournaments=self.tournament_ids,
                                 ranking=[
                                     self.ranking_entry_1,
                                     self.ranking_entry_2, self.ranking_entry_4
                                 ])
        self.ranking_3 = Ranking(
            id=ObjectId(),
            region='norcal',
            time=self.ranking_time_2,
            tournaments=self.tournament_ids,
            ranking=[self.ranking_entry_1, self.ranking_entry_2])

        self.rankings = [self.ranking_1, self.ranking_2, self.ranking_3]

        self.user_id_1 = 'abc123'
        self.user_admin_regions_1 = ['norcal', 'texas']
        self.user_1 = User(id=self.user_id_1,
                           admin_regions=self.user_admin_regions_1,
                           username='******',
                           salt='nacl',
                           hashed_password='******')

        self.user_id_2 = 'asdfasdf'
        self.user_full_name_2 = 'Full Name'
        self.user_admin_regions_2 = []
        self.user_2 = User(id=self.user_id_2,
                           admin_regions=self.user_admin_regions_2,
                           username=self.user_full_name_2,
                           salt='nacl',
                           hashed_password='******')

        self.users = [self.user_1, self.user_2]

        self.region_1 = Region(id='norcal', display_name='Norcal')
        self.region_2 = Region(id='texas', display_name='Texas')

        self.regions = [self.region_1, self.region_2]

        for region in self.regions:
            Dao.insert_region(region,
                              self.mongo_client,
                              database_name=DATABASE_NAME)

        self.norcal_dao = Dao('norcal',
                              self.mongo_client,
                              database_name=DATABASE_NAME)

        for player in self.players:
            self.norcal_dao.insert_player(player)

        for tournament in self.tournaments:
            self.norcal_dao.insert_tournament(tournament)

        for pending_tournament in self.pending_tournaments:
            self.norcal_dao.insert_pending_tournament(pending_tournament)

        for ranking in self.rankings:
            self.norcal_dao.insert_ranking(ranking)

        for user in self.users:
            self.norcal_dao.insert_user(user)
Exemplo n.º 20
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)
Exemplo n.º 21
0
 def test_load(self):
     region = Region.load(self.region_json_dict, context='db')
     self.assertEqual(region.id, self.id)
     self.assertEqual(region.display_name, self.display_name)
Exemplo n.º 22
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)
Exemplo n.º 23
0
 def test_load(self):
     region = Region.load(self.region_json_dict, context='db')
     self.assertEqual(region.id, self.id)
     self.assertEqual(region.display_name, self.display_name)
Exemplo n.º 24
0
def load_regions():
    """loads region names and codes"""
    for r in Parse.regions:
        region = Region(region_name=r)
        db.session.add(region)
        db.session.commit()