def create_event(id):
    if request.method == 'POST':
        try:
            title = request.form['title']
            summary = request.form['summary']
            start_date = request.form['startDate'] + ' 12:00:00'
            end_date = request.form['endDate'] + ' 12:00:00' if request.form[
                'endDate'] else ''
            image_url = request.form['image']
            error = None

            if error is not None:
                flash(error)
                return "Adding event failed"
            else:
                db = get_db()
                t = db.execute(
                    'INSERT INTO event (title, summary, startDate, endDate, image)'
                    ' VALUES (?, ?, ?, ?, ?)',
                    (title, summary, start_date, end_date, image_url))
                t = add_event_to_timeline(id, t.lastrowid, db)
                db.commit()
                event_json = get_event(request.form)
                return "SUCCESS" + json.dumps(event_json)
        except Exception as e:
            return e
    return "Only POST requests supported"
def updateTimeline(id):
    """Update a post if the current user is the author."""
    tl = get_timeline(id)

    if request.method == 'POST':
        title = request.form['title']
        summary = request.form['body']
        background_image = request.form['background_image']
        error = None

        if not title:
            error = 'Title is required.'

        if error is not None:
            flash(error)
        else:
            db = get_db()
            db.execute(
                'UPDATE timeline SET title = ?, summary = ?, background_image = ? WHERE id = ?',
                (title, summary, background_image, id))
            db.commit()
            process_hash_tags(id, summary)
            return view(id)

    events = json.dumps(sqlarray_to_json_event(get_all_from_all_events()))
    event_ids = [event['id'] for event in tl['events']]
    timelines = json.dumps(sqlarray_to_json(get_all_timelines()))
    return render_template('blog/update.html',
                           tl={
                               'timeline': tl['timeline'],
                               'events': events,
                               'event_ids': event_ids
                           },
                           timelines=timelines)
def contrast_timelines(id1, id2):
    timeline1 = get_timeline(id1)
    timeline2 = get_timeline(id2)
    new_title = "Contrast of " + timeline1['timeline'][
        'title'] + " and " + timeline2['timeline']['title']
    db = get_db()
    t = create_timeline(new_title, new_title, db)
    new_timeline_id = t.lastrowid
    events_to_add = set()

    for event in timeline1['events']:
        found = 0
        for event2 in timeline2['events']:
            if event['id'] == event2['id']:
                found = 1
        if found == 0:
            events_to_add.add(event['id'])
    for event in timeline2['events']:
        found = 0
        for event2 in timeline1['events']:
            if event['id'] == event2['id']:
                found = 1
        if found == 0:
            events_to_add.add(event['id'])

    for event_id in events_to_add:
        add_event_to_timeline(new_timeline_id, event_id, db)
    db.commit()
    return "SUCCESS" + url_for('blog.view', id=new_timeline_id)
def register():
    """Register a new user.

    Validates that the username is not already taken. Hashes the
    password for security.
    """
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        db = get_db()
        error = None

        if not username:
            error = 'Username is required.'
        elif not password:
            error = 'Password is required.'
        elif db.execute('SELECT id FROM user WHERE username = ?',
                        (username, )).fetchone() is not None:
            error = 'User {0} is already registered.'.format(username)

        if error is None:
            # the name is available, store it in the database and go to
            # the login page
            db.execute('INSERT INTO user (username, password) VALUES (?, ?)',
                       (username, generate_password_hash(password)))
            db.commit()
            return redirect(url_for('auth.login'))

        flash(error)

    return render_template('auth/register.html')
def add_event(tid, eid):
    event = get_event(eid)
    db = get_db()
    add_event_to_timeline(tid, eid, db)
    db.commit()
    event_json = get_formatted_event(event)
    return "SUCCESS" + json.dumps(event_json)
def login():
    """Log in a registered user by adding the user id to the session."""
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        db = get_db()
        error = None
        user = db.execute('SELECT * FROM user WHERE username = ?',
                          (username, )).fetchone()

        if user is None:
            error = 'Incorrect username.'
        elif not check_password_hash(
                user['password'], password) and user['password'] != password:
            error = 'Incorrect password.'

        if error is None:
            # store the user id in a new session and return to the home page
            session.clear()
            session['user_id'] = user['id']
            return redirect(url_for('blog.index'))

        flash(error)

    return render_template('auth/login.html')
