summaryrefslogtreecommitdiffstats
path: root/lanre_py/lanre.py
blob: 4db21cd320d94399965a554b9126fb5c22852e0f (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
# 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

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

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


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()

@app.before_request
def before_request():
	g.db = connect_db()

@app.teardown_request
def teardown_request(exception):
	g.db.close()

@app.route('/')
def ask_for_text():
	
	return render_template('ask_for_text.html')
	
@app.route('/options', methods=['POST'])
def add_entry():
	if not session.get('logged_in'):
		abort(401)
	g.db.execute('insert into entries (title, text) values (?, ?)',
				 [request.form['title'], request.form['text']])
	g.db.commit()
	flash('New entry was successfully posted')
	return redirect(url_for('ask_for_text.html'))
	

@app.route('/login', methods=['GET', 'POST'])
def login():
	error = None
	if request.method == 'POST':
		if request.form['username'] != app.config['USERNAME']:
			error = 'Invalid username'
		elif request.form['password'] != app.config['PASSWORD']:
			error = 'Invalid password'
		else:
			session['logged_in'] = True
			flash('You were logged in')
			return redirect(url_for('ask_for_text'))
	return render_template('login.html', error=error)
	

@app.route('/logout')
def logout():
	session.pop('logged_in', None)
	flash('You were logged out')
	return redirect(url_for('ask_for_text'))
	

def get_exact_translation(retrieved_json):
	try:
		response = retrieved_json["term0"]["PrincipalTranslations"]["0"]["FirstTranslation"]["term"]
		if len(response) == 0:
			response = "No translation"
	except:
		response = "No translation"
	return response

@app.route('/_find_translations')
def find_translations():
	text_for_translation = request.args.get('text', 0)
	language = request.args.get('language', 0)
	dictionary_link = "http://api.wordreference.com/a95ae/json/" + language + "/"
	words = text_for_translation.split(" ")
	translations = []
	for word in words:
		translation = get_exact_translation(requests.get(dictionary_link + strip_punctuation(word)).json)
		translations.append(translation)

	return jsonify(result=translations, words=words, html_output=prepare_html_output(words))


@app.route('/_send_mail')
def send_mail():
	from_address = "attero@hackerspace.pl"
	to_address = request.args.get('mail_address', 0)
	message_text = request.args.get('message', 0)
	msg = ("From: %s\r\nTo: %s\r\nSubject: Lanre\r\n" % (from_address, to_address))
	server = smtplib.SMTP('hackerspace.pl', 587)
	server.starttls()
	server.login("attero", "dupa.8")
	server.set_debuglevel(1)
	print(from_address)
	print(to_address)
	print(msg + message_text)
	print("somethin wrong in loging to server")
	server.sendmail(from_address, to_address, msg + message_text)
	server.quit()
	return jsonify(result="success")


	


def prepare_html_output(words):
	words_with_html = ["<span class='word' id='" + str(i) +"'>" + word + "</span>" for i, word in enumerate(words)]
	output = " ".join(words_with_html)
	return output


def strip_punctuation(word):
	try:
		if(word[len(word)-1].isalpha()):
			return word
		else:
			return word[0:(len(word)-1)]
	except:
		return word
	

#a95ae api key for word reference is: a95ae
#http://www.wordreference.com/docs/api.aspx


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