annotate core/management/commands/ssl_images.py @ 895:e7c549e4dbf7

Add counter and timer.
author Brian Neal <bgneal@gmail.com>
date Thu, 19 Feb 2015 21:02:21 -0600
parents 101728976f9c
children 0054a4a88c1c
rev   line source
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@888 11 import httplib
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@881 17 import socket
bgneal@881 18 import urllib
bgneal@868 19 import urlparse
bgneal@881 20 import uuid
bgneal@859 21
bgneal@859 22 from django.core.management.base import NoArgsCommand, CommandError
bgneal@859 23 from django.conf import settings
bgneal@894 24 from lxml import etree
bgneal@863 25 import markdown.inlinepatterns
bgneal@881 26 from PIL import Image
bgneal@859 27
bgneal@860 28 from comments.models import Comment
bgneal@860 29 from forums.models import Post
bgneal@881 30 from core.s3 import S3Bucket
bgneal@860 31
bgneal@860 32
bgneal@859 33 LOGFILE = os.path.join(settings.PROJECT_PATH, 'logs', 'ssl_images.log')
bgneal@859 34 logger = logging.getLogger(__name__)
bgneal@859 35
bgneal@871 36 IMAGE_LINK_RE = re.compile(markdown.inlinepatterns.IMAGE_LINK_RE,
bgneal@871 37 re.DOTALL | re.UNICODE)
bgneal@871 38 IMAGE_REF_RE = re.compile(markdown.inlinepatterns.IMAGE_REFERENCE_RE,
bgneal@871 39 re.DOTALL | re.UNICODE)
bgneal@863 40
bgneal@868 41 SG101_HOSTS = set(['www.surfguitar101.com', 'surfguitar101.com'])
bgneal@866 42 MODEL_CHOICES = ['comments', 'posts']
bgneal@866 43
bgneal@881 44 PHOTO_MAX_SIZE = (660, 720)
bgneal@881 45 PHOTO_BASE_URL = 'https://s3.amazonaws.com/'
bgneal@881 46 PHOTO_BUCKET_NAME = 'sg101.forum.photos'
bgneal@881 47
bgneal@863 48 quit_flag = False
bgneal@881 49 opener = None
bgneal@881 50 bucket = None
bgneal@881 51 url_cache = {}
bgneal@863 52
bgneal@863 53
bgneal@863 54 def signal_handler(signum, frame):
bgneal@863 55 """SIGINT signal handler"""
bgneal@863 56 global quit_flag
bgneal@863 57 quit_flag = True
bgneal@863 58
bgneal@859 59
bgneal@859 60 def _setup_logging():
bgneal@859 61 logger.setLevel(logging.DEBUG)
bgneal@859 62 logger.propagate = False
bgneal@859 63 handler = logging.FileHandler(filename=LOGFILE, encoding='utf-8')
bgneal@859 64 formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
bgneal@859 65 handler.setFormatter(formatter)
bgneal@859 66 logger.addHandler(handler)
bgneal@859 67
bgneal@859 68
bgneal@881 69 class ImageURLopener(urllib.FancyURLopener):
bgneal@881 70 """Our URL opener. Handles redirects as per FancyURLopener. But all other
bgneal@881 71 errors and authentication requests will raise an IOError.
bgneal@881 72 """
bgneal@881 73 HANDLED_ERRORS = set([302, 301, 303, 307])
bgneal@881 74
bgneal@881 75 def http_error_default(self, url, fp, errcode, errmsg, headers):
bgneal@881 76 return urllib.URLopener.http_error_default(self, url, fp, errcode,
bgneal@881 77 errmsg, headers)
bgneal@881 78
bgneal@881 79 def http_error(self, url, fp, errcode, errmsg, headers, data=None):
bgneal@881 80 """Handle http errors.
bgneal@881 81 We let FancyURLopener handle the redirects, but any other error we want
bgneal@881 82 to let fail.
bgneal@881 83 """
bgneal@881 84 if errcode in self.HANDLED_ERRORS:
bgneal@881 85 name = 'http_error_%d' % errcode
bgneal@881 86 method = getattr(self, name)
bgneal@881 87 if data is None:
bgneal@881 88 result = method(url, fp, errcode, errmsg, headers)
bgneal@881 89 else:
bgneal@881 90 result = method(url, fp, errcode, errmsg, headers, data)
bgneal@881 91 if result:
bgneal@881 92 return result
bgneal@881 93 return self.http_error_default(url, fp, errcode, errmsg, headers)
bgneal@881 94
bgneal@881 95
bgneal@881 96 def download_image(src):
bgneal@881 97 """Downloads the image file from the given source URL.
bgneal@881 98
bgneal@881 99 If successful returns the path to the downloaded file. Otherwise None is
bgneal@881 100 returned.
bgneal@881 101 """
bgneal@881 102 logger.info("Retrieving %s", src)
bgneal@881 103 try:
bgneal@881 104 fn, hdrs = opener.retrieve(src)
bgneal@881 105 except IOError as ex:
bgneal@881 106 args = ex.args
bgneal@881 107 if len(args) == 4 and args[0] == 'http error':
bgneal@881 108 logger.error("http error: %d - %s", args[1], args[2])
bgneal@881 109 else:
bgneal@881 110 logger.error("%s", ex)
bgneal@881 111 return None
bgneal@881 112
bgneal@881 113 # Does it look like an image?
bgneal@881 114 content_type = hdrs.get('content-type')
bgneal@881 115 if not content_type:
bgneal@881 116 logger.error("No content-type header found")
bgneal@881 117 return None
bgneal@881 118
bgneal@888 119 file_size = os.stat(fn).st_size
bgneal@888 120 logger.info("Retrieved: %s bytes; content-type: %s", file_size, content_type)
bgneal@881 121
bgneal@881 122 parts = content_type.split('/')
bgneal@881 123 if len(parts) < 2 or parts[0] != 'image':
bgneal@881 124 logger.error("Unknown content-type: %s", content_type)
bgneal@881 125 return None
bgneal@881 126
bgneal@881 127 return fn
bgneal@881 128
bgneal@881 129
bgneal@881 130 def resize_image(img_path):
bgneal@881 131 """Resizes the image found at img_path if necessary."""
bgneal@881 132 image = Image.open(img_path)
bgneal@881 133 if image.size > PHOTO_MAX_SIZE:
bgneal@881 134 logger.info('Resizing from %s to %s', image.size, PHOTO_MAX_SIZE)
bgneal@881 135 image.thumbnail(PHOTO_MAX_SIZE, Image.ANTIALIAS)
bgneal@881 136 image.save(img_path)
bgneal@881 137
bgneal@881 138
bgneal@882 139 def gen_key():
bgneal@882 140 """Return a random key."""
bgneal@882 141 return base64.b64encode(uuid.uuid4().bytes, '-_').rstrip('=')
bgneal@882 142
bgneal@882 143
bgneal@881 144 def upload_image(img_path):
bgneal@881 145 """Upload image file located at img_path to our S3 bucket.
bgneal@881 146
bgneal@881 147 Returns the URL of the image in the bucket or None if an error occurs.
bgneal@881 148 """
bgneal@881 149 logger.info("upload_image starting")
bgneal@881 150 # Make a unique name for the image in the bucket
bgneal@881 151 ext = os.path.splitext(img_path)[1]
bgneal@882 152 file_key = gen_key() + ext
bgneal@881 153 try:
bgneal@881 154 return bucket.upload_from_filename(file_key, img_path, public=True)
bgneal@881 155 except IOError as ex:
bgneal@881 156 logger.error("Error uploading file: %s", ex)
bgneal@881 157 return None
bgneal@881 158
bgneal@881 159
bgneal@888 160 def convert_to_ssl(parsed_url):
bgneal@888 161 """Top-level function for moving an image to SSL."""
bgneal@888 162
bgneal@888 163 src = parsed_url.geturl()
bgneal@888 164
bgneal@888 165 # Check the cache first
bgneal@888 166 new_url = url_cache.get(src)
bgneal@888 167 if new_url:
bgneal@888 168 logger.info("Found URL in cache: %s => %s", src, new_url)
bgneal@888 169 return new_url
bgneal@888 170
bgneal@888 171 # It has been observed that at least 2 different services
bgneal@888 172 # serve up the same image on https: with the URL otherwise the same.
bgneal@888 173 # Check to see if the image is available via https first.
bgneal@888 174 new_url = check_https_availability(parsed_url)
bgneal@888 175 if new_url:
bgneal@889 176 url_cache[src] = new_url
bgneal@888 177 return new_url
bgneal@888 178
bgneal@888 179 # If none of the above worked, try to download and upload to our S3 bucket
bgneal@889 180 new_url = save_image_to_cloud(src)
bgneal@889 181 if new_url:
bgneal@889 182 url_cache[src] = new_url
bgneal@889 183 return new_url
bgneal@888 184
bgneal@888 185
bgneal@888 186 def check_https_availability(parsed_url):
bgneal@888 187 """Given a urlparse.urlparse() result, perform a HEAD request over https
bgneal@888 188 using the same net location and path. If we get a response that indicates an
bgneal@888 189 image is available, return the url of the image over https. Otherwise return
bgneal@888 190 None.
bgneal@888 191 """
bgneal@888 192 logger.info("Checking https availability for %s", parsed_url.geturl())
bgneal@888 193 con = httplib.HTTPSConnection(parsed_url.netloc)
bgneal@888 194 try:
bgneal@888 195 con.request('HEAD', parsed_url.path)
bgneal@888 196 except (httplib.HTTPException, socket.timeout) as ex:
bgneal@888 197 logger.info("https HEAD request failed: %s", ex)
bgneal@888 198 return None
bgneal@888 199
bgneal@888 200 content_type = None
bgneal@888 201 response = con.getresponse()
bgneal@888 202 if response.status == 200:
bgneal@888 203 content_type = response.getheader('content-type')
bgneal@888 204 if content_type:
bgneal@888 205 parts = content_type.split('/')
bgneal@888 206 if len(parts) >= 2 and parts[0] == 'image':
bgneal@888 207 url = urlparse.urlunparse(('https', ) + parsed_url[1:])
bgneal@888 208 logger.info("Image is available at %s", url)
bgneal@888 209 return url
bgneal@888 210
bgneal@888 211 logger.info('https HEAD request failed; status = %d, content-type = %s',
bgneal@888 212 response.status, content_type)
bgneal@888 213 return None
bgneal@888 214
bgneal@888 215
bgneal@868 216 def save_image_to_cloud(src):
bgneal@881 217 """Downloads an image at a given source URL. Uploads it to cloud storage.
bgneal@881 218
bgneal@881 219 Returns the new URL or None if unsuccessful.
bgneal@881 220 """
bgneal@881 221 fn = download_image(src)
bgneal@881 222 if fn:
bgneal@881 223 resize_image(fn)
bgneal@889 224 return upload_image(fn)
bgneal@881 225 return None
bgneal@868 226
bgneal@868 227
bgneal@866 228 def replace_image_markup(match):
bgneal@870 229 src_parts = match.group(8).split()
bgneal@868 230 if src_parts:
bgneal@868 231 src = src_parts[0]
bgneal@868 232 if src[0] == "<" and src[-1] == ">":
bgneal@868 233 src = src[1:-1]
bgneal@868 234 else:
bgneal@868 235 src = ''
bgneal@868 236
bgneal@868 237 title = ''
bgneal@868 238 if len(src_parts) > 1:
bgneal@868 239 title = " ".join(src_parts[1:])
bgneal@870 240 alt = match.group(1)
bgneal@868 241
bgneal@871 242 new_src = None
bgneal@868 243 if src:
bgneal@868 244 r = urlparse.urlparse(src)
bgneal@871 245 if r.hostname in SG101_HOSTS:
bgneal@871 246 new_src = r.path # convert to relative path
bgneal@871 247 elif r.scheme == 'http':
bgneal@888 248 # Try a few things to get this on ssl:
bgneal@888 249 new_src = convert_to_ssl(r)
bgneal@868 250 elif r.scheme == 'https':
bgneal@868 251 new_src = src # already https, accept it as-is
bgneal@868 252
bgneal@868 253 if new_src:
bgneal@868 254 if title:
bgneal@871 255 s = u'![{alt}]({src} {title})'.format(alt=alt, src=new_src, title=title)
bgneal@868 256 else:
bgneal@868 257 s = u'![{alt}]({src})'.format(alt=alt, src=new_src)
bgneal@868 258 else:
bgneal@868 259 # something's messed up, convert to a link using original src
bgneal@868 260 s = u'[{alt}]({src})'.format(alt=alt, src=src)
bgneal@868 261
bgneal@868 262 return s
bgneal@860 263
bgneal@860 264
bgneal@887 265 def warn_if_image_refs(text, model_name, pk):
bgneal@887 266 """Search text for Markdown image reference markup.
bgneal@887 267
bgneal@887 268 We aren't expecting these, but we will log something if we see any.
bgneal@887 269 """
bgneal@887 270 if IMAGE_REF_RE.search(text):
bgneal@887 271 logger.warning("Image reference found in %s pk = #%d", model_name, pk)
bgneal@887 272
bgneal@887 273
bgneal@866 274 def process_post(text):
bgneal@863 275 """Process the post object:
bgneal@863 276
bgneal@863 277 A regex substitution is run on the post's text field. This fixes up image
bgneal@863 278 links, getting rid of plain old http sources; either converting to https
bgneal@863 279 or relative style links (if the link is to SG101).
bgneal@863 280
bgneal@863 281 """
bgneal@866 282 return IMAGE_LINK_RE.sub(replace_image_markup, text)
bgneal@863 283
bgneal@863 284
bgneal@894 285 def html_check(html):
bgneal@894 286 """Return True if the given HTML fragment has <img> tags with src attributes
bgneal@894 287 that use http, and False otherwise.
bgneal@894 288 """
bgneal@894 289 if not html:
bgneal@894 290 return False
bgneal@894 291
bgneal@894 292 root = etree.HTML(html)
bgneal@894 293 for img in root.iter('img'):
bgneal@894 294 src = img.get('src')
bgneal@894 295 if src and src.lower().startswith('http:'):
bgneal@894 296 return True
bgneal@894 297 return False
bgneal@894 298
bgneal@894 299
bgneal@859 300 class Command(NoArgsCommand):
bgneal@859 301 help = "Rewrite forum posts and comments to not use http for images"
bgneal@859 302 option_list = NoArgsCommand.option_list + (
bgneal@866 303 make_option('-m', '--model',
bgneal@866 304 choices=MODEL_CHOICES,
bgneal@866 305 help="which model to update; must be one of {{{}}}".format(
bgneal@866 306 ', '.join(MODEL_CHOICES))),
bgneal@860 307 make_option('-i', '--i',
bgneal@859 308 type='int',
bgneal@863 309 help="optional first slice index; the i in [i:j]"),
bgneal@860 310 make_option('-j', '--j',
bgneal@859 311 type='int',
bgneal@863 312 help="optional second slice index; the j in [i:j]"),
bgneal@859 313 )
bgneal@859 314
bgneal@859 315 def handle_noargs(self, **options):
bgneal@895 316 time_started = datetime.datetime.now()
bgneal@859 317 _setup_logging()
bgneal@860 318 logger.info("Starting; arguments received: %s", options)
bgneal@859 319
bgneal@866 320 if options['model'] not in MODEL_CHOICES:
bgneal@866 321 raise CommandError('Please choose a --model option')
bgneal@859 322
bgneal@866 323 if options['model'] == 'comments':
bgneal@860 324 qs = Comment.objects.all()
bgneal@866 325 text_attr = 'comment'
bgneal@881 326 model_name = 'Comment'
bgneal@860 327 else:
bgneal@860 328 qs = Post.objects.all()
bgneal@866 329 text_attr = 'body'
bgneal@881 330 model_name = 'Post'
bgneal@860 331
bgneal@860 332 i, j = options['i'], options['j']
bgneal@860 333
bgneal@860 334 if i is not None and i < 0:
bgneal@860 335 raise CommandError("-i must be >= 0")
bgneal@860 336 if j is not None and j < 0:
bgneal@860 337 raise CommandError("-j must be >= 0")
bgneal@860 338 if j is not None and i is not None and j <= i:
bgneal@860 339 raise CommandError("-j must be > -i")
bgneal@860 340
bgneal@860 341 if i is not None and j is not None:
bgneal@860 342 qs = qs[i:j]
bgneal@860 343 elif i is not None and j is None:
bgneal@860 344 qs = qs[i:]
bgneal@860 345 elif i is None and j is not None:
bgneal@860 346 qs = qs[:j]
bgneal@860 347
bgneal@881 348 # Set global socket timeout
bgneal@881 349 socket.setdefaulttimeout(30)
bgneal@881 350
bgneal@863 351 # Install signal handler for ctrl-c
bgneal@863 352 signal.signal(signal.SIGINT, signal_handler)
bgneal@863 353
bgneal@881 354 # Create URL opener to download photos
bgneal@881 355 global opener
bgneal@881 356 opener = ImageURLopener()
bgneal@881 357
bgneal@881 358 # Create bucket to upload photos
bgneal@881 359 global bucket
bgneal@881 360 bucket = S3Bucket(access_key=settings.USER_PHOTOS_ACCESS_KEY,
bgneal@881 361 secret_key=settings.USER_PHOTOS_SECRET_KEY,
bgneal@881 362 base_url=PHOTO_BASE_URL,
bgneal@881 363 bucket_name=PHOTO_BUCKET_NAME)
bgneal@887 364
bgneal@887 365 if i is None:
bgneal@887 366 i = 0
bgneal@887 367
bgneal@895 368 count = 0
bgneal@881 369 for n, model in enumerate(qs.iterator()):
bgneal@863 370 if quit_flag:
bgneal@863 371 logger.warning("SIGINT received, exiting")
bgneal@881 372 break
bgneal@881 373 logger.info("Processing %s #%d (pk = %d)", model_name, n + i, model.pk)
bgneal@866 374 txt = getattr(model, text_attr)
bgneal@887 375 warn_if_image_refs(txt, model_name, model.pk)
bgneal@866 376 new_txt = process_post(txt)
bgneal@881 377 if txt != new_txt:
bgneal@889 378 logger.info("Content changed on %s #%d (pk = %d)",
bgneal@887 379 model_name, n + i, model.pk)
bgneal@881 380 logger.debug("original: %s", txt)
bgneal@881 381 logger.debug("changed: %s", new_txt)
bgneal@887 382 setattr(model, text_attr, new_txt)
bgneal@887 383 model.save()
bgneal@894 384 elif html_check(model.html):
bgneal@894 385 # Check for content generated with older smiley code that used
bgneal@894 386 # absolute URLs for the smiley images. If True, then just save
bgneal@894 387 # the model again to force updated HTML to be created.
bgneal@894 388 logger.info("Older Smiley HTML detected, forcing a save")
bgneal@894 389 model.save()
bgneal@895 390 count += 1
bgneal@860 391
bgneal@895 392 time_finished = datetime.datetime.now()
bgneal@895 393 elapsed = time_finished - time_started
bgneal@895 394 logger.info("ssl_images exiting; number of objects: %d; elapsed: %s",
bgneal@895 395 count, elapsed)