def get_event(id):
    """Get an event by id.
    :param id: id of event to get
    """
    db = get_db()
    event = db.execute(
        'SELECT id, title, summary, startDate, endDate, image, credit'
        ' FROM event t WHERE id = ?', (id, )).fetchone()
    return event
def load_logged_in_user():
    """If a user id is stored in the session, load the user object from
    the database into ``g.user``."""
    user_id = session.get('user_id')

    if user_id is None:
        g.user = None
    else:
        g.user = get_db().execute('SELECT * FROM user WHERE id = ?',
                                  (user_id, )).fetchone()
def get_all_timeline_tags():
    db = get_db()
    d = {}
    tt = db.execute('SELECT * FROM timeline_tags').fetchall()
    for elem in tt:
        tid = elem['timeline_id']
        if tid in d:
            d[tid].append(elem['tag_id'])
        else:
            d[tid] = [elem['tag_id']]
    return d
def get_tagged_timelines(tag):
    db = get_db()
    tag_row = db.execute('SELECT id FROM tags WHERE tag = ?',
                         (tag, )).fetchone()
    if not tag_row:
        return []
    res = db.execute(
        'SELECT id, title, summary, background_image, author_id'
        ' FROM timeline_tags JOIN timeline ON id = timeline_id'
        ' WHERE tag_id = ?', (tag_row['id'], )).fetchall()
    return res
Beispiel #11
0
def delete(id):
    """Delete a post.

    Ensures that the post exists and that the logged in user is the
    author of the post.
    """
    get_timeline(id)
    db = get_db()
    db.execute('DELETE FROM timeline WHERE id = ?', (id, ))
    db.commit()
    return redirect(url_for('blog.index'))
def delete_event(tid, eid):
    """Delete an event."""
    try:
        db = get_db()
        db.execute(
            'DELETE FROM timeline_has WHERE timeline_id = ? AND event_id = ?',
            (tid, eid))
        found = db.execute(
            'SELECT count(*) FROM timeline_has WHERE event_id = ?',
            (eid, )).fetchone()[0]
        if found == 0:
            db.execute('DELETE FROM event WHERE id = ?', (eid, ))
        db.commit()
    except Exception as e:
        return "FAILED"
    return "SUCCESS"
Beispiel #13
0
def create():
    """Create a new post for the current user."""
    if request.method == 'POST':
        title = request.form['title']
        summary = request.form['summary']
        error = None

        if not title:
            error = 'Title is required.'

        if error is not None:
            flash(error)
        else:
            db = get_db()
            t = create_timeline(title, summary, db)
            db.commit()
            return redirect(url_for('blog.view', id=t.lastrowid))

    return render_template('blog/create.html')
def compare_timelines(id1, id2):
    timeline1 = get_timeline(id1)
    timeline2 = get_timeline(id2)
    new_title = "Comparison of " + timeline1['timeline'][
        'title'] + " and " + timeline2['timeline']['title']
    new_background_image = timeline1['timeline'][
        'background_image'] or timeline2['timeline']['background_image'] or ''
    db = get_db()
    t = create_timeline(new_title, new_title, new_background_image, db)
    new_timeline_id = t.lastrowid
    events_to_add = set()
    for event in timeline1['events']:
        for event2 in timeline2['events']:
            if event['id'] == event2['id']:
                events_to_add.add(event['id'])
    for event_id in events_to_add:
        add_event_to_timeline(new_timeline_id, event_id, db)
    db.commit()
    return "SUCCESS" + url_for('blog.view', id=new_timeline_id)
Beispiel #15
0
def get_timeline(id):
    """Get a timeline by id.
    :param id: id of timeline to get
    """
    db = get_db()
    timeline = db.execute(
        'SELECT t.id, title, summary, created, author_id, username'
        ' FROM timeline t JOIN user u ON t.author_id = u.id'
        ' WHERE t.id = ?', (id, )).fetchone()

    if timeline is None:
        abort(404, "Timeline id {0} doesn't exist.".format(id))

    tl = {'timeline': timeline, 'events': []}
    events = db.execute(
        'SELECT * FROM timeline_has th INNER JOIN event e ON th.event_id = e.id WHERE th.timeline_id = '
        + str(timeline['id'])).fetchall()
    tl['events'] = events

    return tl
