Exemplo n.º 1
0
 def commit_to_session(self, session=session):
     """Commit this blog post to the database"""
     session.add(self)
     session.flush()
     session.commit()
     session.refresh(self)
     return self.id
Exemplo n.º 2
0
def create_competition():
    data = request.form
    if current_user.admin == 0:
        return serve_error('Only admins can create competitions', 401)

    try:
        competition = Competition(
            name=data['name'],
            start=int(data['start_time']),
            stop=(int(data['start_time']) + int(data['length'])),
            closed=1 if bool(data['closed']) else 0
        )
        competition.commit_to_session()

        comp_problems = loads(data['problems'])
    except KeyError as err:
        return serve_error('You must specify name, startTime, length, and'
                ' problem attributes. ' + err[0] + ' not found.',
                response_code=400)
    except ValueError:
        return serve_error('JSON data for \'problems\' not properly formatted',
                response_code=400)

    for problem in comp_problems:
        session.add(CompProblem(
            label=problem['label'][:2],
            cid=competition.cid,
            pid=problem['pid']
        ))
    session.flush()
    session.commit()

    return serve_response(competition.to_dict())
Exemplo n.º 3
0
 def commit_to_session(self, session=session):
     """Commit this problem to the database as a new problem."""
     session.add(self)
     session.flush()
     session.commit()
     session.refresh(self)
     return self.pid
Exemplo n.º 4
0
def put_competition_teams(cid):
    """ Update the teams for a competition

    If a user is an admin, they can update the competition's users, doing a PUT.
    This will take the JSON data in the 'teams' part of the request form and
    store it to the database. Any teams or users not included in the JSON data
    will not be a part of the competition and will have to re-register; however
    it should not be used for the solely purpose of de-registering participants.
    """
    try:
        teams = loads(request.form['teams'])
    except KeyError as err:
        return serve_error('You must include the parameter \'teams\'.',
                response_code=400)
    except ValueError:
        return serve_error('JSON data for \'teams\' not properly formatted',
                response_code=400)

    # Delete all of the old CompUser rows for this competition
    session.query(CompUser).filter(CompUser.cid == cid).delete()

    for team in teams:
        for user in teams[team]:
            session.add(CompUser(
                cid=cid,
                username=user,
                team=team
            ))

    session.flush()
    session.commit()

    return serve_response({})
 def setUp(self):
     """Instantiate dummy test details."""
     self.username = fake.user_name()
     self.password = fake.password()
     password_hash = generate_password_hash(self.password)
     self.user = User(username=self.username, password_hash=password_hash)
     session.add(self.user)
     session.commit()
Exemplo n.º 6
0
    def commit_to_session(self):
        """Commit this CompUser to the database.

        This is useful for adding a newly-created CompUser to the database.
        """
        session.add(self)
        session.flush()
        session.commit()
        session.refresh(self)
        self._problem = None
Exemplo n.º 7
0
    def mutate(self, info, input):
        Model = DateScheduleType._meta.model
        data = input_to_dictionary(input)
        date_schedule = Model(**data)

        session.add(date_schedule)
        session.commit()
        success = True

        return CreateDateSchedule(date_schedule=date_schedule, success=success)
Exemplo n.º 8
0
 def save(self, commit=True):
     if self.db_obj is None:
         self.db_obj = models.Block()
     self.db_obj.x = self.x
     self.db_obj.y = self.y
     for param in BLOCK_ENV_PARAMS:
         setattr(self.db_obj, param, getattr(self, param))
     session.add(self.db_obj)
     if commit:
         session.commit()
Exemplo n.º 9
0
    def commit_to_session(self, session=session):
        """Commit this Competition to the database.

        This is useful for adding a newly-created Competition to the database.
        """
        session.add(self)
        session.flush()
        session.commit()
        session.refresh(self)
        self._problem = None
        return self.cid
Exemplo n.º 10
0
def insert_real_life_location(datas):
	rll = Real_life_location()
	rll.name = datas['name']
	rll.scene = datas['scene']
	rll.overview = datas['overview']
	rll.image_path = datas['image_path']
	rll.latitude = datas['latitude']
	rll.longitude = datas['longitude']
	rll.products_id = datas['products_id']
	session.add(rll)
	session.commit()
Exemplo n.º 11
0
def change_password():
    oldPassword = request.form['oldPassword']
    newPassword = request.form['newPassword']
    if bcrypt.check_password_hash(current_user.passw, oldPassword):
        hashed = bcrypt.generate_password_hash(newPassword)
        current_user.passw = hashed
        session.add(current_user)
        session.flush()
        session.commit()
        return serve_response({})
    return serve_error('old password does not match', 401)
Exemplo n.º 12
0
def gconnect():
    code = request.data
    try:
        # Upgrade the authorization code into a credentials object
        oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        return error_message(401, "Failed to upgrade the authorization code.")

    # Check if the access token is valid
    access_token = credentials.access_token
    url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' %
           access_token)
    h = httplib2.Http()
    result = json.loads(h.request(url, 'GET')[1])

    # If there was an error in the access token info, abort
    if result.get('error') is not None:
        return error_message(500, result.get('error'))

    # Verify that the access token is used for the intended user.
    gplus_id = credentials.id_token['sub']
    if result['user_id'] != gplus_id:
        return error_message(401,
                             "Token's user ID doesn't match give user ID.")

    # Verify that the access token is valid for this app.
    if result['issued_to'] != CLIENT_ID:
        return error_message(401, "Token's client ID does not match app's.")

    # Get user info
    userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)

    data = answer.json()

    name = data["name"]
    picture = data["picture"]
    email = data["email"]

    user = session.query(User).filter_by(email=email).first()
    if not user:
        user = User(username=name, picture=picture, email=email)
        session.add(user)
        session.commit()

    # Make token
    token = user.generate_auth_token(600)

    return data_message(200, {'token': token.decode('ascii')},
                        "Successfully generated token."), 200
