def social_network_handler(author_id):
    ses = get_session()
    try:
        author = ses.query(Author).filter(Author.id == author_id).one()
        return render_template("social_network.html", author=author)
    except NoResultFound:
        return render_template("404.html"), 404
def affiliation_authors_handler_get(affiliation_id):
    ses = get_session()
    try:
        affiliation = ses.query(Affiliation).filter_by(id=affiliation_id).one()
    except NoResultFound:
        return render_template("404.html"), 404
    return render_template("affiliation_authors.html", affiliation=affiliation)
def user_authors_handler_post(user_id):
    """Creates an association between users and authors"""
    ses = get_session()
    param_authors = request.form.getlist('authors')
    if not param_authors:
        flash("You must complete all fields", "alert-error")
        return redirect(url_for('subscriptions_handler_new_get'))
    for ra in param_authors:
        param_author_name = ra.split()[0]
        param_author_surname = ra.split()[-1]
        print param_author_name
        print param_author_surname

        try:
            user = ses.query(User).filter_by(id=g.user.id).one()
        except NoResultFound:
            return render_template("404.html"), 404
            # user = User()
            # user.email = param_email
            # user.skype_name = param_skype_name

        try:
            author = ses.query(Author).\
            filter_by(name=param_author_name).\
            filter_by(surname=param_author_surname).one()
        except NoResultFound:
            author = Author(param_author_name, param_author_surname)

        user.authors.append(author)
        ses.add(user)
    ses.commit()
    flash("Authors Added", "alert-success")
    return redirect(url_for('subscriptions_handler_new_get'))
def affiliation_stats_handler_get(affiliation_id):
    """Retrieves statistics about an affiliation"""
    ses = get_session()
    try:
        last_years = int(request.values['last_years'])
    except KeyError:
        return render_template("404.html"), 404
    end_year = datetime.date.today().year
    start_year = end_year - last_years
    years = [y for y in range(start_year + 1, end_year + 1)]
    try:
        affiliation = ses.query(Affiliation).filter_by(id=affiliation_id).one()
    except NoResultFound:
        return render_template("404.html"), 404
    response = {}
    response['result'] = {}
    print years
    response['result']['labels'] = []
    response['result']['datasets'] = {}
    response['result']['datasets']['data'] = []
    for y in years:
        dy = datetime.date(y, 1, 1)
        response['result']['labels'].append(y)
        stats = len(ses.query(Publication, Author).join(Publication, Author.pubs).join(Affiliation, Author.affiliation).filter(Publication.year==dy, Affiliation.id==affiliation.id).all())
        print stats
        response['result']['datasets']['data'].append(str(stats))
        print response
    return jsonify(response)
def user_affiliations_handler_put(user_id):
    """Creates an association between users and affiliations"""
    ses = get_session()
    try:
        param_affiliations = request.values.getlist('affiliations[]')
    except:
        tb = traceback.format_exc()
        print tb


    try:
        user = ses.query(User).filter_by(id=g.user.id).one()
    except NoResultFound:
        return render_template("404.html"), 404

    affiliations_to_add = []
    for ra in param_affiliations:
        try:
            affiliation = ses.query(Affiliation).filter_by(id=ra).one()
        except NoResultFound:
            return render_template("404.html"), 404

        affiliations_to_add.append(affiliation)

    user.affiliations = affiliations_to_add
    ses.add(user)
    ses.commit()
    return "OK"
def affiliation_recent_pubs_handler(aff_id):
    """Retrieves most recent publications about an author"""
    try:
        pub_count = int(request.values['pub_count'])
    except KeyError:
        return "Server Error", 505

    ses = get_session()
    try:
        affiliation = ses.query(Affiliation).filter_by(id=aff_id).one()
    except NoResultFound:
        return render_template("404.html"), 404

    try:

        pubs_tuple = ses.query(Author, Publication).join(Author.affiliation).join(Author.pubs).filter(Affiliation.id==affiliation.id).order_by('year desc').limit(pub_count).all()
        pubs = []
        for p in pubs_tuple:
            pubs.append(p[1])
        response = {}
        response['result'] = {}
        response['result']['titles'] = [p.title for p in pubs]
        response['result']['urls'] = [p.url for p in pubs]
        return jsonify(response)
    except NoResultFound:
        return render_template("404.html"), 404
    return str(affiliation)
