-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiff.py
More file actions
140 lines (121 loc) · 4.02 KB
/
diff.py
File metadata and controls
140 lines (121 loc) · 4.02 KB
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
from __future__ import with_statement
import difflib
import logging
import os
import shutil
import sqlite3
from contextlib import closing
from urllib import urlopen
from flask import Flask, request, session, g, url_for, abort, render_template
from twilio.rest import TwilioRestClient
from apscheduler.scheduler import Scheduler
sched = Scheduler()
sched.start()
logging.basicConfig()
# temporary
DATABASE = '/tmp/diff.db'
DEBUG = True
SECRET_KEY = 'development key'
USERNAME = 'admin'
PASSWORD = 'default'
def init_twilio(filename):
curpath = os.path.abspath(os.curdir)
with open(os.path.join(curpath, filename)) as f:
lines = f.readlines() # temporary method
num = lines[0].strip()
sid = lines[1].strip()
token = lines[2].strip()
return [num, TwilioRestClient(sid, token)]
twilio = init_twilio('twilio-info')
twilio_num = twilio[0]
twilio_client = twilio[1]
diff = Flask(__name__)
diff.config.from_object(__name__)
# from flask docs
def connect_db():
return sqlite3.connect(diff.config['DATABASE'])
# from flask docs
def init_db():
with closing(connect_db()) as db:
with diff.open_resource('schema.sql') as f:
db.cursor().executescript(f.read())
db.commit()
# from flask docs
def query_db(query, args=(), one=False):
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
# from flask docs
@diff.before_request
def before_request():
g.db = connect_db()
# from flask docs
@diff.teardown_request
def teardown_request(exception):
g.db.close()
@diff.route('/')
def index_page():
return render_template('index.html')
@diff.route('/confirm', methods=['POST'])
def confirm_page():
args = request.form
phone = args['phone']
url = args['url']
enter_data(phone, url)
return render_template('confirm.html', phone=phone, url=url)
def enter_data(phone, url):
src = urlopen(url)
fname = generate_fname(phone, url)
with open(fname, 'w') as f:
shutil.copyfileobj(src, f)
uid = get_id(phone)
if uid is None:
g.db.execute("insert into users (phone) values (?)", [phone])
g.db.commit()
uid = get_id(phone)
g.db.execute("insert into requests (uid, url) values (?, ?)", [uid, url])
g.db.commit()
msg = "You will receive updates for %s! Love, Diff Checker." % url
sched.add_interval_job(update, seconds=10, args=[uid])
return send_text(phone, msg)
def update(uid):
with diff.test_request_context():
diff.preprocess_request()
user = g.db.execute("select phone from users where id = ?", [uid])
phone = '+' + str([row[0] for row in user.fetchall()][0])
reqs = g.db.execute("select url from requests where uid = ?", [uid])
urls = [row[0] for row in reqs.fetchall()]
for url in urls:
check_and_send(phone, url)
def check_and_send(phone, url):
contents = urlopen(url).read()
fname = generate_fname(phone, url)
with open(fname, 'r') as f:
match = difflib.SequenceMatcher(None, f.read(), contents)
matchratio = match.ratio()
if matchratio != 1:
print "Difference detected -- sending text to %s" % phone
msg = "%s has changed! Love, Diff Checker." % url
send_text(phone, msg)
with open(fname, 'w+') as f2:
f2.write(contents)
def send_text(phone, content):
msg = twilio_client.sms.messages.create(to=phone, from_=twilio_num,
body=content)
return msg
def generate_fname(phone, url):
curpath = os.path.abspath(os.curdir)
last = url.split('/')[-1]
fname = "contents/%s-%s" % (phone, last)
return fname
# adapted from flask docs
def get_id(phone):
user = query_db("select * from users where phone = ?", [phone],
one=True)
if user is None:
return None
else:
return user['id']
if __name__ == '__main__':
diff.run()