Fix for comments.
[librarian.git] / src / librarian / covers / widgets / background.py
1 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
3 #
4 import io
5 import time
6 from urllib.request import urlopen
7 import PIL.Image
8 from .base import Widget
9
10
11 class Background(Widget):
12     transparency = False
13
14     def __init__(self, cover, crop_to_square=True):
15         self.crop_to_square = crop_to_square
16         super().__init__(cover)
17
18     def setup(self):
19         self.img = None
20         if self.cover.book_info.cover_url:
21             while True:
22                 try:
23                     data = io.BytesIO(urlopen(self.cover.book_info.cover_url, timeout=3).read())
24                 except:
25                     time.sleep(2)
26                 else:
27                     break
28                 
29             img = PIL.Image.open(data)
30
31             if self.crop_to_square:
32                 # crop top square.
33                 if img.size[1] > img.size[0]:
34                     img = img.crop((0, 0, img.size[0], img.size[0]))
35                 else:
36                     left = round((img.size[0] - img.size[1])/2)
37                     img = img.crop((
38                         left,
39                         0,
40                         left + img.size[1],
41                         img.size[1]
42                     ))
43             self.img = img
44
45     def build(self, w, h):
46         if not self.img:
47             return
48         img = self.img
49         scale = max(
50             w / img.size[0],
51             h / img.size[1]
52         )
53         img = self.img.resize((
54             round(scale * img.size[0]),
55             round(scale * img.size[1]),
56         ))
57         img = img.crop((
58             int((img.size[0] - w) / 2),
59             0,
60             w + int((img.size[0] - w) / 2),
61             h))
62         
63         return img