Пример #1
0
def login():
    if request.method == "POST":
        email = request.form["email"]
        session["email"] = email
        try:
            session["access"] = database.get_access(email)
        except AssertionError:
            return render_template("home.html", correct={"login":True}, bad_login=True, error="User does not exist.", resend_auth=False)

        password = request.form["password"]
        if database.user_exists(email) and not database.user_authed(email):
            return render_template("home.html", correct={"login":True}, bad_login=True, error="You have not authorized your account.", resend_auth=True)

        if database.correct_user(email, password):
            session["access"] = database.get_access(email) 
            session["gitlink"] = database.get_git_link(email)
            session["location"] = database.get_location(email)

            return redirect(url_for("login_home", access=session["access"]))
        else:
            return render_template("home.html", correct={"login":True}, bad_login=True, error="Incorrect username or password.", resend_auth=False)
    else:
        if "email" in session:
            if "access" in session:
                session["gitlink"] = database.get_git_link(session["email"])
                session["location"] = database.get_location(session["email"])
                return redirect(url_for("login_home", access=session["access"]))
        return render_template("home.html", correct={"login":True}, bad_login=False)
Пример #2
0
def rated():
    if request.method == "POST":
        if "username" in session:
            user = database.get_user(session['username'])
            if "upvote" in request.form:
                _id = request.form['upvote']
                loc = database.get_location(_id)
                locations.update(loc,{'$pull':{'downvotes':user['_id']},'$push':{'upvotes':user['_id']}},upsert=False,multi=False)
                #locations.update(loc,{'$push':{'upvotes':user['_id']}},upsert=False,multi=False)
            elif "downvote" in request.form:
                _id = request.form['downvote']
                loc = database.get_location(_id)
                locations.update(loc,{'$pull':{'upvotes':user['_id']},'$push':{'downvotes':user['_id']}},upsert=False,multi=False)
Пример #3
0
def move_ship(session, ship, coordinate):
    """ Attempt to move this ship to a new location. """

    if coordinate not in ship.location.coordinate.neighbors:
        raise ValueError(f"{ship} too far away from {coordinate}")

    ship.location = get_location(session, ship.location.sector, coordinate)
Пример #4
0
def post(postid=None):
    isError = False
    error = ""
    curr_loc = database.get_location(postid)
    print curr_loc
    curr_comments = database.get_comments(postid)
    if request.method == "GET":
        if 'username' in session:
            user = database.get_user(session['username']);
            return render_template("post.html", location=curr_loc,get_timestamp=get_timestamp, comments=curr_comments, get_votes=database.get_votes_pst,postid=postid,session=session,user=user) 
        return render_template("post.html", location=curr_loc,get_timestamp=get_timestamp, comments=curr_comments, get_votes=database.get_votes_pst,postid=postid,session=session) 
    else:
        if 'username' in session:
            user=database.get_user(session['username']);
        rated()
        postid = postid
        if "content" in request.form:
            content = request.form['content']
            if content == "":
                error = "You didn't write anything!"
                isError=True
                return render_template("post.html", error=error, isError=isError, location=curr_loc, get_timestamp=get_timestamp, comments=curr_comments, get_votes=database.get_votes, postid=postid, session=session, user=user)
            elif "username" in session:
                author = session['username'] 
                user = database.get_user(author)
                database.add_comment(None, content, postid, author)
                users.update(
                user,
                    {'$push':{'comments':postid}}
                )
                #return redirect(url_for("post",postid=postid,session=session))

        #return redirect(url_for("post",postid=postid))
    return redirect(url_for("post",postid=postid,session=session, isError=isError, error=error))