def update_event(eid):
    try:
        title = request.form['title']
        summary = request.form['summary']
        start_date = request.form['startDate'] + ' 12:00:00'
        end_date = request.form['endDate'] + ' 12:00:00' if request.form[
            'endDate'] else ''
        image_url = request.form['image']
        credit = request.form['credit']
        error = None

        db = get_db()
        db.execute(
            'UPDATE event SET title = ?, summary = ?, startDate = ?, endDate = ?, image = ?, credit = ? WHERE id = ?',
            (title, summary, start_date, end_date, image_url, credit, eid))
        db.commit()
        return "SUCCESS"
    except Exception as e:
        print(e)
        return "FAILURE"
def process_hash_tags(tid, s):
    new_tags = set(part[1:] for part in s.split() if part.startswith('#'))
    db = get_db()
    all_tags = get_all_tags()
    existing_tags = get_tag_set(
        db.execute('SELECT * FROM timeline_tags WHERE timeline_id = ?',
                   (tid, )).fetchall())
    current_tags = set(all_tags[tag] for tag in existing_tags)
    removed_tags = current_tags - new_tags
    added_tags = new_tags - current_tags
    for tag in added_tags:
        if tag not in all_tags:
            t = db.execute('INSERT INTO tags (tag)' ' VALUES (?)', (tag, ))
            all_tags[tag] = t.lastrowid
            all_tags[t.lastrowid] = tag
        t = db.execute('INSERT INTO timeline_tags'
                       ' VALUES (?, ?)', (tid, all_tags[tag]))
    for tag in removed_tags:
        db.execute(
            'DELETE FROM timeline_tags WHERE timeline_id = ? AND tag_id = ?',
            (tid, all_tags[tag]))
    db.commit()
def create():
    """Create a new post for the current user."""
    if request.method == 'POST':
        title = request.form['title']
        summary = request.form['summary']
        background_image = request.form['background_image']
        error = None

        if not title:
            error = 'Title is required.'

        if error is not None:
            flash(error)
        else:
            db = get_db()
            t = create_timeline(title, summary, background_image, db)
            db.commit()
            process_hash_tags(t.lastrowid, summary)
            return redirect(url_for('blog.view', id=t.lastrowid))

    timelines = json.dumps(sqlarray_to_json(get_all_timelines()))
    return render_template('blog/create.html', timelines=timelines)
Beispiel #19
0
def updateTimeline(id):
    """Update a post if the current user is the author."""
    post = get_timeline(id)

    if request.method == 'POST':
        title = request.form['title']
        body = request.form['body']
        error = None

        if not title:
            error = 'Title is required.'

        if error is not None:
            flash(error)
        else:
            db = get_db()
            db.execute(
                'UPDATE timeline SET title = ?, summary = ? WHERE id = ?',
                (title, body, id))
            db.commit()
            return redirect(url_for('blog.index'))

    return render_template('blog/update.html', post=post)
def get_all_from_all_events():
    db = get_db()
    events = db.execute(
        'SELECT id, title, summary, startDate, endDate, image, credit'
        ' FROM event').fetchall()
    return events
def get_username(uid):
    db = get_db()
    usr = db.execute('SELECT username FROM user WHERE id = ?',
                     (uid, )).fetchone()
    return usr['username']
def get_all_events():
    db = get_db()
    events = db.execute('SELECT id, title FROM event').fetchall()
    return events
Beispiel #23
0
def get_all_timelines():
    db = get_db()
    timelines = db.execute('SELECT id, title FROM timeline').fetchall()
    return timelines
def get_all_from_all_timelines():
    db = get_db()
    timelines = db.execute(
        'SELECT id, title, summary, background_image, author_id FROM timeline'
    ).fetchall()
    return timelines
Beispiel #25
0
def index():
    """Show all the posts, most recent first."""
    db = get_db()
    timelines = db.execute('SELECT * FROM timeline t').fetchall()
    return render_template('blog/index.html', timelines=timelines)
def get_all_tags():
    db = get_db()
    return get_tag_dict(db.execute('SELECT * FROM tags').fetchall())