Exemplo n.º 13
0
    def commit_to_session(self):
        '''Commit this Submission to the database.

        This is useful for adding a newly-created Submission to the database.
        '''
        dblock.acquire()
        session.add(self)
        session.flush()
        session.commit()
        session.refresh(self)
        dblock.release()
        self._problem = None
    def test_bucketlist_search_by_name(self):
        """Test that a user can search for a bucketlist by its name."""
        list_name = 'Ins Kino gehen'
        bucketlist = BucketList(list_name=list_name,
                                creator=self.user.user_id)
        session.add(bucketlist)
        session.commit()

        response = self.client.get('/bucketlists/?q=Kino',
                                   headers={'token': self.token})
        self.assertIn('Kino', response.data)
        self.assertEqual(response.status_code, 200)
Exemplo n.º 15
0
def register_for_competition(cid):
    """ Called when a user wants to register for a competition.

    All the user has to do is submit a post to this url with no form data.
    From their logged-in status, we'll go ahead and add them to the competiton
    as an individual (team name is default their display name). A 400 error will
    be returned if the user is already registered for the competition.

    If the user that is submitting this is an admin, they can optionally
    supply a json array of usernames to register for the competition. Specifying
    this will not register the admin, but it will register all users that are
    listed. A 400 error will be returned if any of the users are already
    registered for the competition.
    """
    if session.query(Competition).filter(Competition.cid == cid).first() \
            is None:
        return serve_error('Competition does not exist', response_code=404)

    if current_user.admin == 1 and 'users' in request.data:
        try:
            registrants = loads(request.data['users'])
        except ValueError:
            return serve_error('JSON data for \'users\' not properly formatted',
                    response_code=400)
    else:
        registrants = [current_user.username]

    for user in registrants:
        if session.query(CompUser).filter(CompUser.cid == cid,
            CompUser.username == user).first() is not None:
            return serve_error('User ' + user + ' already registered for '
                    'competition', response_code=400)

    for username in registrants:
        user = session.query(User).filter(User.username == user).first()
        session.add(CompUser(
            cid=cid,
            username=user.username,
            team=user.display
        ))
        socketio.emit('new_user', {
            'cid': cid,
            'user': {
                'display': user.display,
                'username': user.username
            }
        },
        namespace='/register')
    session.flush()
    session.commit()

    return serve_response({})
Exemplo n.º 16
0
    def save(self):
        if self.db_obj is None:
            self.db_obj = models.Chunk()
        self.db_obj.x = self.x
        self.db_obj.y = self.y
        self.db_obj.name = self.name

        for block in self.blocks:
            block.save(commit=False)
            block.db_obj.chunk_id = self.db_obj.id

        session.add(self.db_obj)
        session.commit()
Exemplo n.º 17
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for('main.index'))
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(username=form.username.data, email=form.email.data)
        user.set_password(form.password.data)
        session.add(user)
        session.commit()
        flash('Congratulations, you are now a registered user!')
        return redirect(url_for('auth.login'))
    return render_template('auth/register.html.jinja',
                           title='Register',
                           form=form)
Exemplo n.º 18
0
def edit_category(category_id):
    try:
        category = session.query(Category).filter_by(id=category_id).one()
    except:
        return error_message(404, "Cannot update: Category not found.")
    name = request.form.get('name')
    if name:
        category.name = name
        session.add(category)
        session.commit()
    else:
        return error_message(400, "Course name is required.")
    return data_message(200, {"Category": category.serialize},
                        "Successfully updated the category.")
Exemplo n.º 19
0
def update_competition_data(cid):
    """ Adds problems to a competition

    Doing a POST request adds that problem to the competition whereas
    a PUT request will remove all problems that were previously associated
    with that competition and add all of the ones in the form body.

    TODO: form validation to make sure that no duplicates are added.
    """
    if current_user.admin == 0:
        # admins only
        return serve_error('Only admins can modify competitions', 401)

    data = request.form

    try:
        competition = session.query(Competition).filter(Competition.cid == cid)\
                .first()

        competition.name = data['name']
        competition.start=int(data['start_time'])
        competition.stop=(int(data['start_time']) + int(data['length']))
        competition.closed = 0 if bool(data['closed']) else 0
        competition.commit_to_session()

        # If the client sends a PUT request, we need to delete all of the old
        # problems associated with this competition
        session.query(CompProblem).filter(CompProblem.cid == cid).delete()

        comp_problems = loads(data['problems'])
    except KeyError as err:
        return serve_error('You must specify name, startTime, length, and'
                ' and problem attributes. ' + err[0] + ' not found.',
                response_code=400)
    except ValueError:
        return serve_error('JSON data for \'problems\' not properly formatted',
                response_code=400)

    for problem in comp_problems:
        session.add(CompProblem(
            label=problem['label'],
            cid=competition.cid,
            pid=problem['pid']
        ))

    session.flush()
    session.commit()
    return serve_response(competition.to_dict())
