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
    return flask.jsonify(newpage)
76
77
78
@app.route('/page/<_id>', methods=['PUT', 'DELETE'])
79
def updatePage(_id):
80
    if flask.request.method == 'PUT':
81
        changedPage = flask.request.json
82
        print changedPage
83
        print '======='
84
        res = siteContent.update({'_id': bson.ObjId(_id)},
85
                                changedPage)
86
        print res
87
        if res['err'] == None:
88
            print changedPage
89
            #return flask.jsonify(status='ok', page=changedPage)
90
            return flask.jsonify(changedPage)
91
92
    elif flask.request.method == 'DELETE':
93
        delPage = flask.request.url
94
        print delPage
95
        print _id
96
        res = siteContent.remove({'_id': bson.ObjId(_id)})
97
        print res
98
        if res['err'] == None:
99
            return flask.jsonify(status='ok')
100
        else:
101
            return flask.jsonify(error=res['err'], status='error')
102
103
104
@app.route('/menu', methods=['POST'])
105
def insertMenu():
106
    #newmenu = flask.request.json
107
    #print newmenu
108
    #res = siteMenu.insert(newmenu)
109
    #print res
110
    #return flask.jsonify(status='success')#, content=getContent())
111
    return '200 OK'
112
113
114
@app.route('/menu/<_id>', methods=['PUT'])
115
def updateMenu(_id):
116
    if flask.request.method == 'PUT':
117
        changedMenu = flask.request.json
118
        print "changed menu:"
119
        print changedMenu
120
        res = siteMenu.update({'_id': bson.ObjId(_id)}, changedMenu)
121
        print res
122
        #return flask.jsonify(status='ok', menu=changedMenu)
123
        return flask.jsonify(changedMenu)
124
125
    #elif flask.request.method == 'DELETE':
126
    #    delMenu = flask.request.url
127
    #    print delMenu
128
    #    print _id
129
    #    res = siteMenu.remove({'_id': bson.ObjId(_id)})
130
    #    return flask.jsonify(status='deleted')
131
132
133
# Basic login for one single admin user whose credentials are in conf.py
134
@app.route('/login', methods=['GET', 'POST'])
135
def login():
136
    error = None
137
    if flask.request.method == 'POST':
138
        print flask.request.form
139
        if flask.request.form['username'] != conf.ADMIN_USERNAME:
140
            error = 'Invalid username'
141
        elif flask.request.form['password'] != conf.ADMIN_PASSWORD:
142
            error = 'Invaid password'
143
        else:
144
            flask.session['logged_in'] = True
145
            flask.session['key'] = conf.SECRET_KEY
146
            flask.flash('You were logged in')
147
            return flask.redirect(flask.url_for('edit'))
148
    return flask.render_template('login.html', error=error)
149
150
@app.route('/logout')
151
def logout():
152
    flask.session.pop('logged_in', None)
153
    flask.flash('You were logged out')
154
    return flask.redirect(flask.url_for('login'))
155
156
@app.route('/robots.txt')
157
@app.route('/crossdomain.xml')
158
def static_from_root():
159
    return flask.send_from_directory(app.static_folder, request.path[1:])
160
161
162
app.config.from_object(conf)
163
164
import logging,os
165
from logging import FileHandler
166
167
fil = FileHandler(os.path.join(os.path.dirname(__file__),'logme'),mode='a')
168
fil.setLevel(logging.ERROR)
169
app.logger.addHandler(fil)
170
171
172
173
if __name__ == "__main__":
174
    app.run(debug=True, host=conf.HOST, port=conf.PORT)