1
from flask import Flask
2
from flask import request
3
from flask import render_template
4
import lxml.html
5
import pymongo
6
from bson import Code
7
import urllib2
8
import StringIO
9
from flask import g
10
from flask import redirect
11
from urllib import quote_plus
12
from urllib import unquote_plus
13
import conf
14
import oursql
15
from flask import jsonify
16
app = Flask(__name__)
17
@app.before_request
18
def first():
19
    g.connection = pymongo.Connection('localhost',27017) #Create the object once and use it.
20
    g.db = g.connection['dev_alipi']
21
@app.teardown_request
22
def close(exception):
23
    g.connection.disconnect()
24
@app.route('/')
25
def start_page() :
26
    d = {}
27
    d['foruri'] = request.args['foruri']
28
    myhandler1 = urllib2.Request(d['foruri'],headers={'User-Agent':"Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"}) #A fix to send user-agents, so that sites render properly.
29
    try:
30
        a = urllib2.urlopen(myhandler1)
31
        if a.geturl() != d['foruri']:
32
            return "There was a server redirect, please click on the <a href='http://dev.a11y.in/web?foruri={0}'>link</a> to continue.".format(quote_plus(a.geturl()))
33
        else:
34
            page = a.read()
35
            a.close()
36
    except ValueError:
37
        return "The link is malformed, click <a href='http://dev.a11y.in/web?foruri={0}&lang={1}&interactive=1'>here</a> to be redirected.".format(quote_plus(unquote_plus(d['foruri'])),request.args['lang'])
38
    except urllib2.URLError:
39
        return render_template('error.html')
40
    try:
41
        page = unicode(page,'utf-8')  #Hack to fix improperly displayed chars on wikipedia.
42
    except UnicodeDecodeError:
43
        pass #Some pages may not need be utf-8'ed
44
    g.root = lxml.html.parse(StringIO.StringIO(page)).getroot()
45
    if request.args.has_key('lang') == False and request.args.has_key('blog') == False:
46
        g.root.make_links_absolute(d['foruri'], resolve_base_href = True)
47
        for i in g.root.iterlinks():
48
            if i[1] == 'href' and i[0].tag != 'link':
49
                i[0].attrib['href'] = 'http://{0}?foruri={1}'.format(conf.DEPLOYURL[0],quote_plus(i[0].attrib['href']))
50
        setScripts() 
51
        g.root.body.set("onload","a11ypi.loadOverlay();")
52
        return lxml.html.tostring(g.root)
53
54
    elif request.args.has_key('lang') == True and request.args.has_key('interactive') == True and request.args.has_key('blog') == False:
55
        setScripts()
56
        setSocialScript()
57
        g.root.body.set("onload","a11ypi.ren();a11ypi.tweet(); a11ypi.facebook(); a11ypi.loadOverlay();")
58
        return lxml.html.tostring(g.root)
59
        
60
    elif request.args.has_key('lang') == True and request.args.has_key('blog') == False:
61
        script_jq_mini = root.makeelement('script')
62
        root.body.append(script_jq_mini)
63
        script_jq_mini.set("src", conf.JQUERYURL[0] + "/jquery-1.7.min.js")
64
        script_jq_mini.set("type", "text/javascript")
65
        d['lang'] = request.args['lang']
66
        script_test = root.makeelement('script')
67
        root.body.append(script_test)
68
        script_test.set("src", conf.APPURL[0] + "/server/ui.js")
69
        script_test.set("type", "text/javascript")
70
        root.body.set("onload","a11ypi.ren()");
71
        root.make_links_absolute(d['foruri'], resolve_base_href = True)
72
        return lxml.html.tostring(root)
73
74
    elif request.args.has_key('interactive') == True and request.args.has_key('blog') == True and request.args.has_key('lang') == True:
75
        setScripts()
76
        setSocialScript()
77
        g.root.body.set("onload","a11ypi.filter(); a11ypi.tweet(); a11ypi.facebook(); a11ypi.loadOverlay();");