Exemplo n.º 20
0
def create_blog_post():
    if not current_user.admin == 1:
        return serve_error('You must be an admin to submit blog posts', response_code=401)
    if not request.form['title'] or not request.form['subtitle'] or not request.form['body']:
        return serve_error('Must include title, subtitle, and body with request', 
                           response_code=400)
    post = BlogPost(title=request.form['title'],
                    subtitle=request.form['subtitle'],
                    post_time=int(time()),
                    body=request.form['body'],
                    username=current_user.username)
    session.add(post)
    session.flush()
    session.commit()
    session.refresh(post)
    return serve_response(create_blog_object(post))
Exemplo n.º 21
0
def add_user():
    name = raw_input("Name: ")
    email = raw_input("Email: ")
    if session.query(User).filter_by(email=email).first():
        print "User with that email already exists"
        return

    password = ""
    password_2 = ""
    while not (password and password_2) or password != password_2:
        password = getpass("Password: "******"Re-enter password: ")
    user = User(name=name, email=email,
        password=generate_password_hash(password))
    session.add(user)
    session.commit()
Exemplo n.º 22
0
def view(id, character, editable):
    subskillform = SubskillForm(prefix="subskillform")
    if editable and subskillform.data and subskillform.validate_on_submit():
        character.add_subskill(subskillform.name.data,
                               subskillform.parent.data)
        logentry = LogEntry(
            character,
            f"add subskill {subskillform.name.data} under {subskillform.parent.data}",
            user_id=current_user.id)
        session.add(logentry)

        character.store_data()
        session.commit()
        return redirect(url_for('character.view', id=id))

    skillform = SkillForm(prefix="skillform")
    if editable and skillform.data and skillform.validate_on_submit():
        skills = character.skills()
        for skill in skills:
            if skillform.name.data == skill['name']:
                flash("Skill already exists")
                return redirect(url_for('character.view', id=id))

        character.add_skill(skillform.name.data)
        character.store_data()
        logentry = LogEntry(character,
                            f"add skill {subskillform.name.data}",
                            user_id=current_user.id)
        session.add(logentry)

        session.commit()
        return redirect(url_for('character.view', id=id))

    typeheader = "1920s Era Investigator"
    if character.game and character.game[1] == "Modern":
        typeheader = "Modern Era"

    shared = Invite.query_for(character).count()

    return render_template('character/coc7e/sheet.html.jinja',
                           shared=shared,
                           character=character,
                           typeheader=typeheader,
                           editable=editable,
                           skillform=skillform,
                           subskillform=subskillform)
Exemplo n.º 23
0
def index():

    user_profile = UserProfile.query.get(current_user.id)

    if user_profile is None:
        user_profile = UserProfile(user_id=current_user.id)
        session.add(user_profile)
        session.commit()

    logger.info(f"Showing profile {user_profile.id}")

    characters = user_profile.characters
    folders = user_profile.folders  # .filter(Folder.parent_id.__eq__(None))
    return render_template('profile/profile.html.jinja',
                           profile=user_profile,
                           characters=characters,
                           folders=folders)
Exemplo n.º 24
0
def on_revert(request, page_name):
    """Revert an old revision."""
    rev_id = request.args.get('rev', type=int)

    old_revision = page = None
    error = 'No such revision'

    if request.method == 'POST' and request.form.get('cancel'):
        return redirect(href(page_name))

    if rev_id:
        old_revision = Revision.query.filter(
            (Revision.revision_id == rev_id) &
            (Revision.page_id == Page.page_id) &
            (Page.name == page_name)
        ).first()
        if old_revision:
            new_revision = Revision.query.filter(
                (Revision.page_id == Page.page_id) &
                (Page.name == page_name)
            ).order_by(Revision.revision_id.desc()).first()
            if old_revision == new_revision:
                error = 'You tried to revert the current active ' \
                        'revision.'
            elif old_revision.text == new_revision.text:
                error = 'There are no changes between the current ' \
                        'revision and the revision you want to ' \
                        'restore.'
            else:
                error = ''
                page = old_revision.page
                if request.method == 'POST':
                    change_note = request.form.get('change_note', '')
                    change_note = 'revert' + (change_note and ': ' +
                                              change_note or '')
                    session.add(Revision(page, old_revision.text,
                                         change_note))
                    session.commit()
                    return redirect(href(page_name))

    return Response(generate_template('action_revert.html',
        error=error,
        old_revision=old_revision,
        page=page
    ))
Exemplo n.º 25
0
    def update_status(self, status):
        '''Updates status in the database.

        :param status: the status of the submission
        :return: None
        '''
        self.result = status
        dblock.acquire()

        # Add to problem_solved if solved for first time
        if status == 'good' and not (session.query(ProblemSolved)
                .filter(ProblemSolved.pid == self.pid)
                .filter(ProblemSolved.username == self.username).all()):
            session.add(ProblemSolved(username=self.username, pid=self.pid,
                                      submit_time=self.submit_time))

        session.flush()
        session.commit()
        dblock.release()
Exemplo n.º 26
0
def add_course(category_id):
    try:
        category = session.query(Category).filter_by(id=category_id).one()
    except:
        return error_message(
            404, "Cannot add new course to this category: Category not found.")
    name = request.form.get('name')
    if name:
        course = Course(name=name,
                        description=request.form.get('description'),
                        img_url=request.form.get('img-url'),
                        intro_video_url=request.form.get('intro-video-url'),
                        category_id=category.id)
        session.add(course)
        session.commit()
    else:
        return error_message(400, "Course name is required.")
    return data_message(200, {"Course": course.serialize},
                        "Successfully added a course.")
