]> git.lizzy.rs Git - nhentai.git/blob - nhentai/parser.py
Merge pull request #162 from Nontre12/master
[nhentai.git] / nhentai / parser.py
1 # coding: utf-8
2 from __future__ import unicode_literals, print_function
3
4 import sys
5 import os
6 import re
7 import time
8 from bs4 import BeautifulSoup
9 from tabulate import tabulate
10
11 import nhentai.constant as constant
12 from nhentai.utils import request
13 from nhentai.logger import logger
14
15
16 def _get_csrf_token(content):
17     html = BeautifulSoup(content, 'html.parser')
18     csrf_token_elem = html.find('input', attrs={'name': 'csrfmiddlewaretoken'})
19     if not csrf_token_elem:
20         raise Exception('Cannot find csrf token to login')
21     return csrf_token_elem.attrs['value']
22
23
24 def login(username, password):
25     logger.warning('This feature is deprecated, please use --cookie to set your cookie.')
26     csrf_token = _get_csrf_token(request('get', url=constant.LOGIN_URL).text)
27     if os.getenv('DEBUG'):
28         logger.info('Getting CSRF token ...')
29
30     if os.getenv('DEBUG'):
31         logger.info('CSRF token is {}'.format(csrf_token))
32
33     login_dict = {
34         'csrfmiddlewaretoken': csrf_token,
35         'username_or_email': username,
36         'password': password,
37     }
38     resp = request('post', url=constant.LOGIN_URL, data=login_dict)
39
40     if 'You\'re loading pages way too quickly.' in resp.text or 'Really, slow down' in resp.text:
41         csrf_token = _get_csrf_token(resp.text)
42         resp = request('post', url=resp.url, data={'csrfmiddlewaretoken': csrf_token, 'next': '/'})
43
44     if 'Invalid username/email or password' in resp.text:
45         logger.error('Login failed, please check your username and password')
46         exit(1)
47
48     if 'You\'re loading pages way too quickly.' in resp.text or 'Really, slow down' in resp.text:
49         logger.error('Using nhentai --cookie \'YOUR_COOKIE_HERE\' to save your Cookie.')
50         exit(2)
51
52
53 def _get_title_and_id(response):
54     result = []
55     html = BeautifulSoup(response, 'html.parser')
56     doujinshi_search_result = html.find_all('div', attrs={'class': 'gallery'})
57     for doujinshi in doujinshi_search_result:
58         doujinshi_container = doujinshi.find('div', attrs={'class': 'caption'})
59         title = doujinshi_container.text.strip()
60         title = title if len(title) < 85 else title[:82] + '...'
61         id_ = re.search('/g/(\d+)/', doujinshi.a['href']).group(1)
62         result.append({'id': id_, 'title': title})
63
64     return result
65
66
67 def favorites_parser(page_range=''):
68     result = []
69     html = BeautifulSoup(request('get', constant.FAV_URL).content, 'html.parser')
70     count = html.find('span', attrs={'class': 'count'})
71     if not count:
72         logger.error("Can't get your number of favorited doujins. Did the login failed?")
73         return []
74
75     count = int(count.text.strip('(').strip(')').replace(',', ''))
76     if count == 0:
77         logger.warning('No favorites found')
78         return []
79     pages = int(count / 25)
80
81     if pages:
82         pages += 1 if count % (25 * pages) else 0
83     else:
84         pages = 1
85
86     logger.info('You have %d favorites in %d pages.' % (count, pages))
87
88     if os.getenv('DEBUG'):
89         pages = 1
90
91     page_range_list = range(1, pages + 1)
92     if page_range:
93         logger.info('page range is {0}'.format(page_range))
94         page_range_list = page_range_parser(page_range, pages)
95
96     for page in page_range_list:
97         try:
98             logger.info('Getting doujinshi ids of page %d' % page)
99             resp = request('get', constant.FAV_URL + '?page=%d' % page).content
100
101             result.extend(_get_title_and_id(resp))
102         except Exception as e:
103             logger.error('Error: %s, continue', str(e))
104
105     return result
106
107
108 def page_range_parser(page_range, max_page_num):
109     pages = set()
110     ranges = str.split(page_range, ',')
111     for range_str in ranges:
112         idx = range_str.find('-')
113         if idx == -1:
114             try:
115                 page = int(range_str)
116                 if page <= max_page_num:
117                     pages.add(page)
118             except ValueError:
119                 logger.error('page range({0}) is not valid'.format(page_range))
120         else:
121             try:
122                 left = int(range_str[:idx])
123                 right = int(range_str[idx + 1:])
124                 if right > max_page_num:
125                     right = max_page_num
126                 for page in range(left, right + 1):
127                     pages.add(page)
128             except ValueError:
129                 logger.error('page range({0}) is not valid'.format(page_range))
130
131     return list(pages)
132
133
134 def doujinshi_parser(id_):
135     if not isinstance(id_, (int,)) and (isinstance(id_, (str,)) and not id_.isdigit()):
136         raise Exception('Doujinshi id({0}) is not valid'.format(id_))
137
138     id_ = int(id_)
139     logger.log(15, 'Fetching doujinshi information of id {0}'.format(id_))
140     doujinshi = dict()
141     doujinshi['id'] = id_
142     url = '{0}/{1}/'.format(constant.DETAIL_URL, id_)
143
144     try:
145         response = request('get', url)
146         if response.status_code in (200,):
147             response = response.content
148         else:
149             logger.debug('Slow down and retry ({}) ...'.format(id_))
150             time.sleep(1)
151             return doujinshi_parser(str(id_))
152
153     except Exception as e:
154         logger.warn('Error: {}, ignored'.format(str(e)))
155         return None
156
157     html = BeautifulSoup(response, 'html.parser')
158     doujinshi_info = html.find('div', attrs={'id': 'info'})
159
160     title = doujinshi_info.find('h1').text
161     subtitle = doujinshi_info.find('h2')
162
163     doujinshi['name'] = title
164     doujinshi['subtitle'] = subtitle.text if subtitle else ''
165
166     doujinshi_cover = html.find('div', attrs={'id': 'cover'})
167     img_id = re.search('/galleries/([\d]+)/cover\.(jpg|png|gif)$', doujinshi_cover.a.img.attrs['data-src'])
168
169     ext = []
170     for i in html.find_all('div', attrs={'class': 'thumb-container'}):
171         _, ext_name = os.path.basename(i.img.attrs['data-src']).rsplit('.', 1)
172         ext.append(ext_name)
173
174     if not img_id:
175         logger.critical('Tried yo get image id failed')
176         exit(1)
177
178     doujinshi['img_id'] = img_id.group(1)
179     doujinshi['ext'] = ext
180
181     for _ in doujinshi_info.find_all('div', class_='tag-container field-name'):
182         if re.search('Pages:', _.text):
183             pages = _.find('span', class_='name').string
184     doujinshi['pages'] = int(pages)
185
186     # gain information of the doujinshi
187     information_fields = doujinshi_info.find_all('div', attrs={'class': 'field-name'})
188     needed_fields = ['Characters', 'Artists', 'Languages', 'Tags', 'Parodies', 'Groups', 'Categories']
189     for field in information_fields:
190         field_name = field.contents[0].strip().strip(':')
191         if field_name in needed_fields:
192             data = [sub_field.find('span', attrs={'class': 'name'}).contents[0].strip() for sub_field in
193                     field.find_all('a', attrs={'class': 'tag'})]
194             doujinshi[field_name.lower()] = ', '.join(data)
195
196     time_field = doujinshi_info.find('time')
197     if time_field.has_attr('datetime'):
198         doujinshi['date'] = time_field['datetime']
199     return doujinshi
200
201
202 def old_search_parser(keyword, sorting='date', page=1):
203     logger.debug('Searching doujinshis of keyword {0}'.format(keyword))
204     response = request('get', url=constant.SEARCH_URL, params={'q': keyword, 'page': page, 'sort': sorting}).content
205
206     result = _get_title_and_id(response)
207     if not result:
208         logger.warn('Not found anything of keyword {}'.format(keyword))
209
210     return result
211
212
213 def print_doujinshi(doujinshi_list):
214     if not doujinshi_list:
215         return
216     doujinshi_list = [(i['id'], i['title']) for i in doujinshi_list]
217     headers = ['id', 'doujinshi']
218     logger.info('Search Result\n' +
219                 tabulate(tabular_data=doujinshi_list, headers=headers, tablefmt='rst'))
220
221
222 def search_parser(keyword, sorting, page):
223     logger.debug('Searching doujinshis using keywords {0}'.format(keyword))
224     # keyword = '+'.join([i.strip().replace(' ', '-').lower() for i in keyword.split(',')])
225     result = []
226     i = 0
227     while i < 5:
228         try:
229             url = request('get', url=constant.SEARCH_URL, params={'query': keyword, 'page': page, 'sort': sorting}).url
230             response = request('get', url.replace('%2B', '+')).json()
231         except Exception as e:
232             logger.critical(str(e))
233
234         break
235
236     if 'result' not in response:
237         raise Exception('No result in response')
238
239     for row in response['result']:
240         title = row['title']['english']
241         title = title[:85] + '..' if len(title) > 85 else title
242         result.append({'id': row['id'], 'title': title})
243
244     if not result:
245         logger.warn('No results for keywords {}'.format(keyword))
246
247     return result
248
249
250 def __api_suspended_doujinshi_parser(id_):
251     if not isinstance(id_, (int,)) and (isinstance(id_, (str,)) and not id_.isdigit()):
252         raise Exception('Doujinshi id({0}) is not valid'.format(id_))
253
254     id_ = int(id_)
255     logger.log(15, 'Fetching information of doujinshi id {0}'.format(id_))
256     doujinshi = dict()
257     doujinshi['id'] = id_
258     url = '{0}/{1}'.format(constant.DETAIL_URL, id_)
259     i = 0
260     while 5 > i:
261         try:
262             response = request('get', url).json()
263         except Exception as e:
264             i += 1
265             if not i < 5:
266                 logger.critical(str(e))
267                 exit(1)
268             continue
269         break
270
271     doujinshi['name'] = response['title']['english']
272     doujinshi['subtitle'] = response['title']['japanese']
273     doujinshi['img_id'] = response['media_id']
274     doujinshi['ext'] = ''.join([i['t'] for i in response['images']['pages']])
275     doujinshi['pages'] = len(response['images']['pages'])
276
277     # gain information of the doujinshi
278     needed_fields = ['character', 'artist', 'language', 'tag', 'parody', 'group', 'category']
279     for tag in response['tags']:
280         tag_type = tag['type']
281         if tag_type in needed_fields:
282             if tag_type == 'tag':
283                 if tag_type not in doujinshi:
284                     doujinshi[tag_type] = {}
285
286                 tag['name'] = tag['name'].replace(' ', '-')
287                 tag['name'] = tag['name'].lower()
288                 doujinshi[tag_type][tag['name']] = tag['id']
289             elif tag_type not in doujinshi:
290                 doujinshi[tag_type] = tag['name']
291             else:
292                 doujinshi[tag_type] += ', ' + tag['name']
293
294     return doujinshi
295
296
297 if __name__ == '__main__':
298     print(doujinshi_parser("32271"))