Debian Codegraph @

recipes/arret_sur_images.recipe

raw
1 #!/usr/bin/env python
2 # vim:fileencoding=utf-8
3
4 import json
5 from datetime import datetime
6 from zoneinfo import ZoneInfo
7
8 import mechanize
9
10 from calibre import browser
11 from calibre.web.feeds.news import BasicNewsRecipe
12
13
14 class ArretSurImages(BasicNewsRecipe):
15 title = 'Arrêt sur Images'
16 description = "Site français d'analyse des médias"
17 language = 'fr'
18 encoding = 'utf-8'
19 needs_subscription = True
20 oldest_article = 7
21 max_articles_per_feed = 100
22 no_stylesheets = True
23 remove_javascript = True
24
25 feeds = [('Arrêt sur images', 'https://api.arretsurimages.net/api/public/rss/all-content')]
26
27 def default_cover(self, cover_file):
28 """
29 Crée une couverture personnalisée avec le logo ASI
30 """
31 from qt.core import QColor, QFont, QImage, QPainter, QPen, QRect, Qt
32
33 from calibre.gui2 import ensure_app, load_builtin_fonts, pixmap_to_data
34
35 try:
36 ensure_app()
37 load_builtin_fonts()
38
39 today = datetime.now(ZoneInfo('Europe/Paris'))
40 wkd = today.weekday()
41 french_weekday = {0: 'Lundi', 1: 'Mardi', 2: 'Mercredi', 3: 'Jeudi', 4: 'Vendredi', 5: 'Samedi', 6: 'Dimanche'}
42 french_month = {
43 1: 'janvier',
44 2: 'février',
45 3: 'mars',
46 4: 'avril',
47 5: 'mai',
48 6: 'juin',
49 7: 'juillet',
50 8: 'août',
51 9: 'septembre',
52 10: 'octobre',
53 11: 'novembre',
54 12: 'décembre',
55 }
56
57 weekday = french_weekday[wkd]
58 month = french_month[today.month]
59 date_str = f'{weekday} {today.day} {month} {today.year}'
60 edition = today.strftime('Édition de %Hh')
61
62 img = QImage(1400, 1920, QImage.Format_RGB888)
63 img.fill(QColor('white'))
64
65 # Dessiner la bordure rouge
66 border_painter = QPainter(img)
67 border_pen = QPen(QColor('red'))
68 border_pen.setWidth(120) # Épaisseur de la bordure
69 border_painter.setPen(border_pen)
70 border_painter.drawRect(10, 10, img.width() - 20, img.height() - 20) # Marge de 10 pixels
71 border_painter.end()
72
73 logo_url = 'https://www.arretsurimages.net/assets/img/front/logo-asi-grand.png'
74 logo_data = browser().open(logo_url).read()
75 logo = QImage()
76 logo.loadFromData(logo_data)
77
78 logo_width = 800
79 scaled_logo = logo.scaledToWidth(logo_width, Qt.SmoothTransformation)
80
81 x = (img.width() - scaled_logo.width()) // 2
82 y = (img.height() - scaled_logo.height()) // 2 - 100
83
84 p = QPainter(img)
85 p.drawImage(x, y, scaled_logo)
86 p.end()
87
88 p = QPainter(img)
89 p.setPen(QPen(QColor('black')))
90
91 font = QFont('Liberation Sans', 36)
92 p.setFont(font)
93
94 r = QRect(0, y + scaled_logo.height() + 50, img.width(), 100)
95 p.drawText(r, Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter, date_str)
96
97 font.setItalic(True)
98 font.setPointSize(32)
99 p.setFont(font)
100
101 r = QRect(0, y + scaled_logo.height() + 150, img.width(), 100)
102 p.drawText(r, Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter, edition)
103
104 p.end()
105
106 img_data = pixmap_to_data(img)
107 cover_file.write(img_data)
108 cover_file.flush()
109 return True
110
111 except Exception as e:
112 print(f'Erreur lors de la création de la couverture: {e}')
113 return False
114
115 def get_browser(self):
116 br = BasicNewsRecipe.get_browser(self)
117 if self.username and self.password:
118 auth_data = {
119 'client_id': '1_1e3dazertyukilygfos7ldzertyuof7pfd',
120 'client_secret': '2r8yd4a8un0fn45d93acfr3efrgthzdheifhrehihidg4dk5kds7ds23',
121 'username': self.username,
122 'password': self.password,
123 'grant_type': 'password',
124 }
125 request = mechanize.Request(
126 'https://api.arretsurimages.net/oauth/v2/token',
127 data=json.dumps(auth_data).encode('utf-8'),
128 headers={'Content-Type': 'application/json', 'Accept': 'application/json'},
129 )
130 try:
131 response = br.open(request)
132 auth_response = json.loads(response.read().decode('utf-8'))
133 if 'access_token' in auth_response:
134 br.addheaders += [('Authorization', f'Bearer {auth_response["access_token"]}')]
135 print('Authentification réussie')
136 else:
137 print("Échec de l'authentification - Vérifiez vos identifiants")
138 except Exception as e:
139 print(f"Erreur lors de l'authentification: {e}")
140 return br
141
142 def get_article_url(self, article):
143 url = article.get('link', article.get('guid'))
144 if url:
145 return url.replace('www.arretsurimages.net/', 'api.arretsurimages.net/api/public/contents/')
146 return None
147
148 def preprocess_raw_html(self, raw_html, url):
149 try:
150 article_data = json.loads(raw_html)
151 authors = ', '.join([a.get('name', '') for a in article_data.get('authors', [])])
152 cover_html = ''
153 if article_data.get('cover') and article_data['cover'].get('formats', {}).get('article_header'):
154 cover_slug = article_data['cover']['slug']
155 cover_url = f'https://api.arretsurimages.net/api/public/media/{cover_slug}/action/show?format=article_header'
156 cover_html = f'<img src="{cover_url}" alt="{article_data.get("title", "")}">'
157 return f'''
158 <html>
159 <head><title>{article_data.get('title', 'Article sans titre')}</title></head>
160 <body>
161 <article>
162 <h1>{article_data.get('title', 'Article sans titre')}</h1>
163 <div class="article-meta">
164 <p>Par {authors or "Auteur inconnu"}</p>
165 </div>
166 {cover_html}
167 <div class="article-content">
168 <p><strong>{article_data.get('lead', '')}</strong></p>
169 {article_data.get('content', '')}
170 </div>
171 </article>
172 </body>
173 </html>
174 '''
175 except Exception as e:
176 print(f'Erreur preprocessing HTML: {e}')
177 return raw_html
178
179 def preprocess_html(self, soup):
180 try:
181 for tag in soup.find_all(['asi-html', 'asi-image', 'asi-video']):
182 if tag.name == 'asi-html' and tag.get('data-html'):
183 tag.replace_with(soup.new_tag('div', attrs={'class': 'asi-content'}).append(tag['data-html']))
184 elif tag.name == 'asi-image':
185 img_data = tag.get('data-image', {})
186 if img_data:
187 try:
188 img_data = json.loads(img_data)
189 if img_data.get('slug'):
190 img_url = f'https://api.arretsurimages.net/api/public/media/{img_data["slug"]}/action/show?format=article_body'
191 img_tag = soup.new_tag('img', src=img_url)
192 if img_data.get('caption'):
193 caption_div = soup.new_tag('div', attrs={'class': 'image-caption'})
194 caption_div.string = img_data['caption']
195 tag.replace_with(img_tag)
196 img_tag.insert_after(caption_div)
197 else:
198 tag.replace_with(img_tag)
199 except Exception as e:
200 print(f'Erreur processing image: {e}')
201 tag.decompose()
202 else:
203 tag.decompose()
204 return soup
205 except Exception as e:
206 print(f'Erreur preprocessing HTML: {e}')
207 return soup