Exemplo n.º 27
0
    def post(self):
        """Allow a user to register."""
        parser.add_argument('username')
        parser.add_argument('password')

        args = parser.parse_args()
        username = args['username']
        password = args['password']
        exists = session.query(User).filter_by(username=username).first()
        if username and password:
            if exists and exists.username == username:
                return {'message': 'User already exists!'}, 400
            user = User(username=username)
            user.hash_password(password)
            session.add(user)
            session.commit()
            return {'message': 'User {} has been successfully registered'
                               .format(username)}, 201
        return {'message': 'Missing fields!'}, 400
Exemplo n.º 28
0
def edit_course(category_id, course_id):
    try:
        course = session.query(Course).filter_by(
            id=course_id, category_id=category_id).one()
    except:
        return error_message(404, "Cannot update: Course not found.")
    if request.form.get(
            'name'
    ):  # if 'name' is a non-empty value then update else keep current value
        course.name = request.form('name')

    course.description = request.form.get('description')
    course.img_url = request.form.get('img-url')
    course.intro_video_url = request.form.get('intro-video-url')

    session.add(course)
    session.commit()
    return data_message(200, {"Course": course.serialize},
                        "Successfully updated the course.")
Exemplo n.º 29
0
def manage_npc(id: int, npcid: int):
    npc = NPC.query.get(npcid)

    transferform = NPCTransferForm(prefix="npctransfer", npc_id=npcid)

    if npc is None:
        return abort(404)

    if npc.campaign_id != id:
        return abort(404)

    if current_user.profile != npc.campaign.user:
        return abort(404)

    if transferform.submit.data:
        if transferform.validate_on_submit():
            player = UserProfile.query.get(transferform.player.data)
            campaign = npc.campaign

            # Create a copy of the character
            new_character = Character(title=npc.character.title,
                                      body=npc.character.body,
                                      user_id=player.id)

            session.add(new_character)

            # Add the character to the campaign
            campaign.characters.append(new_character)

            # Remove the NPC
            session.delete(npc)

            # Commit changes
            session.commit()

            return redirect(url_for('campaign.view', id=campaign.id))

    transferform.player.choices = [(p.id, p.user.username)
                                   for p in npc.campaign.players]

    return render_template('campaign/managenpc.html.jinja',
                           npc=npc,
                           transferform=transferform)
Exemplo n.º 30
0
def create(chartype: str):

    character_module = globals()[chartype] if chartype in globals() else core

    form = getattr(character_module, 'CreateForm', CreateForm)()
    template = getattr(character_module, 'CREATE_TEMPLATE',
                       'character/create.html.jinja')

    if form.validate_on_submit():
        logger.debug(f"Creating new character specified by {form.data}")
        char_data = character_module.new_character(**form.data)
        c = Character(title=form.title.data,
                      body=char_data,
                      user_id=current_user.profile.id)
        session.add(c)
        session.commit()
        return redirect(url_for('character.view', id=c.id))

    form.system.data = chartype
    return render_template(template, form=form, type=type)
Exemplo n.º 31
0
def create_user():
    # Verify that the poster is an admin
    if current_user.admin == 0:
        return server_error('Must be admin to create users', 401)

    # Get form contents
    username = request.form['username']
    password = request.form['password']
    display = request.form['display']

    # Create the user if doesn't already exist
    user = load_user(username)
    if user is None:
        hashed = bcrypt.generate_password_hash(password)
        user = User(username=username, passw=hashed, display=display, admin=0)
        session.add(user)
        session.flush()
        session.commit()
        return serve_response({})
    return serve_error('username already exists', 401)
Exemplo n.º 32
0
def import_character(type=None, id: int = None, code: str = None):
    logger.debug(f"{type}, {code}, {id}")
    character = None
    if id:
        character = get_character(id, check_author=True)
    elif code is not None:
        invite = Invite.query.get(code)
        if invite is None or invite.table != Character.__tablename__:
            return "Invalid code"
        character = Character.query.get(invite.object_id)

    form = ImportForm(obj=character)
    if form.validate_on_submit():
        c = Character(title=form.title.data,
                      body=form.body.data,
                      user_id=current_user.profile.id)
        session.add(c)
        session.commit()
        return redirect(url_for('character.view', id=c.id))
    return render_template('character/import.html.jinja', form=form, type=None)
Exemplo n.º 33
0
    def insert_into_db(session, model, args_list):
        """
        Insert a number of ORM objects into the session for testing. The number
        of objects inserted is equal to the length of the args_list parameter.

        :param session: the database session to insert into
        :param model: the model class of the objects to be added
        :param args: a list of the arguments to pass to the model constructor
        :param num: the number of ORM objects to create and insert
        :returns: the list of new ORM objects
        """
        results = list()
        for args in args_list:
            model_object = model(**args)
            session.add(model_object)
            session.flush()
            session.commit(self)
            session.refresh(model_object)
            results.append(model_object)

        return results
