bgneal@859
|
1 """
|
bgneal@859
|
2 ssl_images is a custom manage.py command to convert forum post and comment
|
bgneal@859
|
3 images to https. It does this by rewriting the markup:
|
bgneal@859
|
4 - Images with src = http://surfguitar101.com/something are rewritten to be
|
bgneal@859
|
5 /something.
|
bgneal@859
|
6 - Non SG101 images that use http: are downloaded, resized, and uploaded to
|
bgneal@859
|
7 an S3 bucket. The src attribute is replaced with the new S3 URL.
|
bgneal@859
|
8 """
|
bgneal@882
|
9 import base64
|
bgneal@895
|
10 import datetime
|
bgneal@899
|
11 import json
|
bgneal@859
|
12 import logging
|
bgneal@859
|
13 from optparse import make_option
|
bgneal@888
|
14 import os
|
bgneal@863
|
15 import re
|
bgneal@863
|
16 import signal
|
bgneal@868
|
17 import urlparse
|
bgneal@881
|
18 import uuid
|
bgneal@859
|
19
|
bgneal@859
|
20 from django.core.management.base import NoArgsCommand, CommandError
|
bgneal@859
|
21 from django.conf import settings
|
bgneal@894
|
22 from lxml import etree
|
bgneal@863
|
23 import markdown.inlinepatterns
|
bgneal@881
|
24 from PIL import Image
|
bgneal@979
|
25 import requests
|
bgneal@859
|
26
|
bgneal@860
|
27 from comments.models import Comment
|
bgneal@860
|
28 from forums.models import Post
|
bgneal@979
|
29 from core.download import download_file
|
bgneal@979
|
30 from core.functions import remove_file
|
bgneal@881
|
31 from core.s3 import S3Bucket
|
bgneal@860
|
32
|
bgneal@860
|
33
|
bgneal@859
|
34 LOGFILE = os.path.join(settings.PROJECT_PATH, 'logs', 'ssl_images.log')
|
bgneal@859
|
35 logger = logging.getLogger(__name__)
|
bgneal@859
|
36
|
bgneal@871
|
37 IMAGE_LINK_RE = re.compile(markdown.inlinepatterns.IMAGE_LINK_RE,
|
bgneal@871
|
38 re.DOTALL | re.UNICODE)
|
bgneal@871
|
39 IMAGE_REF_RE = re.compile(markdown.inlinepatterns.IMAGE_REFERENCE_RE,
|
bgneal@871
|
40 re.DOTALL | re.UNICODE)
|
bgneal@863
|
41
|
bgneal@868
|
42 SG101_HOSTS = set(['www.surfguitar101.com', 'surfguitar101.com'])
|
bgneal@963
|
43 WHITELIST_HOSTS = set(settings.USER_IMAGES_SOURCES)
|
bgneal@866
|
44 MODEL_CHOICES = ['comments', 'posts']
|
bgneal@866
|
45
|
bgneal@881
|
46 PHOTO_MAX_SIZE = (660, 720)
|
bgneal@979
|
47 PHOTO_BASE_URL = settings.HOT_LINK_PHOTOS_BASE_URL
|
bgneal@979
|
48 PHOTO_BUCKET_NAME = settings.HOT_LINK_PHOTOS_BUCKET
|
bgneal@881
|
49
|
bgneal@899
|
50 CACHE_FILENAME = 'ssl_images_cache.json'
|
bgneal@899
|
51
|
bgneal@863
|
52 quit_flag = False
|
bgneal@881
|
53 bucket = None
|
bgneal@881
|
54 url_cache = {}
|
bgneal@899
|
55 bad_hosts = set()
|
bgneal@980
|
56 request_timeout = None
|
bgneal@863
|
57
|
bgneal@863
|
58
|
bgneal@863
|
59 def signal_handler(signum, frame):
|
bgneal@863
|
60 """SIGINT signal handler"""
|
bgneal@863
|
61 global quit_flag
|
bgneal@863
|
62 quit_flag = True
|
bgneal@863
|
63
|
bgneal@859
|
64
|
bgneal@859
|
65 def _setup_logging():
|
bgneal@859
|
66 logger.setLevel(logging.DEBUG)
|
bgneal@859
|
67 logger.propagate = False
|
bgneal@859
|
68 handler = logging.FileHandler(filename=LOGFILE, encoding='utf-8')
|
bgneal@859
|
69 formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
|
bgneal@859
|
70 handler.setFormatter(formatter)
|
bgneal@859
|
71 logger.addHandler(handler)
|
bgneal@859
|
72
|
bgneal@981
|
73 requests_log = logging.getLogger("requests.packages.urllib3")
|
bgneal@981
|
74 requests_log.setLevel(logging.INFO)
|
bgneal@981
|
75 requests_log.propagate = True
|
bgneal@981
|
76 requests_log.addHandler(handler)
|
bgneal@981
|
77
|
bgneal@982
|
78 dl_log = logging.getLogger("core.download")
|
bgneal@982
|
79 dl_log.setLevel(logging.INFO)
|
bgneal@982
|
80 dl_log.propagate = True
|
bgneal@982
|
81 dl_log.addHandler(handler)
|
bgneal@982
|
82
|
bgneal@859
|
83
|
bgneal@979
|
84 def resize_image(img_path):
|
bgneal@979
|
85 """Resizes the image found at img_path if necessary.
|
bgneal@979
|
86
|
bgneal@979
|
87 Returns True if the image was resized or resizing wasn't necessary.
|
bgneal@979
|
88 Returns False if the image could not be read or processed.
|
bgneal@881
|
89 """
|
bgneal@979
|
90 try:
|
bgneal@979
|
91 image = Image.open(img_path)
|
bgneal@979
|
92 except IOError as ex:
|
bgneal@979
|
93 logger.error("Error opening %s: %s", img_path, ex)
|
bgneal@979
|
94 return False
|
bgneal@881
|
95
|
bgneal@881
|
96 if image.size > PHOTO_MAX_SIZE:
|
bgneal@881
|
97 logger.info('Resizing from %s to %s', image.size, PHOTO_MAX_SIZE)
|
bgneal@981
|
98 try:
|
bgneal@981
|
99 image.thumbnail(PHOTO_MAX_SIZE, Image.ANTIALIAS)
|
bgneal@981
|
100 image.save(img_path)
|
bgneal@981
|
101 except IOError as ex:
|
bgneal@981
|
102 logger.error("Error resizing image from %s: %s", img_path, ex)
|
bgneal@981
|
103 return False
|
bgneal@881
|
104
|
bgneal@979
|
105 return True
|
bgneal@979
|
106
|
bgneal@881
|
107
|
bgneal@882
|
108 def gen_key():
|
bgneal@882
|
109 """Return a random key."""
|
bgneal@882
|
110 return base64.b64encode(uuid.uuid4().bytes, '-_').rstrip('=')
|
bgneal@882
|
111
|
bgneal@882
|
112
|
bgneal@881
|
113 def upload_image(img_path):
|
bgneal@881
|
114 """Upload image file located at img_path to our S3 bucket.
|
bgneal@881
|
115
|
bgneal@881
|
116 Returns the URL of the image in the bucket or None if an error occurs.
|
bgneal@881
|
117 """
|
bgneal@881
|
118 logger.info("upload_image starting")
|
bgneal@881
|
119 # Make a unique name for the image in the bucket
|
bgneal@881
|
120 ext = os.path.splitext(img_path)[1]
|
bgneal@882
|
121 file_key = gen_key() + ext
|
bgneal@881
|
122 try:
|
bgneal@881
|
123 return bucket.upload_from_filename(file_key, img_path, public=True)
|
bgneal@881
|
124 except IOError as ex:
|
bgneal@881
|
125 logger.error("Error uploading file: %s", ex)
|
bgneal@881
|
126 return None
|
bgneal@881
|
127
|
bgneal@881
|
128
|
bgneal@888
|
129 def convert_to_ssl(parsed_url):
|
bgneal@888
|
130 """Top-level function for moving an image to SSL."""
|
bgneal@888
|
131
|
bgneal@888
|
132 src = parsed_url.geturl()
|
bgneal@888
|
133
|
bgneal@899
|
134 if parsed_url.hostname in bad_hosts:
|
bgneal@899
|
135 logger.info("Host known to be bad, skipping: %s", src)
|
bgneal@899
|
136 return None
|
bgneal@899
|
137
|
bgneal@899
|
138 # Check the cache
|
bgneal@897
|
139 try:
|
bgneal@897
|
140 new_url = url_cache[src]
|
bgneal@897
|
141 except KeyError:
|
bgneal@897
|
142 # cache miss, try to get the file
|
bgneal@899
|
143 new_url = save_image_to_cloud(parsed_url)
|
bgneal@897
|
144 url_cache[src] = new_url
|
bgneal@897
|
145 else:
|
bgneal@897
|
146 if new_url:
|
bgneal@897
|
147 logger.info("Found URL in cache: %s => %s", src, new_url)
|
bgneal@897
|
148 else:
|
bgneal@897
|
149 logger.info("URL known to be bad, skipping: %s", src)
|
bgneal@888
|
150
|
bgneal@889
|
151 return new_url
|
bgneal@888
|
152
|
bgneal@888
|
153
|
bgneal@899
|
154 def save_image_to_cloud(parsed_url):
|
bgneal@881
|
155 """Downloads an image at a given source URL. Uploads it to cloud storage.
|
bgneal@881
|
156
|
bgneal@881
|
157 Returns the new URL or None if unsuccessful.
|
bgneal@881
|
158 """
|
bgneal@979
|
159 url = parsed_url.geturl()
|
bgneal@979
|
160 fn = None
|
bgneal@979
|
161 try:
|
bgneal@980
|
162 fn = download_file(url, timeout=request_timeout)
|
bgneal@979
|
163 except requests.ConnectionError as ex:
|
bgneal@979
|
164 logger.error("ConnectionError, ignoring host %s", parsed_url.hostname)
|
bgneal@979
|
165 bad_hosts.add(parsed_url.hostname)
|
bgneal@979
|
166 except requests.RequestException as ex:
|
bgneal@979
|
167 logger.error("%s", ex)
|
bgneal@979
|
168 except Exception as ex:
|
bgneal@979
|
169 logger.exception("%s", ex)
|
bgneal@979
|
170
|
bgneal@881
|
171 if fn:
|
bgneal@979
|
172 with remove_file(fn):
|
bgneal@979
|
173 if resize_image(fn):
|
bgneal@979
|
174 return upload_image(fn)
|
bgneal@881
|
175 return None
|
bgneal@868
|
176
|
bgneal@868
|
177
|
bgneal@866
|
178 def replace_image_markup(match):
|
bgneal@870
|
179 src_parts = match.group(8).split()
|
bgneal@868
|
180 if src_parts:
|
bgneal@868
|
181 src = src_parts[0]
|
bgneal@868
|
182 if src[0] == "<" and src[-1] == ">":
|
bgneal@868
|
183 src = src[1:-1]
|
bgneal@868
|
184 else:
|
bgneal@868
|
185 src = ''
|
bgneal@868
|
186
|
bgneal@868
|
187 title = ''
|
bgneal@868
|
188 if len(src_parts) > 1:
|
bgneal@868
|
189 title = " ".join(src_parts[1:])
|
bgneal@870
|
190 alt = match.group(1)
|
bgneal@868
|
191
|
bgneal@871
|
192 new_src = None
|
bgneal@868
|
193 if src:
|
bgneal@868
|
194 r = urlparse.urlparse(src)
|
bgneal@871
|
195 if r.hostname in SG101_HOSTS:
|
bgneal@871
|
196 new_src = r.path # convert to relative path
|
bgneal@871
|
197 elif r.scheme == 'http':
|
bgneal@888
|
198 # Try a few things to get this on ssl:
|
bgneal@888
|
199 new_src = convert_to_ssl(r)
|
bgneal@868
|
200 elif r.scheme == 'https':
|
bgneal@963
|
201 if r.hostname in WHITELIST_HOSTS:
|
bgneal@963
|
202 new_src = src # already in whitelist
|
bgneal@963
|
203 else:
|
bgneal@963
|
204 new_src = convert_to_ssl(r)
|
bgneal@868
|
205
|
bgneal@868
|
206 if new_src:
|
bgneal@868
|
207 if title:
|
bgneal@871
|
208 s = u'![{alt}]({src} {title})'.format(alt=alt, src=new_src, title=title)
|
bgneal@868
|
209 else:
|
bgneal@868
|
210 s = u'![{alt}]({src})'.format(alt=alt, src=new_src)
|
bgneal@868
|
211 else:
|
bgneal@868
|
212 # something's messed up, convert to a link using original src
|
bgneal@868
|
213 s = u'[{alt}]({src})'.format(alt=alt, src=src)
|
bgneal@868
|
214
|
bgneal@868
|
215 return s
|
bgneal@860
|
216
|
bgneal@860
|
217
|
bgneal@887
|
218 def warn_if_image_refs(text, model_name, pk):
|
bgneal@887
|
219 """Search text for Markdown image reference markup.
|
bgneal@887
|
220
|
bgneal@887
|
221 We aren't expecting these, but we will log something if we see any.
|
bgneal@887
|
222 """
|
bgneal@887
|
223 if IMAGE_REF_RE.search(text):
|
bgneal@887
|
224 logger.warning("Image reference found in %s pk = #%d", model_name, pk)
|
bgneal@887
|
225
|
bgneal@887
|
226
|
bgneal@866
|
227 def process_post(text):
|
bgneal@863
|
228 """Process the post object:
|
bgneal@863
|
229
|
bgneal@863
|
230 A regex substitution is run on the post's text field. This fixes up image
|
bgneal@863
|
231 links, getting rid of plain old http sources; either converting to https
|
bgneal@863
|
232 or relative style links (if the link is to SG101).
|
bgneal@863
|
233
|
bgneal@863
|
234 """
|
bgneal@866
|
235 return IMAGE_LINK_RE.sub(replace_image_markup, text)
|
bgneal@863
|
236
|
bgneal@863
|
237
|
bgneal@894
|
238 def html_check(html):
|
bgneal@894
|
239 """Return True if the given HTML fragment has <img> tags with src attributes
|
bgneal@894
|
240 that use http, and False otherwise.
|
bgneal@894
|
241 """
|
bgneal@894
|
242 if not html:
|
bgneal@894
|
243 return False
|
bgneal@894
|
244
|
bgneal@894
|
245 root = etree.HTML(html)
|
bgneal@894
|
246 for img in root.iter('img'):
|
bgneal@894
|
247 src = img.get('src')
|
bgneal@894
|
248 if src and src.lower().startswith('http:'):
|
bgneal@894
|
249 return True
|
bgneal@894
|
250 return False
|
bgneal@894
|
251
|
bgneal@894
|
252
|
bgneal@859
|
253 class Command(NoArgsCommand):
|
bgneal@859
|
254 help = "Rewrite forum posts and comments to not use http for images"
|
bgneal@859
|
255 option_list = NoArgsCommand.option_list + (
|
bgneal@866
|
256 make_option('-m', '--model',
|
bgneal@866
|
257 choices=MODEL_CHOICES,
|
bgneal@866
|
258 help="which model to update; must be one of {{{}}}".format(
|
bgneal@866
|
259 ', '.join(MODEL_CHOICES))),
|
bgneal@860
|
260 make_option('-i', '--i',
|
bgneal@859
|
261 type='int',
|
bgneal@863
|
262 help="optional first slice index; the i in [i:j]"),
|
bgneal@860
|
263 make_option('-j', '--j',
|
bgneal@859
|
264 type='int',
|
bgneal@863
|
265 help="optional second slice index; the j in [i:j]"),
|
bgneal@898
|
266 make_option('-t', '--timeout',
|
bgneal@980
|
267 type='float',
|
bgneal@979
|
268 help="optional socket timeout (secs)",
|
bgneal@980
|
269 default=30.0),
|
bgneal@859
|
270 )
|
bgneal@859
|
271
|
bgneal@859
|
272 def handle_noargs(self, **options):
|
bgneal@895
|
273 time_started = datetime.datetime.now()
|
bgneal@859
|
274 _setup_logging()
|
bgneal@860
|
275 logger.info("Starting; arguments received: %s", options)
|
bgneal@859
|
276
|
bgneal@866
|
277 if options['model'] not in MODEL_CHOICES:
|
bgneal@866
|
278 raise CommandError('Please choose a --model option')
|
bgneal@859
|
279
|
bgneal@866
|
280 if options['model'] == 'comments':
|
bgneal@860
|
281 qs = Comment.objects.all()
|
bgneal@866
|
282 text_attr = 'comment'
|
bgneal@881
|
283 model_name = 'Comment'
|
bgneal@860
|
284 else:
|
bgneal@860
|
285 qs = Post.objects.all()
|
bgneal@866
|
286 text_attr = 'body'
|
bgneal@881
|
287 model_name = 'Post'
|
bgneal@860
|
288
|
bgneal@860
|
289 i, j = options['i'], options['j']
|
bgneal@860
|
290
|
bgneal@860
|
291 if i is not None and i < 0:
|
bgneal@860
|
292 raise CommandError("-i must be >= 0")
|
bgneal@860
|
293 if j is not None and j < 0:
|
bgneal@860
|
294 raise CommandError("-j must be >= 0")
|
bgneal@860
|
295 if j is not None and i is not None and j <= i:
|
bgneal@860
|
296 raise CommandError("-j must be > -i")
|
bgneal@860
|
297
|
bgneal@860
|
298 if i is not None and j is not None:
|
bgneal@860
|
299 qs = qs[i:j]
|
bgneal@860
|
300 elif i is not None and j is None:
|
bgneal@860
|
301 qs = qs[i:]
|
bgneal@860
|
302 elif i is None and j is not None:
|
bgneal@860
|
303 qs = qs[:j]
|
bgneal@860
|
304
|
bgneal@881
|
305 # Set global socket timeout
|
bgneal@980
|
306 global request_timeout
|
bgneal@980
|
307 request_timeout = options.get('timeout')
|
bgneal@980
|
308 logger.info("Using socket timeout of %4.2f", request_timeout)
|
bgneal@881
|
309
|
bgneal@863
|
310 # Install signal handler for ctrl-c
|
bgneal@863
|
311 signal.signal(signal.SIGINT, signal_handler)
|
bgneal@863
|
312
|
bgneal@881
|
313 # Create bucket to upload photos
|
bgneal@881
|
314 global bucket
|
bgneal@881
|
315 bucket = S3Bucket(access_key=settings.USER_PHOTOS_ACCESS_KEY,
|
bgneal@881
|
316 secret_key=settings.USER_PHOTOS_SECRET_KEY,
|
bgneal@881
|
317 base_url=PHOTO_BASE_URL,
|
bgneal@881
|
318 bucket_name=PHOTO_BUCKET_NAME)
|
bgneal@887
|
319
|
bgneal@899
|
320 # Load cached info from previous runs
|
bgneal@899
|
321 load_cache()
|
bgneal@899
|
322
|
bgneal@887
|
323 if i is None:
|
bgneal@887
|
324 i = 0
|
bgneal@887
|
325
|
bgneal@895
|
326 count = 0
|
bgneal@881
|
327 for n, model in enumerate(qs.iterator()):
|
bgneal@863
|
328 if quit_flag:
|
bgneal@863
|
329 logger.warning("SIGINT received, exiting")
|
bgneal@881
|
330 break
|
bgneal@881
|
331 logger.info("Processing %s #%d (pk = %d)", model_name, n + i, model.pk)
|
bgneal@866
|
332 txt = getattr(model, text_attr)
|
bgneal@887
|
333 warn_if_image_refs(txt, model_name, model.pk)
|
bgneal@866
|
334 new_txt = process_post(txt)
|
bgneal@881
|
335 if txt != new_txt:
|
bgneal@889
|
336 logger.info("Content changed on %s #%d (pk = %d)",
|
bgneal@887
|
337 model_name, n + i, model.pk)
|
bgneal@881
|
338 logger.debug("original: %s", txt)
|
bgneal@881
|
339 logger.debug("changed: %s", new_txt)
|
bgneal@887
|
340 setattr(model, text_attr, new_txt)
|
bgneal@887
|
341 model.save()
|
bgneal@894
|
342 elif html_check(model.html):
|
bgneal@894
|
343 # Check for content generated with older smiley code that used
|
bgneal@894
|
344 # absolute URLs for the smiley images. If True, then just save
|
bgneal@894
|
345 # the model again to force updated HTML to be created.
|
bgneal@894
|
346 logger.info("Older Smiley HTML detected, forcing a save")
|
bgneal@894
|
347 model.save()
|
bgneal@895
|
348 count += 1
|
bgneal@860
|
349
|
bgneal@895
|
350 time_finished = datetime.datetime.now()
|
bgneal@895
|
351 elapsed = time_finished - time_started
|
bgneal@895
|
352 logger.info("ssl_images exiting; number of objects: %d; elapsed: %s",
|
bgneal@895
|
353 count, elapsed)
|
bgneal@897
|
354
|
bgneal@897
|
355 http_images = len(url_cache)
|
bgneal@897
|
356 https_images = sum(1 for v in url_cache.itervalues() if v)
|
bgneal@897
|
357 bad_images = http_images - https_images
|
bgneal@897
|
358 if http_images > 0:
|
bgneal@897
|
359 pct_saved = float(https_images) / http_images * 100.0
|
bgneal@897
|
360 else:
|
bgneal@897
|
361 pct_saved = 0.0
|
bgneal@897
|
362
|
bgneal@897
|
363 logger.info("Summary: http: %d; https: %d; lost: %d; saved: %3.1f %%",
|
bgneal@897
|
364 http_images, https_images, bad_images, pct_saved)
|
bgneal@899
|
365
|
bgneal@899
|
366 save_cache()
|
bgneal@899
|
367 logger.info("ssl_images done")
|
bgneal@899
|
368
|
bgneal@899
|
369
|
bgneal@899
|
370 def load_cache():
|
bgneal@899
|
371 """Load cache from previous runs."""
|
bgneal@899
|
372 logger.info("Loading cached information")
|
bgneal@899
|
373 try:
|
bgneal@899
|
374 with open(CACHE_FILENAME, 'r') as fp:
|
bgneal@899
|
375 d = json.load(fp)
|
bgneal@899
|
376 except IOError as ex:
|
bgneal@899
|
377 logger.error("Cache file (%s) IOError: %s", CACHE_FILENAME, ex)
|
bgneal@899
|
378 return
|
bgneal@899
|
379 except ValueError:
|
bgneal@899
|
380 logger.error("Mangled cache file: %s", CACHE_FILENAME)
|
bgneal@899
|
381 return
|
bgneal@899
|
382
|
bgneal@899
|
383 global bad_hosts, url_cache
|
bgneal@899
|
384 try:
|
bgneal@899
|
385 bad_hosts = set(d['bad_hosts'])
|
bgneal@899
|
386 url_cache = d['url_cache']
|
bgneal@899
|
387 except KeyError:
|
bgneal@899
|
388 logger.error("Malformed cache file: %s", CACHE_FILENAME)
|
bgneal@899
|
389
|
bgneal@899
|
390
|
bgneal@899
|
391 def save_cache():
|
bgneal@899
|
392 """Save our cache to a file for future runs."""
|
bgneal@899
|
393 logger.info("Saving cached information")
|
bgneal@899
|
394 d = {'bad_hosts': list(bad_hosts), 'url_cache': url_cache}
|
bgneal@899
|
395 with open(CACHE_FILENAME, 'w') as fp:
|
bgneal@899
|
396 json.dump(d, fp, indent=4)
|