def publication_handler_get(pub_id):
    ses = get_session()
    try:
        pub = ses.query(Publication).filter_by(id=pub_id).one()
        return render_template("publication_details.html", pub=pub)
    except NoResultFound:
        return render_template("404.html"), 404
def user_handler_post(user_id):
    """Updates details for a user"""
    ses = get_session()
    param_email = request.form['email']
    param_skype_name = request.form['skype_name']

    try:
        param_skype_notifications = request.form['skype_notifications']
    except KeyError:
        param_skype_notifications = None

    try:
        param_email_notifications = request.form['email_notifications']
    except KeyError:
        param_email_notifications = None

    try:
        user = ses.query(User).filter_by(id=user_id).one()
        user.email = param_email
        user.skype_name = param_skype_name
        if param_skype_notifications == 'on':
            user.skype_notifications = True
        else:
            user.skype_notifications = False
        if param_email_notifications == 'on':
            user.email_notifications = True
        else:
            user.email_notifications = False
        ses.add(user)
        ses.commit()
        flash("User details successfully updated", "alert-success")
        return redirect(url_for('user_handler_get', user_id=user.id))
    except NoResultFound:
        return "User not Found"
def user_authors_handler_delete(user_id, author_id):
    """ Deletes the association between the user and the requested author. """
    ses = get_session()

    try:
        user = ses.query(User).filter_by(id=user_id).one()
    except NoResultFound:
        return render_template("404.html"), 404

    try:
        author = ses.query(Author).\
                filter_by(id=author_id).one()
    except NoResultFound:
        return render_template("404.html"), 404

    user.authors.remove(author)

    if not author.users:
        ses.delete(author)
        for p in author.pubs:
            ses.delete(p)
    ses.add(user)
    ses.commit()
    print user
    print user.id
    return redirect(url_for('user_authors_handler_get', user_id=user.id))
def author_publications_handler(author_id):
    """Retrieves all publications for an author"""
    ses = get_session()
    try:
        author = ses.query(Author).filter_by(id=author_id).one()
        return render_template('author_publications.html', author=author)
    except NoResultFound:
        return render_template("404.html"), 404
def user_handler_get(user_id):
    """Retrieves details about a user"""
    ses = get_session()
    try:
        user = ses.query(User).filter_by(id=user_id).one()
        return render_template("user_details.html", user=user)
    except NoResultFound:
        return render_template("404.html"), 404
def affiliation_handler_get(affiliation_id):
    ses = get_session()
    try:
        affiliation = ses.query(Affiliation).\
                filter_by(id=affiliation_id).one()
        return render_template("affiliation_details.html",
                ra=affiliation)
    except NoResultFound:
        return render_template('404.html'), 404
def author_handler_get(author_id):
    """Retrieves details about an author"""
    ses = get_session()
    try:
        author = ses.query(Author).filter_by(id=author_id).one()
        affiliations = ses.query(Affiliation).all()
        return render_template("author_details.html", author=author, affiliations=affiliations)
    except NoResultFound:
        return render_template("404.html"), 404
def user_handler_delete(user_id):
    """Deletes a user"""
    ses = get_session()
    try:
        u = ses.query(User).filter_by(id=user_id).one()
        ses.delete(u)
        ses.commit()
        flash("User deleted", "alert-success")
        return redirect(url_for('users_handler_get'))
    except NoResultFound:
        return render_template("404.html"), 404
def author_handler_delete(author_id):
    """Deletes an author"""
    ses = get_session()
    print "Delete author"
    try:
        a = ses.query(Author).filter_by(id=author_id).one()
        ses.delete(a)
        ses.commit()
        return redirect(url_for('authors_handler_get'))
    except NoResultFound:
        return render_template("404.html"), 404
def affiliation_handler_delete(affiliation_id):
    ses = get_session()
    try:
        affiliation = ses.query(Affiliation).\
                filter_by(id=affiliation_id).one()
        ses.delete(affiliation)
        ses.commit()
        flash("Affiliation deleted", "alert-success")
        return "OK"
    except NoResultFound:
        return render_template('404.html'), 404