Exemplo n.º 34
0
    def setUp(self):
        """Instantiate dummy bucketlist details for testing."""
        # create a dummy user
        self.username = fake.user_name()
        self.password = fake.password()
        password_hash = generate_password_hash(self.password)
        self.user = User(username=self.username, password_hash=password_hash)
        session.add(self.user)
        session.commit()

        # create a dummy bucketlist
        self.list_name = 'Ein Schatz finden'
        self.bucketlist = BucketList(list_name=self.list_name,
                                     creator=self.user.user_id)
        session.add(self.bucketlist)
        session.commit()

        # create a dummy bucketlistitem
        self.item_name = 'Ein bisschen Bier trinken'
        self.bucketlistitem = BucketListItems(
            item_name=self.item_name, bucket_id=self.bucketlist.list_id)
        session.add(self.bucketlistitem)
        session.commit()

        # log in a user to retrieve token
        self.response = self.client.post(url_for('login'),
                                         data=json.dumps({
                                             'username':
                                             self.username,
                                             'password':
                                             self.password
                                         }),
                                         content_type='application/json')
        self.token = json.loads(self.response.data)['token']
    def setUp(self):
        """Instantiate dummy bucketlist details for testing."""
        # create a dummy user
        self.username = fake.user_name()
        self.password = fake.password()
        password_hash = generate_password_hash(self.password)
        self.user = User(username=self.username, password_hash=password_hash)
        session.add(self.user)
        session.commit()

        # create a dummy bucketlist
        self.list_name = 'Ein Schatz finden'
        self.bucketlist = BucketList(list_name=self.list_name,
                                     creator=self.user.user_id)
        session.add(self.bucketlist)
        session.commit()

        # create a dummy bucketlistitem
        self.item_name = 'Ein bisschen Bier trinken'
        self.bucketlistitem = BucketListItems(item_name=self.item_name,
                                              bucket_id=self.bucketlist
                                              .list_id)
        session.add(self.bucketlistitem)
        session.commit()

        # log in a user to retrieve token
        self.response = self.client.post(url_for('login'),
                                         data=json.dumps({
                                             'username': self.username,
                                             'password': self.password}),
                                         content_type='application/json')
        self.token = json.loads(self.response.data)['token']
Exemplo n.º 36
0
def edit(id: int):
    c = Campaign.query.get(id)
    form = EditForm(obj=c, prefix="campaign_edit")
    folderform = ChooseFolderForm(prefix="choose_folder")

    if form.submit.data and form.validate_on_submit():
        form.populate_obj(c)
        session.add(c)
        session.commit()
        return redirect(url_for('campaign.view', id=c.id))

    if folderform.choose.data and folderform.validate_on_submit():
        print("Folder form submitted!")
        c.folder = folderform.folder_id.data
        session.commit()
        return redirect(url_for('campaign.view', id=c.id))

    folderform.folder_id.data = c.folder

    return render_template('campaign/edit.html.jinja',
                           form=form,
                           folderform=folderform)
Exemplo n.º 37
0
def upload_file(folder_id=None):
    form = UploadForm(prefix='fileupload')
    if form.validate_on_submit():
        fileobject = form.uploaded.data
        folder = AssetFolder.query.get(form.folder_id.data)

        if folder.owner != current_user.profile:
            abort(403)

        if fileobject.filename:
            filename = secure_filename(fileobject.filename)

            Path(folder.system_path).mkdir(parents=True, exist_ok=True)
            fileobject.save(os.path.join(folder.system_path, filename))

            asset = Asset(filename=fileobject.filename,
                          folder=folder,
                          owner=current_user.profile)
            session.add(asset)
            session.commit()

    return redirect(url_for('userassets.index', folder_id=folder_id))
Exemplo n.º 38
0
def index(folder_id=None):
    if current_user.profile.assetfolders.count() < 1:
        logger.debug("Creating initial folder")
        rootfolder = AssetFolder(title='assets', owner=current_user.profile)
        session.add(rootfolder)
        session.commit()

    if folder_id is not None:
        folder = AssetFolder.query.get(folder_id)
    else:
        folder = current_user.profile.assetfolders \
            .filter(AssetFolder.parent_id.__eq__(None)).first()

    form = UploadForm(folder_id=folder.id, prefix="fileupload")
    folderform = NewFolderForm(parent_id=folder.id, prefix="newfolderform")
    deletefolderform = DeleteAssetFolderForm(id=folder.id,
                                             prefix="deletefolderform")

    return render_template('assets.html.jinja',
                           form=form,
                           folderform=folderform,
                           deletefolderform=deletefolderform,
                           folder=folder)
Exemplo n.º 39
0
    def mutate(self, info, input):
        code_type = ParentCodeType._meta.model(
            code_type_id=input.get("code_type_id"),
            code_type_nm=input.get("code_type_nm"),
            code_type_desc=input.get("code_type_desc"),
            use_yn=input.get("use_yn"),
            sort_order=input.get("sort_order"),
        )

        codes = input.get("codes")
        for code in codes:
            code_type.code.append(
                CodeType._meta.model(code_id=code.get("code_id"),
                                     code_nm=code.get("code_nm"),
                                     code_desc=code.get("code_desc"),
                                     use_yn=code.get("use_yn"),
                                     sort_order=code.get("sort_order")))

        session.add(code_type)
        session.commit()
        success = True

        return CreateParentCode(code_type=code_type, success=success)
Exemplo n.º 40
0
def share(id: int):
    """Share a character."""
    character = get_character(id, check_author=True)
    logger.debug("Finding previous invite")
    invite = Invite.query_for(character).first()
    logger.debug(f"Invites found {invite}")
    if not invite:
        logger.debug(f"Creating an invite for character {character.id}")
        invite = Invite(character)
        invite.owner_id = character.user_id
        session.add(invite)
        session.commit()

    share_url = url_for('character.shared', code=invite.id, _external=True)

    form = None

    html_response = render_template('character/api_share.html.jinja',
                                    form=form,
                                    url=share_url,
                                    code=invite.id)

    return jsonify({'url': share_url, 'html': html_response})
