1
#!/usr/bin/python
2
3
# Mouchak Server -
4
# A Flask Application (http://flask.pocoo.org/)
5
6
import flask
7
import pymongo
8
import bson
9
import conf
10
11
app = flask.Flask(__name__)
12
13
14
15
dbClient = pymongo.MongoClient()
16
db = dbClient[conf.DB]
17
siteContent = db['content']
18
siteMenu = db['menu']
19
if siteMenu.find_one() == None:
20
    siteMenu.insert({'customMenu': False, 'menuOrder': [], 'html': ''})
21
22
23
# handy reference to otherwise long name
24
bson.ObjId = bson.objectid.ObjectId
25
26
27
def getContent():
28
    content = []
29
    for i in siteContent.find():
30
        objId = bson.ObjId(i['_id'])
31
        del(i['_id'])
32
        i['id'] = str(objId)
33
        content.append(i)
34
35
    menu = siteMenu.find_one()
36
    objId = bson.ObjId(menu['_id'])
37
    del(menu['_id'])
38
    menu['id'] = str(objId)
39
40
    return {'content': content, 'menu': menu}
41
42
43
@app.errorhandler(404)
44
def pageNotFound(e):
45
    return flask.render_template('404.html'), 404
46
47
48
@app.route('/', methods=['GET'])
49
def index():
50
    return flask.render_template('index.html', content=getContent(),
51
                                 title=conf.SITE_TITLE, footer=conf.SITE_FOOTER)
52
53
54
@app.route('/edit', methods=['GET'])
55
def edit():
56
    if "logged_in" in flask.session:
57
        flask.session['key'] = conf.SECRET_KEY
58
        return flask.render_template('editor.html', content=getContent(),
59
                                     title=conf.SITE_TITLE)
60
    else:
61
        return flask.redirect(flask.url_for('login'))
62
63
64
@app.route('/page', methods=['POST'])
65
def insertPage():
66
    newpage = flask.request.json
67
    print newpage
68
    res = siteContent.insert(newpage)
69
    _id = bson.ObjId(res)
70
    newpage['id'] = str(_id)
71
    del(newpage['_id'])
72
    print newpage
73
    # FIXME: handle errors
74
    return flask.jsonify(status='ok', page=newpage)
75
76
77
@app.route('/page/<_id>', methods=['PUT', 'DELETE'])
78
def updatePage(_id):
79
    if flask.request.method == 'PUT':
80
        changedPage = flask.request.json
81
        print changedPage
82
        print '======='
83
        res = siteContent.update({'_id': bson.ObjId(_id)},
84
                                changedPage)
85
        print res
86
        if res['err'] == None:
87
            print changedPage
88
            return flask.jsonify(status='ok', page=changedPage)
89
90
    elif flask.request.method == 'DELETE':
91
        delPage = flask.request.url
92
        print delPage
93
        print _id
94
        res = siteContent.remove({'_id': bson.ObjId(_id)})
95
        print res
96
        if res['err'] == None:
97
            return flask.jsonify(status='ok')
98
        else:
99
            return flask.jsonify(error=res['err'], status='error')
100
101
102
@app.route('/menu', methods=['POST'])
103
def insertMenu():
104
    #newmenu = flask.request.json
105
    #print newmenu
106
    #res = siteMenu.insert(newmenu)
107
    #print res
108
    #return flask.jsonify(status='success')#, content=getContent())
109
    return '200 OK'
110
111
112
@app.route('/menu/<_id>', methods=['PUT'])
113
def updateMenu(_id):
114
    if flask.request.method == 'PUT':
115
        changedMenu = flask.request.json
116
        print "changed menu:"
117
        print changedMenu
118
        res = siteMenu.update({'_id': bson.ObjId(_id)}, changedMenu)
119
        print res
120
        return flask.jsonify(status='ok', menu=changedMenu)
121
122
    #elif flask.request.method == 'DELETE':
123
    #    delMenu = flask.request.url
124
    #    print delMenu
125
    #    print _id
126
    #    res = siteMenu.remove({'_id': bson.ObjId(_id)})
127
    #    return flask.jsonify(status='deleted')
128
129
130
# Basic login for one single admin user whose credentials are in conf.py
131
@app.route('/login', methods=['GET', 'POST'])
132
def login():
133
    error = None
134
    if flask.request.method == 'POST':
135
        print flask.request.form
136
        if flask.request.form['username'] != conf.ADMIN_USERNAME:
137
            error = 'Invalid username'
138
        elif flask.request.form['password'] != conf.ADMIN_PASSWORD:
139
            error = 'Invaid password'
140
        else:
141
            flask.session['logged_in'] = True
142
            flask.session['key'] = conf.SECRET_KEY
143
            flask.flash('You were logged in')
144
            return flask.redirect(flask.url_for('edit'))
145
    return flask.render_template('login.html', error=error)
146
147
@app.route('/logout')
148
def logout():
149
    flask.session.pop('logged_in', None)
150
    flask.flash('You were logged out')
151
    return flask.redirect(flask.url_for('login'))
152
153
@app.route('/robots.txt')
154
@app.route('/crossdomain.xml')
155
def static_from_root():
156
    return flask.send_from_directory(app.static_folder, request.path[1:])
157
158
159
app.config.from_object(conf)
160
161
import logging,os
162
from logging import FileHandler
163
164
fil = FileHandler(os.path.join(os.path.dirname(__file__),'logme'),mode='a')
165
fil.setLevel(logging.ERROR)
166
app.logger.addHandler(fil)
167
168
169
170
if __name__ == "__main__":
171
    app.run(debug=True, host=conf.HOST, port=conf.PORT)