def affiliations_handler_get():
    ses = get_session()
    json = None
    try:
        json = request.values['json']
    except KeyError:
        pass
    affiliations = ses.query(Affiliation).all()
    if json == "true":
        response = [(a.id, str(a.university) + " , " + str(a.department)) for a in affiliations]
        return jsonify(response)
    return render_template("affiliations.html", affiliations=affiliations)
def user_authors_handler_put(user_id):
    """Update the association between a user and its authors"""
    ses = get_session()
    try:
        param_authors = request.values.getlist('authors[]')
    except:
        tb = traceback.format_exc()
        print tb

    try:
        user = ses.query(User).filter_by(id=g.user.id).one()
    except NoResultFound:
        return render_template("404.html"), 404

    authors_to_add = []
    for ra in param_authors:
        param_author_name = ra.split()[0]
        param_author_surname = ra.split()[-1]

        try:
            author = ses.query(Author).\
            filter_by(name=param_author_name).\
            filter_by(surname=param_author_surname).one()
        except NoResultFound:
            author = Author(param_author_name, param_author_surname)
        authors_to_add.append(author)

    authors_to_delete = []

    for a in user.authors:
        print "author:", a
        if a not in authors_to_add:
            print "going to delete"
            print a.users
            authors_to_delete.append(a)

    print "user.authors:", user.authors
    print "authors_to_delete:", authors_to_delete
    print "authors_to_add:", authors_to_add
    user.authors = authors_to_add
    ses.add(user)
    for a in authors_to_delete:
        print "difference : %s" %a
        if not a.users:
            print "deleting: %s" %a
            ses.delete(a)
    ses.commit()
    flash("Subscribed Authors Updated", "alert-success")
    return redirect(url_for('subscriptions_handler_new_get')), 200
def authors_handler_post():
    """Creates a new author"""
    ses = get_session()
    author_name = request.form['author_name']
    author_surname = request.form['author_surname']
    try:
        author = ses.query(Author).\
                filter_by(name=author_name).\
                filter_by(surname=author_surname).one()
    except NoResultFound:
        author = Author(author_name, author_surname)
    ses.add(author)
    ses.commit()
    flash("Author created successfully", "alert-success")
    return redirect(url_for('authors_handler_get'))
def users_handler_post():
    """Creates a new user"""
    ses = get_session()
    email = request.form['email']
    skype_name = request.form['skype_name']
    try:
        user = ses.query(User).filter_by(email=email).one()
    except:
        user = User()
        user.email = email
        user.skype_name = skype_name
        ses.add(user)
        ses.commit()
    flash("User created successfully", "alert-success")
    return redirect(url_for('user_handler_get', user_id=user.id))
def affiliation_handler_post(affiliation_id):
    ses = get_session()
    university = request.form.get('university')
    department = request.form.get('department')
    try:
        affiliation = ses.query(Affiliation).\
                filter_by(id=affiliation_id).one()
        affiliation.university = university
        affiliation.department = department
        ses.add(affiliation)
        ses.commit()
        flash("Affiliation details updated successfully", "alert-success")
        return redirect(url_for('affiliation_handler_get', affiliation_id=affiliation.id))
    except NoResultFound:
        return render_template('404.html'), 404
def subscriptions_handler_new_get():
    """Renders template for a new subscription"""
    ses = get_session()
    try:
        user = ses.query(User).filter_by(id=g.user.id).one()
    except NoResultFound:
        print "Error: User not found"
        return "error", 404

    affiliations = ses.query(Affiliation).all()
    formated_authors = ""
    for a in user.authors:
        formated_authors += str(a.id) + ":" + a.name + " " + a.surname + ","
    print formated_authors
    return render_template("subscribe_view.html", user=user, authors=user.authors, formated_authors=formated_authors, affiliations=affiliations)
def affiliations_handler_post():
    """View for creating a new affiliation"""
    ses = get_session()
    param_aff_univ = request.form['university']
    print param_aff_univ
    param_aff_dep = request.form['department']
    print param_aff_dep
    try:
        affiliation = ses.query(Affiliation).\
        filter_by(university=param_aff_univ).\
        filter_by(department=param_aff_dep).one()
    except NoResultFound:
        affiliation = Affiliation(param_aff_univ, param_aff_dep)
    ses.add(affiliation)
    ses.commit()
    return redirect(url_for('affiliations_handler_get'))