Exemplo n.º 41
0
def message_player(campaign_id: int, player_id: int = None):
    c = Campaign.query.get(campaign_id)
    player = None
    if player_id:
        player = UserProfile.query.get(player_id)

    form = MessagePlayerForm()

    if form.validate_on_submit():
        flash(form.message.data)
        logger.debug(request.form)

        message = Message()
        form.populate_obj(message)
        if not form.to_id.data:
            message.to_id = None

        session.add(message)
        session.commit()

        return redirect(url_for('campaign.view', id=c.id))

    form.campaign_id.data = c.id
    form.to_id.data = player_id
    form.from_id.data = c.user_id

    messages = c.messages.filter(
        or_(
            and_(Message.to_id == player_id,
                 Message.from_id == current_user.profile.id),
            and_(Message.to_id == current_user.profile.id,
                 Message.from_id == player_id)))
    return render_template('campaign/message_player.html.jinja',
                           player=player,
                           campaign=c,
                           form=form,
                           messages=messages)
Exemplo n.º 42
0
def on_edit(request, page_name):
    """Edit the current revision of a page."""
    change_note = error = ''
    revision = Revision.query.filter(
        (Page.name == page_name) &
        (Page.page_id == Revision.page_id)
    ).order_by(Revision.revision_id.desc()).first()
    if revision is None:
        page = None
    else:
        page = revision.page

    if request.method == 'POST':
        text = request.form.get('text')
        if request.form.get('cancel') or \
           revision and revision.text == text:
            return redirect(href(page.name))
        elif not text:
            error = 'You cannot save empty revisions.'
        else:
            change_note = request.form.get('change_note', '')
            if page is None:
                page = Page(page_name)
                session.add(page)
            session.add(Revision(page, text, change_note))
            session.commit()
            return redirect(href(page.name))

    return Response(generate_template('action_edit.html',
        revision=revision,
        page=page,
        new=page is None,
        page_name=page_name,
        change_note=change_note,
        error=error
    ))
Exemplo n.º 43
0
 def commit_to_session(self):
     session.add(self)
     session.flush()
     session.commit()
     session.refresh(self)
Exemplo n.º 44
0
def view(id: int):
    invites = None
    campaign: Campaign = Campaign.query.get(id)

    # Set up forms
    inviteform = InvitePlayerForm(prefix="inviteform")
    createinviteform = CreateInviteForm(prefix="createinviteform")
    characterform = AddCharacterForm(prefix="characterform")
    npcform = AddNPCForm(prefix="npcform")

    messageform = MessagePlayerForm(players=[
        (campaign.user_id, "GM"),
    ] + [(p.id, p.user.username) for p in campaign.players],
                                    campaign_id=campaign.id,
                                    from_id=current_user.profile.id)

    is_player = current_user.profile in campaign.players
    is_owner = current_user and current_user.profile.id == campaign.user_id

    logger.debug(f"Viewing campagin {campaign.title}")
    logger.debug(f"There are {campaign.players.count()} players")
    logger.debug(f"There are {campaign.characters.count()} characters")

    if not is_player and not is_owner:
        abort(404, "This is not the campaign your are looking for.")

    if is_owner:
        if createinviteform.submit.data and \
                createinviteform.validate_on_submit():
            invite = Invite(campaign)
            invite.owner_id = campaign.user_id
            session.add(invite)
            session.commit()

        if inviteform.submit.data and inviteform.validate_on_submit():
            player = (User.query.filter_by(
                email=inviteform.email.data).first().profile)
            campaign.players.append(player)
            session.commit()
            return redirect(url_for('campaign.view', id=id))

        invites = Invite.query_for(campaign)

        if npcform.submit.data and npcform.validate_on_submit():
            print("Adding NPC")
            character = npcform.character.data
            npc = NPC(character=character, campaign=campaign)
            session.add(npc)
            session.commit()

            return redirect(url_for('campaign.view', id=id))

    if characterform.submit.data and characterform.validate_on_submit():
        print("Adding character")
        character = characterform.character.data
        if (character not in campaign.characters
                and character.user_id == current_user.profile.id):
            campaign.characters.append(character)
            session.commit()
        else:
            flash("Character is already added to campaign")

        return redirect(url_for('campaign.view', id=id))

    createinviteform.submit.label.text = "Create share link."

    handouts = campaign.handouts.filter_by(status=HandoutStatus.visible)
    messages = campaign.messages.filter(
        or_(Message.from_id == current_user.profile.id,
            Message.to_id == current_user.profile.id, Message.to_id.is_(None)))

    added_npc_ids = [c.character_id for c in campaign.NPCs]

    npcform.character.query = current_user.profile.characters.filter(
        Character.id.notin_(added_npc_ids)).\
        order_by(
            Character.folder_id.__eq__(campaign.folder_id).desc()).\
        order_by('title')

    added_character_ids = [c.id for c in campaign.characters]
    characterform.character.query = current_user.profile.characters.\
        filter(Character.id.notin_(added_character_ids)).\
        order_by(Character.folder_id.__eq__(campaign.folder_id).desc()).\
        order_by('title')

    return render_template('campaign/campaign.html.jinja',
                           campaign=campaign,
                           handouts=handouts,
                           invites=invites,
                           inviteform=inviteform,
                           createinviteform=createinviteform,
                           characterform=characterform,
                           messages=messages,
                           npcform=npcform,
                           editable=is_owner,
                           messageform=messageform)
