Completed
Push — master ( 7365f5...41cb1b )
by Andrew
33s
created

process_images()   B

Complexity

Conditions 6

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
c 1
b 0
f 0
dl 0
loc 11
rs 8
1
from chat.models import Image
2
from chat.tornado.constants import VarNames
3
from chat.utils import extract_photo, get_max_key
4
5
6
def process_images(images, message):
7
	if images:
8
		if message.symbol:
9
			replace_symbols_if_needed(images, message)
10
		new_symbol = get_max_key(images)
11
		if message.symbol is None or new_symbol > message.symbol:
12
			message.symbol = new_symbol
13
	db_images = save_images(images, message.id)
14
	if message.symbol:  # fetch all, including that we just store
15
		db_images = Image.objects.filter(message_id=message.id)
16
	return prepare_img(db_images, message.id)
17
18
19
def save_images(images, message_id):
20
	db_images = []
21
	if images:
22
		db_images = [Image(
23
			message_id=message_id,
24
			img=extract_photo(
25
				images[k][VarNames.IMG_B64],
26
				images[k][VarNames.IMG_FILE_NAME]
27
			),
28
			symbol=k) for k in images]
29
		Image.objects.bulk_create(db_images)
30
	return db_images
31
32
33
def replace_symbols_if_needed(images, message):
34
	# if message was edited user wasn't notified about that and he edits message again
35
	# his symbol can go out of sync
36
	order = ord(message.symbol)
37
	new_dict = []
38
	for img in images:
39
		if img <= message.symbol:
40
			order += 1
41
			new_symb = chr(order)
42
			new_dict.append({
43
				'new': new_symb,
44
				'old': img,
45
				'value': images[img]
46
			})
47
			message.content = message.content.replace(img, new_symb)
48
	for d in new_dict:  # dictionary changed size during iteration
49
		del images[d['old']]
50
		images[d['new']] = d['value']
51
52
53
def prepare_img(images, message_id):
54
	"""
55
	:type message_id: int 
56
	:type images: list[chat.models.Image] 
57
	"""
58
	if images:
59
		return {x.symbol: x.img.url for x in images if x.message_id == message_id}
60
61
62
def get_message_images(messages):
63
	ids = [message.id for message in messages if message.symbol]
64
	if ids:
65
		images = Image.objects.filter(message_id__in=ids)
66
	else:
67
		images = []
68
	return images
69
70
71