Пример #5
0
def load_map(session, map_file, sector):
    """ Load a map of tiles into a sector. """

    map_data = load(map_file)

    rows = len(map_data)
    cols = len(map_data[0])

    r_start = -(rows // 2) + 1

    for x, row in enumerate(map_data, r_start):  # rows

        c_start = -(cols // 2) + 1
        for y, tile_type in enumerate(row, c_start):
            tile_type = TileType(tile_type)
            z = -(x + y)

            coordinate = Coordinate(x, y, z)

            tile = get_tile(session, sector, coordinate)
            if tile is None:
                tile = Tile(type=tile_type)
                tile.location = get_location(session, sector, coordinate)
                session.add(tile)
            elif tile.type != tile_type:
                print(f"Updating {tile} to {tile_type.name}")
                tile.type = tile_type
Пример #6
0
def id_for_query(query, config):
    # From the given query, gets the matching ID (if it exists). If it doesn't
    # yet exist, performs the query, and returns the id_ to fetch the result.

    def lookup(query, api_key):
        u = 'https://maps.googleapis.com/maps/api/geocode/json?address={}&key={}'
        resp = json.loads(requests.get(u.format(query, api_key)).text)
        if resp['status'] != 'OK':
            return resp, None
        for result in resp['results']:
            return result
            return None, loc
        return 'No results', None

    id_ = database.get_id_for_query(query)
    if id_:
        return id_

    parsed_result = lookup(query, config['google_api_key'])
    database.save_location_lookup(query, json.dumps(parsed_result))

    id_ = location_database_utils.get_id_for_location_lookup(
        query, parsed_result)
    database.save_id_for_query(query, id_)

    if database.get_location(id_):
        # The location was already fetched. This might happen if previously
        # 'Zurich HB' was added, but this time, 'Zurich Main Station' was the
        # query.
        return id_

    location_data = location_database_utils.create_locations_row_for_lookup(
        parsed_result)
    database.save_location(id_, location_data)
Пример #7
0
 def create_show_button(t, l):
     if not t:
         label = "%s" % get_location(l)
     else:
         label = get_time(t)
     return InlineKeyboardButton(
         label,
         callback_data="{'action':'show', 'time':%d, 'location': %d}" %
         (t, l))
Пример #8
0
def message_handler(message):
    """Handle message from user

    Args:
        message (:class:`telegram.Message`):
    """
    location = database.get_location(message.from_user.id)
    if not location:
        return {"text": "Для поиска лекарств отправь своё местоположение"}

    return get_drugs_message(find_drugs(message.text.encode('utf-8')))
Пример #9
0
def load_templates(access, location, filename):
    if not database.valid_access(access):
        return render_template("error.html", error="Page not found.")
    try:
        if database.is_student(access):
            git_link = database.get_git_link(session["email"])
        else:
            git_link = "/"
        location = database.get_location(session["email"])
        return render_template(filename, access=access, github_link=git_link, location = location)
    except jinja2.exceptions.TemplateNotFound as e:
        return render_template("error.html", error="Page not found.")
Пример #10
0
def myposts(username=None):
    user = database.get_user(username)
    ids = user['bizcuits'];
    print ids
    #locs = database.get_locations()
    locs = [database.get_location(i) for i in ids]
    locs = [x for x in locs if x != None]
    print locs
    #locs = [x for x in locs if x['author'] == user]
    #print locs
    #print user['username']
    return render_template("myposts.html",locations=locs, session=session,get_timestamp=get_timestamp, username=username)
Пример #11
0
def access_material(access, location, assignment):
    if not database.valid_access(access) or assignment not in config.STUDENT_PAGE_LINKS or not database.valid_location(location):
        return render_template("error.html", error="Page not found.")
    elif access != session["access"] and not database.is_admin(session["access"]):
        return redirect(url_for("unauthorized"))
    elif location != session["location"] and not database.is_admin(session["access"]):
        return redirect(url_for("unauthorized"))
    else:
        existing = database.get_existing_lectures(access, assignment, location)
        location = database.get_location(session["email"])

        return render_template("lectures.html", access=access, 
            lectures=existing,
            github_link=session["gitlink"],
            header=config.STUDENT_PAGE_DICT[assignment], 
            location=location)
Пример #12
0
def login_home(access):
    if not database.valid_access(access):
        return render_template("error.html", error="Page not found.")
    elif access != session["access"] and not database.is_admin(session["access"]):
        return redirect(url_for("unauthorized"))

    if database.is_admin(access):
        return render_template("admin_home.html", access=access)
    elif database.is_student(access):
        announcements = database.get_announcements(access)
        location = database.get_location(session["email"])
        return render_template("student_home.html", access=access, 
                location=location,
                github_link=session["gitlink"], announcements=announcements)
    else:
        return redirect(url_for("unauthorized"))
Пример #13
0
def confirm(token):
    #change this you dummy
    email = security.confirm_token(token)
    if email:
        try:
            database.authenticate_user(email)
        except AssertionError:
            return render_template("home.html", correct={"login":True}, bad_login=True, error="User not found.", resend_auth=False)
    else:
        flash("Expired or invalid token.", "danger")
        return render_template("home.html", correct={"login":True}, bad_login=True, error="Expired or invalid token.", resend_auth=True)
    session["email"] = email
    session["access"] = database.get_access(session["email"])
    session["gitlink"] = database.get_git_link(session["email"])
    session["location"] = database.get_location(session["email"])
    return redirect(url_for("login_home", access=session["access"]))
Пример #14
0
def create_initial_ship():
    """ Create default ship for a player. """

    ship_config = CONFIG.get("game.players.default_ship")
    sector = get_sector(database_session, sector_name=ship_config["sector"])
    location = get_location(database_session, sector,
                            Coordinate.load(ship_config["location"]))
    chassis = get_chassis(database_session, name=ship_config["chassis"])

    loadout = []
    for system_name in ship_config["loadout"]:
        system = get_ship_system(database_session, name=system_name)
        loadout.append(system)

    ship = create_ship(database_session, current_user, location, chassis,
                       loadout)
    database_session.commit()
    return ship
Пример #15
0
def generate_sectors(session, sectors_data):
    """ Get or create sectors using static config data. """
    print(sectors_data)
    for sector_name, sector_data in sectors_data.items():
        try:
            sector = get_sector(session, sector_name=sector_name)
        except NoResultFound:
            print(f"{sector_name} not in db, creating it")
            sector = Sector(name=sector_name)
            session.add(sector)

        cities_data = sector_data.pop("cities")
        for city_name, city_data in cities_data.items():
            try:
                get_city(session, city_name=city_name)
            except NoResultFound:
                print(f"{city_name} not found, creating it")
                coordinate = Coordinate.load(city_data["location"])
                location = get_location(session, sector, coordinate)
                create_city(session, city_name, location)

        load_map(session, f"data/maps/{sector.name}.map", sector)
Пример #16
0
 def _maybe_add_location(id_):
     if id_ in locations:
         return
     location = database.get_location(id_)
     locations[id_] = location
Пример #17
0
 def create_location_button(num):
     return InlineKeyboardButton(
         get_location(num),
         callback_data="{'action':'update', 'id':%s, 'location':%s}"
         % (reply['id'], num))
Пример #18
0
def create_travel_map(config):
    def _get_location_dict(loc):
        # Turn a Location object into a json-dumpable form.
        return {
            'lat': loc['latitude'],
            'lng': loc['longitude'],
            'id': loc['id'],
            'address': loc['address'],
            'type': loc['type'],  # eg. 'CLUSTER', 'STATION', 'TOWN'
            'region':
            loc['region'],  # used to cluster close places, and to give names to those clusters.
            'country': loc['country_name'],  # used for stats.
            'country_code': loc['country_code'],
            'human_readable_name': loc['name'],  # no guarantee of uniqueness
        }

    database.regenerate_tables()
    csv_loc = '../mo_thaistil/full.csv'
    #_log_legs_from_csv(csv_loc, config)

    id_to_location = {}
    location_visits = defaultdict(lambda: {
        'num_visits': 0,
        'duration': pendulum.now() - pendulum.now()
    })
    aggregated_legs = defaultdict(lambda: {'count': 0, 'mode': None})
    prev_loc_id = None
    prev_loc_date = None
    for leg in database.get_legs():
        dep_id = leg['departure_location_id']
        arr_id = leg['arrival_location_id']
        dep = _get_location_dict(database.get_location(dep_id))
        arr = _get_location_dict(database.get_location(arr_id))
        id_to_location[dep['id']] = dep
        id_to_location[arr['id']] = arr

        k = (dep['id'], arr['id'], leg['mode'])
        aggregated_legs[k]['count'] += 1
        aggregated_legs[k]['mode'] = leg['mode']
        if leg['departure_datetime'] >= leg['arrival_datetime']:
            print(
                'Warning: travel leg does not have positive duration: {} ({}) to {} ({})'
                .format(dep['human_readable_name'], leg['departure_datetime'],
                        arr['human_readable_name'], leg['arrival_datetime']))

        if prev_loc_id is not None:
            # Try to account for places which never appear as an arrival, and only as a departure location.
            if prev_loc_id == dep['id']:
                location_visits[prev_loc_id]['duration'] += (
                    leg['departure_datetime'] - prev_loc_date)
                location_visits[prev_loc_id]['num_visits'] += 1
            else:
                location_visits[dep['id']]['duration'] += (
                    leg['departure_datetime'] - prev_loc_date) / 2
                location_visits[dep['id']]['num_visits'] += 1
                location_visits[prev_loc_id]['duration'] += (
                    leg['departure_datetime'] - prev_loc_date) / 2
                location_visits[prev_loc_id]['num_visits'] += 1

        prev_loc_id = arr['id']
        prev_loc_date = leg['arrival_datetime']

    legs = []
    for k in aggregated_legs:
        dep_id, arr_id, _ = k
        mode = aggregated_legs[k]['mode']
        count = aggregated_legs[k]['count']
        legs.append({
            'dep': id_to_location[dep_id],
            'arr': id_to_location[arr_id],
            'mode': mode,
            'count': count,
        })
    visits = []
    for id_ in location_visits:
        visits.append({
            'location':
            id_to_location[id_],
            'num_visits':
            location_visits[id_]['num_visits'],
            'days':
            int(0.5 + location_visits[id_]['duration'].total_days()),
            'hours':
            max(1, int(0.5 + location_visits[id_]['duration'].total_hours())),
        })

    # The travel map does not have access to individual leg_ids, so augment the
    # legs in the collection with the dep_id and arr_id.
    def get_collections_for_travel_map():
        collections = get_collections()
        for collection in collections:
            total_distance = 0
            for part in collection['parts']:
                if part['note'] or part['image_url']:
                    continue
                leg_id = part['leg_id']
                leg = database.get_leg(leg_id)
                part['leg'] = leg
                dep_id = leg['departure_location_id']
                arr_id = leg['arrival_location_id']
                part['dep'] = id_to_location[dep_id]
                part['arr'] = id_to_location[arr_id]
                distance = cluster.estimated_distance_km(
                    id_to_location[dep_id]['lat'],
                    id_to_location[dep_id]['lng'],
                    id_to_location[arr_id]['lat'],
                    id_to_location[arr_id]['lng'])
                part['distance'] = int(round(distance))
                total_distance += distance
            collection['meta'] = {
                'distance': int(round(total_distance)),
            }
        return collections

    data = {
        'legs': legs,
        'visits': visits + cluster.get_clusters(visits),
        'collections': get_collections_for_travel_map(),
    }
    s = json.dumps(data, indent=4)
    return s
Пример #19
0
def button(bot, update):
    query = update.callback_query

    reply = ast.literal_eval(query.data)
    print 'BUTTON:', reply
    if reply.get('action') == 'update':
        update_task(query.from_user, reply)
        if 'time' in reply:
            bot.editMessageText(text="Ок, %s" %
                                get_time(reply['time']).encode('utf8'),
                                chat_id=query.message.chat_id,
                                message_id=query.message.message_id)

            def create_location_button(num):
                return InlineKeyboardButton(
                    get_location(num),
                    callback_data="{'action':'update', 'id':%s, 'location':%s}"
                    % (reply['id'], num))

            keyboard = [[create_location_button(i) for i in range(1, 5)]]
            reply_markup = InlineKeyboardMarkup(keyboard)

            bot.sendMessage(chat_id=query.message.chat_id,
                            text="Это где?",
                            reply_markup=reply_markup)

        if 'location' in reply:
            bot.editMessageText(text="Ок, %s" %
                                get_location(reply['location']).encode('utf8'),
                                chat_id=query.message.chat_id,
                                message_id=query.message.message_id)

    if reply.get('action') == 'show':

        number_of_tasks, task_id, task = get_task_from_db(
            query.from_user, reply.get('time', 0), reply.get('location', 0),
            reply.get('number', 0))
        reply['number'] = reply.get('number', 0) + 1
        if number_of_tasks == 0:
            bot.sendMessage(chat_id=query.message.chat_id, text='Таких нет!')
            return
        if reply['number'] >= number_of_tasks:
            reply['number'] = 0
            button_name = 'Давай сначала!'
        else:
            button_name = 'Следущую!'
        keyboard = [[
            InlineKeyboardButton(
                'Делаю!',
                callback_data="{'action':'update', 'id':%s, 'status':1}" %
                task_id),
            InlineKeyboardButton(button_name, callback_data=str(reply)),
            InlineKeyboardButton('Удалить!',
                                 callback_data="{'action':'delete', 'id':%s}" %
                                 task_id)
        ]]
        reply_markup = InlineKeyboardMarkup(keyboard)
        bot.sendMessage(chat_id=query.message.chat_id,
                        text=task,
                        reply_markup=reply_markup)

    if reply.get('action') == 'delete':

        delete_task(reply.get('id'))
Пример #20
0
def location(id_):
    return database.get_location(id_)