Exemplo n.º 45
0
def re_seed():
    Base.metadata.drop_all(engine)
    Base.metadata.create_all(engine)
    
    lacma = POI(name="LACMA",
        category="arts",
        address="5905 Wilshire Blvd, Los Angeles, CA 90036",
        latitude=34.0629,
        longitude= -118.3578,
        desc="Largest art museum in the western United States.  Check out the incredible Latin-American collection.")
    
    venice = POI(name="Venice Beach Boardwalk",
        category="active",
        address="1800 Ocean Front Walk, Los Angeles, CA 90291",
        latitude=33.986,
        longitude= -118.473,
        desc="Best people watching in the entire city.  Wander around, and get your fortune read by one of the palm readers.")
    
    barber = POI(name="The Blind Barber",
        category="drink",
        address="10797 Washington Blvd, Culver City, CA 90232",
        latitude=34.0153,
        longitude= -118.4073,
        desc="Hidden behind an actual barber shop, no sign.  Just walk straight through to the back, and delicious cocktails.")
    
    baco = POI(name="Baco Mercat",
        category="food",
        address="408 S Main St, Los Angeles, CA 90013",
        latitude=34.0479,
        longitude= -118.2474,
        desc="Try one of the amazing flatbread sandwiches!")

    dailypint = POI(name="The Daily Pint",
        category="drink",
        address="2310 Pico Blvd, Santa Monica, CA 90405",
        latitude=34.021084, 
        longitude= -118.466116,
        desc="Hole in the wall, casual and fun.  Start with the scotch.")

    brennans = POI(name="Brennan's Pub",
        category="drink",
        address="4089 Lincoln Blvd, Marina del Rey, CA 90292",
        latitude=33.988296, 
        longitude= -118.446087,
        desc="Turtle Racing.  Yes, seriously!")

    perch = POI(name="Perch",
        category="drink",
        address="448 S Hill St, Los Angeles, CA 90013",
        latitude=34.048858,
        longitude= -118.251316,
        desc="Rooftop bar with some amazing downtown views.  Great Happy Hour!")

    griffith = POI(name="Griffith Park",
        category="active",
        address="2800 E Observatory Rd, Los Angeles, CA 90027",
        latitude=34.118375,
        longitude= -118.300354,
        desc="Great hiking. Go with The Sierra Club on a night hike for some amazing views of the city, all lit up!")

    barnsdall = POI(name="Barnsdall Art Park",
        category="active",
        address="4800 Hollywood Blvd, Los Angeles, CA 90027",
        latitude=34.101528,
        longitude= -118.294334,
        desc="Great place for a picnic, or just a lazy Sunday afternoon.")

    firstfriday = POI(name="Abbot Kinney: First Friday",
        category="other",
        address="1121 Abbot Kinney Blvd, Venice, CA 90291",
        latitude=33.991867,
        longitude= -118.469779,
        desc="Shops and galleries open late in Abbot Kinney on the first Friday of each month.  Also, an amazing collection of food trucks!")

    cinespia = POI(name="Cinespia at Hollywood Forever",
        category="other",
        address="6000 Santa Monica Blvd, Los Angeles, CA 90038",
        latitude=34.090522,
        longitude= -118.319727,
        desc="Scary movies playing outdoors at Hollywood Forever Cemetery around Halloween. Bring a picnic!")

    timetravel = POI(name="Echo Park Time Travel Mart",
        category="other",
        address="1714 Sunset Blvd, Los Angeles, CA 90026",
        latitude=34.077282,
        longitude= -118.259066,
        desc="Quirky store for 'time travelers' in Echo Park. Profits fund the work of 826 Valencia, a nonprofit that focuses on writing education.")

    elmatador = POI(name="El Matador State Beach",
        category="active",
        address="32350 Pacific Coast Hwy, Malibu, CA 90265",
        latitude=34.039051,
        longitude= -118.875141,
        desc="Fewer services means fewer people. Head North toward Malibu to get away from the bustle near Santa Monica and contemplate the waves...")

    flower = POI(name="LA Flower Market",
        category="other",
        address="754 Wall St Los Angeles, CA 90014",
        latitude=34.040473,
        longitude= -118.24961,
        desc="Come early and see an incredible collection of flowers.  Avoid the crowds/bustle on Wednesdays and Fridays if you can.")
    
    largo = POI(name="Largo at the Coronet",
        category="arts",
        address="366 N La Cienega Blvd, Los Angeles, CA 90048",
        latitude=34.077871,
        longitude= -118.376322,
        desc="Both amazing live music and comedy.  Check out ongoing show 'The Thrilling Adventure Hour' for a good laugh!")

    hotelcafe = POI(name="The Hotel Cafe",
        category="arts",
        address="1623 N Cahuenga Blvd, Los Angeles, CA 90028",
        latitude=34.100437,
        longitude= -118.329829,
        desc="Tiny venue in Hollywood hosts some incredible bands that'll probably be famous in a couple years. For now, you can see them for $10!")

    noise = POI(name="A Noise Within",
        category="arts",
        address="3352 E Foothill Boulevard, Pasadena, CA 91107",
        latitude=34.149594,
        longitude= -118.081141,
        desc="Smaller Pasadena theater sticks to the classics.  And does an amazing job with them.")

    tsujita = POI(name="Tsujita",
        category="food",
        address="2057 Sawtelle Blvd, Los Angeles, CA 90025",
        latitude=34.039604, 
        longitude= -118.442753,
        desc="World's. Best. Noodles.  Omnomnomnom.")

    saffron = POI(name="Saffron & Rose",
        category="food",
        address="1387 Westwood Blvd, Los Angeles, CA 90024",
        latitude=34.055425,
        longitude= -118.4422,
        desc="Ice cream with amazing, unique flavors. Try the Cucumber, seriously!")

    kang = POI(name="Kang Ho-Dong Baekjeong",
        category="food",
        address="3465 W 6th St, Los Angeles, CA 90020",
        latitude=34.063733,
        longitude= -118.297282,
        desc="Amazing Korean BBQ in (of course) Koreatown. Knock back a Hite and order everything on the menu.")
    
    places_list = [lacma, venice, barber, baco, dailypint, brennans, 
        perch, griffith, barnsdall, firstfriday, cinespia, timetravel, 
        elmatador, flower, largo, hotelcafe, noise, tsujita, saffron, kang]

    session.add_all(places_list)
    session.commit()

    user1 = User(username="******",
        email="*****@*****.**",
        password=generate_password_hash("test")
        )

    session.add(user1)
    session.commit()

    for place in places_list:
        user1.poi_assocs.append(UserPOI(poi=place, upvote=1))

    session.commit()
    
    #Create sample users and upvotes
    for i in range(1, 20):
        username = "******" + str(i)
        email = "test" + str(i) + "@gmail.com"
        password = "******" + str(i)
        tempuser = User(username=username,
            email=email,
            password=generate_password_hash(password)
            )
        session.add(tempuser)
        session.commit()

        sampsize = random.randint(6, 12)
        sample_likes = random.sample(places_list, sampsize)
        for like in sample_likes:
            tempuser.poi_assocs.append(UserPOI(poi=like, upvote=1))

        session.commit()