def users_affiliations_get(user_id):
    ses = get_session()
    try:
        user = ses.query(User).filter_by(id=user_id).one()
    except NoResultFound:
        return render_template("404.html"), 404
    try:
        response = {}
        param_json = request.values['json']
        if param_json.lower() == 'true':
            response['result'] = user.serialize['affiliations']
            return jsonify(response)
    except KeyError:
        pass
    affiliations = ses.query(Affiliation).all()
    return render_template('affiliation_users.html', user=user, affiliations=affiliations)
def user_authors_handler_get(user_id):
    """Retrieves all authors for a user"""
    ses = get_session()
    try:
        user = ses.query(User).filter_by(id=user_id).one()
    except NoResultFound:
        return render_template("404.html"), 404

    try:
        response = {}
        param_json = request.values['json']
        if param_json.lower() == 'true':
            response['result'] = user.serialize['authors']
            print response
            return jsonify(response)
    except KeyError:
        pass
    authors = ses.query(Author).all()
    return render_template('authors_users.html', user=user, authors=authors)
def main():
    sys.path.append(os.path.abspath(os.path.dirname(CRAWLER_DIR)))
    while True:
        try:
            crawler_modules = get_crawler_modules(CRAWLER_DIR)
            print "crawler modules : %s" % crawler_modules
            ses = db_handler.get_session()
            authors = ses.query(Author).all()
            ses.remove()
            ses.close()
            print authors
            for author in authors:
                print "Crawling for author : %s" % author
                start = time.time()
                for crawler_module in crawler_modules:
                    tasks.crawl(crawler_module, repr(author))
                print "Crawling time : %f" % (time.time() - start)
            time.sleep(1)
        except KeyboardInterrupt:
            sys.exit(0)
def after_login(resp):
    print "After Login"
    ses = get_session()
    if resp.email is None or resp.email == "":
        flash("Invalid login. Please try again.", "alert-error")
        return redirect(url_for('login'))
    user = ses.query(User).filter_by(email=resp.email).first()
    if user is None:
        nickname = resp.nickname
        if nickname is None or nickname == "":
            nickname = resp.email.split('@')[0]
        user = User()
        user.nickname = nickname
        user.email = resp.email
        user.role = ROLE_USER
        ses.add(user)
        ses.commit()
    remember_me = False
    if 'remember_me' in session:
        remember_me = session['remember_me']
        session.pop('remember_me', None)
    login_user(user, remember=remember_me)
    return redirect(request.args.get('next') or url_for('index'))
def graph_handler(author_id):
    ses = get_session()

    q = """select distinct a.name,a.surname,ap1.author_id,ap2.author_id
    from authors_pubs ap1,authors_pubs ap2, authors a
    where ap1.publication_id = ap2.publication_id
    and ap1.author_id = %s
    and ap1.author_id < ap2.author_id
    and ap2.author_id = a.id""" % author_id

    result = ses.execute(q).fetchall()
    print result
    links = []
    authors = []
    for r1, r2, r3, r4 in result:
        links.append((r3, r4))
        authors.append((r1, r2))

    response = {}
    response["links"] = []
    response["nodes"] = []
    for a in authors:
        response["nodes"].append({"name": a[0][0] + '. ' + a[1], "group": 0})
    return jsonify(response)
def author_handler_post(author_id):
    """Updates details for an author"""
    ses = get_session()

    try:
        author = ses.query(Author).filter_by(id=author_id).one()
    except NoResultFound:
        print "author not found"
        return render_template("404.html"), 404

    try:
        name = request.values['author_name']
        author.name = name
    except:
        name = None

    try:
        surname = request.values['author_surname']
        author.surname = surname
    except:
        surname = None

    try:
        param_affiliation_id = request.form['value']
        try:
            aff = ses.query(Affiliation).filter_by(id=param_affiliation_id).one()
            author.affiliation = aff
        except NoResultFound:
            print "no affiliation found"
            pass
    except:
        param_affiliation_id = None

    ses.add(author)
    ses.commit()
    return redirect(url_for('author_handler_get', author_id=author.id))
def publications_handler_get():
    ses = get_session()
    pubs = ses.query(Publication).all()
    return render_template("publications.html", pubs=pubs)