summaryrefslogtreecommitdiffstats
path: root/notes.py
blob: 8aeb17972b5a69518924c3ecac6d052c41f609dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# -*- coding: utf-8 -*-
 # all the imports
from __future__ import with_statement
from contextlib import closing
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash, jsonify
import requests
from bs4 import BeautifulSoup
import re
from email.mime.text import MIMEText
from subprocess import Popen, PIPE
import smtplib
from note import Note, Page, convert_datestring_to_date

# configuration
DATABASE = 'notes.db'
DEBUG = True
SECRET_KEY = 'development key'
USERNAME = 'admin'
PASSWORD = 'dupa.8'

app = Flask(__name__)
app.config.from_object(__name__)

class Thumb:
    def __init__(self, source, href, tags):
        self.src = source
        self.href = href
        self.tags = tags

#DB functions
def connect_db():
    return sqlite3.connect(app.config['DATABASE'])

def init_db():
    with closing(connect_db()) as db:
         with app.open_resource('schema.sql') as f:
            db.cursor().executescript(f.read())
            db.commit()

def query_db(query, args=(), one=False):
    """
    Simple wrapper around query
    """
    cur = g.db.execute(query, args)
    rv = [dict((cur.description[idx][0], value)
               for idx, value in enumerate(row)) for row in cur.fetchall()]
    return (rv[0] if rv else None) if one else rv

@app.before_request
def before_request():
    try:
        g.db = g._db.cursor()
    except AttributeError:
        g._db = connect_db()
        g.db = g._db.cursor()

@app.teardown_request
def teardown_request(exception):
    try:
        g.db.close()
    except AttributeError:
        pass

#VIEWS
@app.route('/')
@app.route('/view')
@app.route('/view/<subject>/<datestring>')
def home(subject= "mechanika", datestring= "14grudnia2012"):
    other_dates = [date["datestring"] for date in get_possible_dates(subject)]
    all_dates = prepare_all_dates()
    all_subjects = [sub["subject"] for sub in get_all_subjects()]
    thumbs =  get_thumbs(subject, datestring)
    if datestring in other_dates:
        other_dates.remove(datestring)
    thumbs_info = {"subject": subject, "datestring": datestring, "other_dates": other_dates}
    
    print thumbs
    thumbs = [dict(href=thumb.href, src=thumb.src) for thumb in thumbs]
    main_page_src=thumbs[0]["href"]
    print all_dates
    return render_template('index.html', thumbs=thumbs, main_page_src=main_page_src,thumbs_info=thumbs_info,
        all_dates=all_dates, all_subjects=all_subjects)

def prepare_all_dates():
    all_dates = [date["datestring"] for date in get_all_dates()]
    datastrings = [date["datestring"] for date in get_all_dates()]
    all_dates = [convert_datestring_to_date(date) for date in datastrings]
    sorted_dates = {}
    for date, datestring in zip(all_dates, datastrings):
        if not date.datetime.year in sorted_dates:
            sorted_dates[date.datetime.year] = {}
        if not date.datetime.month in sorted_dates[date.datetime.year]:
            sorted_dates[date.datetime.year][date.datetime.month] = []
        sorted_dates[date.datetime.year][date.datetime.month].append({"day" : date.datetime.day, "source": datestring,
         "weekday": weekday(date.datetime.weekday())})
        sorted = sort_number_strings(sorted_dates[date.datetime.year][date.datetime.month])
        sorted_dates[date.datetime.year][date.datetime.month] = sorted
    print sorted_dates
    return sorted_dates

def sort_number_strings(data):
    number_data = [int(day["day"]) for day in data]
    number_data.sort()
    print "sorted date" + str(number_data)
    return [{"day": number, "source": data[get_index_for(number, data)]["source"], 
        "weekday": data[get_index_for(number, data)]["weekday"] } for i, number in enumerate(number_data)]

def weekday(number):
    weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
    return weekdays[number]
def get_index_for(number, data):
    index = 0
    for i, day in enumerate(data):
        if day["day"] == number:
            index = i
    return index

@app.route('/subject/<subject>')
def show_subject(subject):
    dates = [date["datestring"] for date in get_possible_dates(subject)]
    all_dates = prepare_all_dates()
    all_subjects = [sub["subject"] for sub in get_all_subjects()]
    return render_template('subject.html', subject=subject, dates=dates, all_dates=all_dates, all_subjects=all_subjects)

@app.route('/date/<datestring>')
def show_date(datestring):
    all_dates = prepare_all_dates()
    all_subjects = [sub["subject"] for sub in get_all_subjects()]
    notes = get_notes_for_day(datestring)
    separated_notes = {}
    for note in notes:
        if not note["subject"] in separated_notes:
            separated_notes[note["subject"]] = []
        separated_notes[note["subject"]].append(note) 

    return render_template('date.html', date=datestring, all_dates=all_dates, all_subjects=all_subjects, separated_notes=separated_notes)

@app.route('/search')
def show_search():
    all_dates = prepare_all_dates()
    all_subjects = [sub["subject"] for sub in get_all_subjects()]
    return render_template('search.html', all_dates=all_dates, all_subjects=all_subjects )

@app.route('/about')
def about():
    all_dates = prepare_all_dates()
    all_subjects = [sub["subject"] for sub in get_all_subjects()]
    return render_template('about.html', all_dates=all_dates, all_subjects=all_subjects )

#HELPERS
def add_note(subject, datestring, notes):
    g.db.execute('insert into notes (subject, datestring ) values (?, ?)', [subject, datestring])
    note_id = g.db.lastrowid
    for note in notes:
        g.db.execute('insert into pages (note_id, name, tags ) values (?, ?, ?)', [note_id, note["name"], note["tags"]])
    g._db.commit()

def create_thumb(subject, datestring, name, tags):
    src = subject + "/" + datestring + "/" + name
    href = src 
    thumb = Thumb(src, href, tags)
    return thumb

def get_thumbs(subject, datestring=""):
    if(datestring==""):
        query_result = query_db("select pages.* from pages left join notes on notes.id = pages.note_id where notes.subject = ?", [subject,])
    else:
        query_result = query_db("select pages.* from pages left join notes on notes.id = pages.note_id \
            where notes.subject = ? and datestring = ?", [subject, datestring])
        print query_result
    return [create_thumb(subject, datestring, t["name"], t["tags"]) for t in query_result ]
    
def get_possible_dates(subject):
    dates = query_db("select distinct datestring from notes where subject = ? ", [subject])
    return dates

def get_notes_for_day(datestring):
    """returns pages which where written that day (daystring) with other info"""
    query_result = query_db("select pages.*,notes.subject from pages left join notes on notes.id = pages.note_id \
            where datestring = ?", [datestring])
    return [{"subject": t["subject"], "datestring": datestring, "name": t["name"]}for t in query_result ]

def get_all_dates():
    dates = query_db("select distinct datestring from notes ")
    return dates

def get_all_subjects():
    subjects = query_db("select distinct subject from notes ")
    return subjects



if __name__ == '__main__':
    app.run()