Exemplo n.º 46
0
def insert_category(data):
	category = Category()
	category.category = data
	session.add(category)
	session.commit()
Exemplo n.º 47
0
 def commit_to_session(self):
     """Commit this problem to the database as a new template."""
     session.add(self)
     session.flush()
     session.commit()
     session.refresh(self)
Exemplo n.º 48
0
 def commit_to_session(self, session=session):
     """Commit this sample case to the database."""
     session.add(self)
     session.flush()
     session.commit()
     session.refresh(self)
Exemplo n.º 49
0
def add_first_admin(*args, **kwargs):
    session.add(UserRoles(user_id=1, role_id=1))
    session.commit()
Exemplo n.º 50
0
    def mutate(self, info, input):

        parent_query = ParentCodeType.get_query(info).filter_by(
            code_type_id=input.get("code_type_id"))

        # Update CodeType Info
        parent_query.update(
            dict(code_type_nm=input.get("code_type_nm"),
                 code_type_desc=input.get("code_type_desc"),
                 use_yn=input.get("use_yn"),
                 sort_order=input.get("sort_order")))

        # Delete to Insert
        CodeType.get_query(info).filter_by(
            code_type_id=input.get("code_type_id")).delete()
        codes = input.get("codes", None)
        if codes is not None:
            for code in codes:
                child = CodeType._meta.model(
                    **dict(code_type_id=input.get("code_type_id"),
                           code_id=code.get("code_id"),
                           code_nm=code.get("code_nm"),
                           code_desc=code.get("code_desc"),
                           use_yn=code.get("use_yn"),
                           sort_order=code.get("sort_order")))
                session.add(child)

        # Update or Insert
        # codes = input.get("codes", None)
        # if codes is not None:
        #   for code in codes:
        # child_query = CodeType.get_query(info).filter_by(
        #   code_type_id=input.get("code_type_id"),
        #   code_id=input.get("code_id")
        # )

        # child = None
        # if child_query.first() is not None:
        #   child = CodeType.update(dict(
        #     code_nm=code.get("code_nm"),
        #     code_desc=code.get("code_desc"),
        #     use_yn=code.get("use_yn"),
        #     sort_order=code.get("sort_order")
        #   ))
        # else:
        #   child = CodeType._meta.model(**dict(
        #     code_type_id=input.get("code_type_id"),
        #     code_id=code.get("code_id"),
        #     code_nm=code.get("code_nm"),
        #     code_desc=code.get("code_desc"),
        #     use_yn=code.get("use_yn"),
        #     sort_order=code.get("sort_order")
        #   ))

        # session.merge(child)

        session.commit()
        success = True

        return UpdateParentCode(code_type=parent_query.first(),
                                success=success)
Exemplo n.º 51
0
 def commit_to_session(self):
     """Commit this problem to the database as a new template."""
     session.add(self)
     session.flush()
     session.commit()
     session.refresh(self)
Exemplo n.º 52
0
 def commit_to_session(self, session=session):
     """Commit this problem data object to the database."""
     session.add(self)
     session.flush()
     session.commit()
     session.refresh(self)
Exemplo n.º 53
0
 def create(cls, object_create):
     session.add(object_create)
     session.commit()
     return cls.objects().filter_by(company_id=object_create.company_id).first()
Exemplo n.º 54
0
 def save_changes(data):
     session.add(data)
     session.commit()
Exemplo n.º 55
0
def create_core_roles(*args, **kwargs):
    session.add(Role(name='admin'))
    session.commit()