78
        g.root.make_links_absolute(d['foruri'], resolve_base_href = True)
79
        return lxml.html.tostring(g.root)
80
81
    elif request.args.has_key('interactive') == False and request.args.has_key('blog') == True:    
82
        setScripts()
83
        g.root.make_links_absolute(d['foruri'], resolve_base_href = True)
84
        g.root.body.set('onload', 'a11ypi.loadOverlay();')
85
        return lxml.html.tostring(g.root)
86
87
def setScripts():
88
    script_test = g.root.makeelement('script')
89
    script_edit = g.root.makeelement('script')
90
    g.root.body.append(script_test)
91
    g.root.body.append(script_edit)
92
    script_test.set("src", conf.APPURL[0] + "/server/ui.js")
93
    script_test.set("type", "text/javascript")
94
    script_edit.set("src", conf.APPURL[0] + "/server/wsgi/pageEditor.js")
95
    script_edit.set("type","text/javascript")
96
    
97
    script_jq_mini = g.root.makeelement('script')
98
    g.root.body.append(script_jq_mini)
99
    script_jq_mini.set("src", conf.JQUERYURL[0] + "/jquery-1.7.min.js")
100
    script_jq_mini.set("type", "text/javascript")
101
    
102
    style = g.root.makeelement('link')
103
    g.root.body.append(style)
104
    style.set("rel","stylesheet")
105
    style.set("type", "text/css")
106
    style.set("href", conf.APPURL[0] + "/server/stylesheet.css")
107
108
    script_jq_cust = g.root.makeelement('script')
109
    g.root.body.append(script_jq_cust)
110
    script_jq_cust.set("src", conf.JQUERYUI[0] + "/jquery-ui.min.js")
111
    script_jq_cust.set("type", "text/javascript")
112
113
    style_cust = g.root.makeelement('link')
114
    style_cust.set("rel","stylesheet")
115
    style_cust.set("type", "text/css")
116
    style_cust.set("href", conf.JQUERYCSS[0] + "/jquery-ui.css")
117
    g.root.body.append(style_cust)
118
    
119
def setSocialScript():
120
    info_button = g.root.makeelement('button')
121
    g.root.body.append(info_button)
122
    info_button.set("id", "info")
123
    info_button.set("class", "alipi")
124
    info_button.set("onClick", "a11ypi.showInfo(a11ypi.responseJSON);")
125
    info_button.text =  "Info"
126
    info_button.set("title", "Have a look at the information of each renarrated element")
127
    
128
    share_button = g.root.makeelement('button')
129
    g.root.body.append(share_button)
130
    share_button.set("id", "share")
131
    share_button.set("class", "alipi")
132
    share_button.set("onClick", "a11ypi.share();")
133
    share_button.text =  "Share"
134
    share_button.set("title", "Share your contribution in your social network")
135
    
136
    see_orig = g.root.makeelement('button')
137
    g.root.body.append(see_orig)
138
    see_orig.set("id", "orig-button")
139
    see_orig.set("class", "alipi")
140
    see_orig.set("onClick", "a11ypi.showOriginal();")
141
    see_orig.text = "Original Page"
142
    see_orig.set("title", "Go to Original link, the original page of this renarrated")
143
    
144
    tweetroot = g.root.makeelement("div")
145
    tweetroot.set("id", "tweet-root")
146
    tweetroot.set("class", "alipi")
147
    tweetroot.set("style", "display:none;padding:10px;")
148
    g.root.body.append(tweetroot)
149
150
    tweet = g.root.makeelement("a")
151
    tweet.set("id", "tweet")
152
    tweet.set("href", "https://twitter.com/share")
153
    tweet.set("class", "alipi twitter-share-button")
154
    tweet.set("data-via", "a11ypi")
155
    tweet.set("data-lang", "en")
156
    tweet.set("data-url", "http://dev.a11y.in/web?foruri={0}&lang={1}&interactive=1".format(quote_plus(request.args['foruri']),request.args['lang']))
