-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstntweets.py
executable file
·185 lines (134 loc) · 6.53 KB
/
stntweets.py
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
#!/usr/bin/env python3
# Grabs the current results of the Secure The News scorecard API,
# compares them to the previous results, and tweets about the
# differences.
import random, json, yaml, os, time, requests
from twython import Twython, TwythonError
from typing import Optional
fullpath = os.path.dirname(os.path.realpath(__file__))
CONFIG = os.path.join(fullpath, "config.yaml")
def get_config():
with open(CONFIG,'r') as c:
config = yaml.load(c)
return config
def get_twitter_instance(config):
twitter_app_key = config['twitter_app_key']
twitter_app_secret = config['twitter_app_secret']
twitter_oauth_token = config['twitter_oauth_token']
twitter_oauth_token_secret = config['twitter_oauth_token_secret']
return Twython(twitter_app_key, twitter_app_secret, twitter_oauth_token, twitter_oauth_token_secret)
def write_results(results,path):
with open(path,"w") as f:
json.dump(results, f, indent = 4)
def available_over_https(site):
if (site['valid_https']
and not site['downgrades_https']):
return True
else:
return False
def get_site_name(site_name: str, twitter_handle: Optional[str]) -> str:
"""Returns a string for the site name with the twitter handle in parens
if available"""
if twitter_handle:
return "{} ({})".format(site_name, twitter_handle)
else:
return site_name
def compare_results(old_site, new_site):
site_tweets = []
site_name = get_site_name(new_site['name'], new_site['twitter_handle'])
if old_site == None:
site_tweets.append("🤖 We're tracking a new site on @SecureTheNews: " + site_name + " has a grade of " + new_site['grade'] + ". " + new_site['url'])
return site_tweets
if (new_site['grade'] != old_site['grade'] and
new_site['score'] > old_site['score']):
site_tweets.append("🤖 " + site_name + " has improved its grade on the @SecureTheNews leaderboard from " + old_site['grade'] + " to " + new_site['grade'] + ". " + new_site['url'])
if (new_site['defaults_to_https']
and not old_site['defaults_to_https']):
site_tweets.append("🤖 Great news: " + site_name + " is now using HTTPS by default! Huge win for reader privacy and security. https://securethe.news/sites")
elif (available_over_https(new_site)
and not available_over_https(old_site)):
site_tweets.append("🤖 " + site_name + " is now available over HTTPS! Next step: turn it on by default. https://securethe.news/sites")
if (new_site['hsts'] and not old_site['hsts']):
site_tweets.append("🤖 " + site_name + " is now using HSTS headers. This means browsers will connect to it more securely. Yes! https://securethe.news/sites")
if (new_site['hsts_preloaded']
and not old_site['hsts_preloaded']):
site_tweets.append("🤖 " + site_name + " is now on the HSTS preload list for major browsers, protecting user privacy. Bravo. https://securethe.news/sites")
if (new_site.get('onion_available', False) and not old_site.get('onion_available', False)):
site_tweets.append("🤖 " + site_name + " provides a @torproject onion service to protect reader privacy and enable censorship circumvention! https://securethe.news/sites")
return site_tweets
def tweet_results(tweets, twitter):
to_sleep = False
for site in tweets:
if to_sleep:
time.sleep(1800)
else:
to_sleep = True
reply_to = 'null'
for item in site:
if reply_to != 'null':
time.sleep(30)
try:
response = twitter.update_status(status=item,
in_reply_to_status_id=reply_to)
reply_to = response['id_str']
except TwythonError as err:
# see note below, this API has been sunsetted
# twitter.send_direct_message(screen_name=botmaster,
# text="I tried to tweet " + item +
# " but got the error " + str(err))
pass
def main():
config = get_config()
twitter = get_twitter_instance(config)
botmaster = config['botmaster']
results = requests.get("https://securethe.news/api/v1/sites/?limit=1000").json()['results']
tweets = list()
new_results = list()
for site in results:
new_results.append({'name':site['name'],
'twitter_handle':site.get('twitter_handle', None),
'grade':site['latest_scan']['grade'],
'score':site['latest_scan']['score'],
'valid_https':site['latest_scan']['valid_https'],
'downgrades_https':
site['latest_scan']['downgrades_https'],
'defaults_to_https':
site['latest_scan']['defaults_to_https'],
'hsts':site['latest_scan']['hsts'],
'hsts_preloaded':site['latest_scan']['hsts_preloaded'],
'onion_available':site['latest_scan'].get('onion_location_header', False),
'url':'https://securethe.news/sites/' + site['slug']})
# Open existing results to compare to the new ones, if they exist.
# If not, save the new ones and we'll compare later.
results_path = os.path.join(fullpath, "old_results.json")
if os.path.exists(results_path):
best_results = []
with open(results_path,"r") as f:
old_results = json.load(f)
# This is the main comparison loop. It takes one site at a time and
# compares the properties of `new_site` to `old_site`.
# If it finds differences, it saves those to a list of tweets.
for new_site in new_results:
old_site = next((s for s in old_results if s['name'] == new_site['name']), None)
site_tweets = compare_results(old_site, new_site)
# After all the comparisons, add the collected differences as a list
# to the `tweets` list.
if len(site_tweets) > 0:
tweets.append(site_tweets)
best_results.append(new_site)
else:
best_results.append(old_site)
# The tweeting loop.
# This part was cool, but won't work after 8/16/18 due to Twitter sunsetting
# this API. Pour one out.
# if len(tweets) == 0:
# twitter.send_direct_message(screen_name=botmaster,
# text="I would've sent a message, but nothing changed!")
tweet_results(tweets, twitter)
write_results(best_results, results_path)
else:
old_results = new_results
write_results(old_results, results_path)
print("Created a new baseline. Comparison will be made later.")
if __name__ == "__main__":
main()