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@859
|
9 import logging
|
bgneal@859
|
10 from optparse import make_option
|
bgneal@859
|
11 import os.path
|
bgneal@863
|
12 import re
|
bgneal@863
|
13 import signal
|
bgneal@868
|
14 import urlparse
|
bgneal@859
|
15
|
bgneal@859
|
16 from django.core.management.base import NoArgsCommand, CommandError
|
bgneal@859
|
17 from django.conf import settings
|
bgneal@863
|
18 import markdown.inlinepatterns
|
bgneal@859
|
19
|
bgneal@860
|
20 from comments.models import Comment
|
bgneal@860
|
21 from forums.models import Post
|
bgneal@860
|
22
|
bgneal@860
|
23
|
bgneal@859
|
24 LOGFILE = os.path.join(settings.PROJECT_PATH, 'logs', 'ssl_images.log')
|
bgneal@859
|
25 logger = logging.getLogger(__name__)
|
bgneal@859
|
26
|
bgneal@863
|
27 IMAGE_LINK_RE = re.compile(markdown.inlinepatterns.IMAGE_LINK_RE)
|
bgneal@863
|
28 IMAGE_REF_RE = re.compile(markdown.inlinepatterns.IMAGE_REFERENCE_RE)
|
bgneal@863
|
29
|
bgneal@868
|
30 SG101_HOSTS = set(['www.surfguitar101.com', 'surfguitar101.com'])
|
bgneal@866
|
31 MODEL_CHOICES = ['comments', 'posts']
|
bgneal@866
|
32
|
bgneal@863
|
33 quit_flag = False
|
bgneal@863
|
34
|
bgneal@863
|
35
|
bgneal@863
|
36 def signal_handler(signum, frame):
|
bgneal@863
|
37 """SIGINT signal handler"""
|
bgneal@863
|
38 global quit_flag
|
bgneal@863
|
39 quit_flag = True
|
bgneal@863
|
40
|
bgneal@859
|
41
|
bgneal@859
|
42 def _setup_logging():
|
bgneal@859
|
43 logger.setLevel(logging.DEBUG)
|
bgneal@859
|
44 logger.propagate = False
|
bgneal@859
|
45 handler = logging.FileHandler(filename=LOGFILE, encoding='utf-8')
|
bgneal@859
|
46 formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
|
bgneal@859
|
47 handler.setFormatter(formatter)
|
bgneal@859
|
48 logger.addHandler(handler)
|
bgneal@859
|
49
|
bgneal@859
|
50
|
bgneal@868
|
51 def save_image_to_cloud(src):
|
bgneal@868
|
52 # TODO
|
bgneal@868
|
53 return src
|
bgneal@868
|
54
|
bgneal@868
|
55
|
bgneal@866
|
56 def replace_image_markup(match):
|
bgneal@868
|
57 src_parts = match.group(9).split()
|
bgneal@868
|
58 if src_parts:
|
bgneal@868
|
59 src = src_parts[0]
|
bgneal@868
|
60 if src[0] == "<" and src[-1] == ">":
|
bgneal@868
|
61 src = src[1:-1]
|
bgneal@868
|
62 else:
|
bgneal@868
|
63 src = ''
|
bgneal@868
|
64
|
bgneal@868
|
65 title = ''
|
bgneal@868
|
66 if len(src_parts) > 1:
|
bgneal@868
|
67 title = " ".join(src_parts[1:])
|
bgneal@868
|
68 alt = match.group(2)
|
bgneal@868
|
69
|
bgneal@868
|
70 new_src = ''
|
bgneal@868
|
71 if src:
|
bgneal@868
|
72 r = urlparse.urlparse(src)
|
bgneal@868
|
73 if r.scheme == 'http':
|
bgneal@868
|
74 if r.hostname in SG101_HOSTS:
|
bgneal@868
|
75 new_src = r.path # convert to relative path
|
bgneal@868
|
76 else:
|
bgneal@868
|
77 new_src = save_image_to_cloud(src)
|
bgneal@868
|
78 elif r.scheme == 'https':
|
bgneal@868
|
79 new_src = src # already https, accept it as-is
|
bgneal@868
|
80
|
bgneal@868
|
81 if new_src:
|
bgneal@868
|
82 if title:
|
bgneal@868
|
83 s = u'![{alt}]({src} "{title}")'.format(alt=alt, src=new_src, title=title)
|
bgneal@868
|
84 else:
|
bgneal@868
|
85 s = u'![{alt}]({src})'.format(alt=alt, src=new_src)
|
bgneal@868
|
86 else:
|
bgneal@868
|
87 # something's messed up, convert to a link using original src
|
bgneal@868
|
88 s = u'[{alt}]({src})'.format(alt=alt, src=src)
|
bgneal@868
|
89
|
bgneal@868
|
90 return s
|
bgneal@860
|
91
|
bgneal@860
|
92
|
bgneal@866
|
93 def process_post(text):
|
bgneal@863
|
94 """Process the post object:
|
bgneal@863
|
95
|
bgneal@863
|
96 A regex substitution is run on the post's text field. This fixes up image
|
bgneal@863
|
97 links, getting rid of plain old http sources; either converting to https
|
bgneal@863
|
98 or relative style links (if the link is to SG101).
|
bgneal@863
|
99
|
bgneal@863
|
100 We also do a search for Markdown image reference markup. We aren't expecting
|
bgneal@863
|
101 these, but we will log something if we see any.
|
bgneal@863
|
102
|
bgneal@863
|
103 """
|
bgneal@866
|
104 return IMAGE_LINK_RE.sub(replace_image_markup, text)
|
bgneal@863
|
105
|
bgneal@863
|
106
|
bgneal@859
|
107 class Command(NoArgsCommand):
|
bgneal@859
|
108 help = "Rewrite forum posts and comments to not use http for images"
|
bgneal@859
|
109 option_list = NoArgsCommand.option_list + (
|
bgneal@866
|
110 make_option('-m', '--model',
|
bgneal@866
|
111 choices=MODEL_CHOICES,
|
bgneal@866
|
112 help="which model to update; must be one of {{{}}}".format(
|
bgneal@866
|
113 ', '.join(MODEL_CHOICES))),
|
bgneal@860
|
114 make_option('-i', '--i',
|
bgneal@859
|
115 type='int',
|
bgneal@863
|
116 help="optional first slice index; the i in [i:j]"),
|
bgneal@860
|
117 make_option('-j', '--j',
|
bgneal@859
|
118 type='int',
|
bgneal@863
|
119 help="optional second slice index; the j in [i:j]"),
|
bgneal@859
|
120 )
|
bgneal@859
|
121
|
bgneal@859
|
122 def handle_noargs(self, **options):
|
bgneal@859
|
123 _setup_logging()
|
bgneal@860
|
124 logger.info("Starting; arguments received: %s", options)
|
bgneal@859
|
125
|
bgneal@866
|
126 if options['model'] not in MODEL_CHOICES:
|
bgneal@866
|
127 raise CommandError('Please choose a --model option')
|
bgneal@859
|
128
|
bgneal@866
|
129 if options['model'] == 'comments':
|
bgneal@860
|
130 qs = Comment.objects.all()
|
bgneal@866
|
131 text_attr = 'comment'
|
bgneal@860
|
132 else:
|
bgneal@860
|
133 qs = Post.objects.all()
|
bgneal@866
|
134 text_attr = 'body'
|
bgneal@860
|
135
|
bgneal@860
|
136 i, j = options['i'], options['j']
|
bgneal@860
|
137
|
bgneal@860
|
138 if i is not None and i < 0:
|
bgneal@860
|
139 raise CommandError("-i must be >= 0")
|
bgneal@860
|
140 if j is not None and j < 0:
|
bgneal@860
|
141 raise CommandError("-j must be >= 0")
|
bgneal@860
|
142 if j is not None and i is not None and j <= i:
|
bgneal@860
|
143 raise CommandError("-j must be > -i")
|
bgneal@860
|
144
|
bgneal@860
|
145 if i is not None and j is not None:
|
bgneal@860
|
146 qs = qs[i:j]
|
bgneal@860
|
147 elif i is not None and j is None:
|
bgneal@860
|
148 qs = qs[i:]
|
bgneal@860
|
149 elif i is None and j is not None:
|
bgneal@860
|
150 qs = qs[:j]
|
bgneal@860
|
151
|
bgneal@863
|
152 # Install signal handler for ctrl-c
|
bgneal@863
|
153 signal.signal(signal.SIGINT, signal_handler)
|
bgneal@863
|
154
|
bgneal@860
|
155 s = []
|
bgneal@860
|
156 for model in qs.iterator():
|
bgneal@863
|
157 if quit_flag:
|
bgneal@863
|
158 logger.warning("SIGINT received, exiting")
|
bgneal@866
|
159 txt = getattr(model, text_attr)
|
bgneal@866
|
160 new_txt = process_post(txt)
|
bgneal@866
|
161 s.append(new_txt)
|
bgneal@860
|
162
|
bgneal@860
|
163 import pprint
|
bgneal@860
|
164 pprint.pprint(s)
|