157
    tweet.textContent = "Tweet"
158
    tweetroot.append(tweet)
159
160
    fblike = g.root.makeelement("div")
161
    fblike.set("id", "fb-like")
162
    fblike.set("class", "alipi fb-like")
163
    fblike.set("style", "display:none;padding:10px;")
164
    fblike.set("data-href", "http://dev.a11y.in/web?foruri={0}&lang={1}&interactive=1".format(quote_plus(request.args['foruri']),request.args['lang']))
165
    fblike.set("data-send", "true")
166
    fblike.set("data-layout", "button_count")
167
    fblike.set("data-width", "50")
168
    fblike.set("data-show-faces", "true")
169
    fblike.set("data-font", "arial")
170
    g.root.body.append(fblike)
171
    
172
    style = g.root.makeelement('link')
173
    g.root.body.append(style)
174
    style.set("rel","stylesheet")
175
    style.set("type", "text/css")
176
    style.set("href", "http://dev.a11y.in/server/stylesheet.css")
177
178
    
179
@app.route('/directory')
180
def show_directory():
181
    collection = g.db['post']
182
    query = collection.group(
183
        key = Code('function(doc){return {"about" : doc.about,"lang":doc.lang}}'),
184
        condition={"about":{'$regex':'^[/\S/]'}},
185
        initial={'na': []},
186
        reduce=Code('function(doc,out){out.na.push(doc.blog)}')
187
        )
188
    query.reverse()
189
    return render_template('directory.html', name=query, mymodule = quote_plus, myset=set, mylist= list)
190
191
@app.route('/getLoc', methods=['GET'])
192
def get_loc():
193
194
    term = request.args['term']
195
    connection = oursql.Connection(conf.DBHOST[0],conf.DBUSRNAME[0],conf.DBPASSWD[0],db=conf.DBNAME[0])
196
    cursor = connection.cursor(oursql.DictCursor)
197
    cursor.execute('select l.name, c.country_name from `location` as l, `codes` as c where l.name like ? and l.code=c.code limit ?', (term+'%', 5))
198
    r = cursor.fetchall()
199
    connection.close()
200
    d = {}
201
    d['return'] = r
202
    response = jsonify(d)
203
    response.headers['Access-Control-Allow-Origin'] = '*'
204
    return response
205
@app.route('/getLang', methods=['GET'])
206
def get_lang():
207
    term = request.args['term']
208
    connection = oursql.Connection(conf.DBHOST[0],conf.DBUSRNAME[0],conf.DBPASSWD[0],db=conf.DBNAME[0])
209
    cursor = connection.cursor(oursql.DictCursor)
210
    cursor.execute('select * from `languages` as l  where l.name like ? limit ?', (term+'%',5))
211
    r = cursor.fetchall()
212
    connection.close()
213
    d = {}
214
    d['return'] = r
215
    response = jsonify(d)
216
    response.headers['Access-Control-Allow-Origin'] = '*'
217
    return response
218
@app.route('/blank', methods=['GET'])
219
def serve_blank():
220
    return render_template('blank.html')
221
222
@app.route('/info', methods=['GET'])
223
def serve_info():
224
    coll = g.db['post']
225
    d = {}
226
    cntr = 0
227
    for i in coll.find({"about":unquote_plus(request.args['about']),"lang":request.args['lang']}):
228
        i['_id'] = str(i['_id'])
229
        d[cntr] = i
230
        cntr+=1
231
    response = jsonify(d)
232
    response.headers['Access-Control-Allow-Origin'] = '*'
233
    return response
234
import logging,os
235
from logging import FileHandler
236
237
fil = FileHandler(os.path.join(os.path.dirname(__file__),'logme'),mode='a')
238
fil.setLevel(logging.ERROR)
239
app.logger.addHandler(fil)
240
241
if __name__ == '__main__':
242
    app.run(debug=True, host='0.0.0.0')