]> git.lizzy.rs Git - nhentai.git/blob - nhentai/parser.py
62224d58f49f03755dd63e0b2d8185d05149b370
[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     pages = 0
182     for _ in doujinshi_info.find_all('div', class_=''):
183         pages = re.search('([\d]+) pages', _.text)
184         if pages:
185             pages = pages.group(1)
186             break
187     doujinshi['pages'] = int(pages)
188
189     # gain information of the doujinshi
190     information_fields = doujinshi_info.find_all('div', attrs={'class': 'field-name'})
191     needed_fields = ['Characters', 'Artists', 'Languages', 'Tags', 'Parodies', 'Groups', 'Categories']
192     for field in information_fields:
193         field_name = field.contents[0].strip().strip(':')
194         if field_name in needed_fields:
195             data = [sub_field.contents[0].strip() for sub_field in
196                     field.find_all('a', attrs={'class': 'tag'})]
197             doujinshi[field_name.lower()] = ', '.join(data)
198
199     time_field = doujinshi_info.find('time')
200     if time_field.has_attr('datetime'):
201         doujinshi['date'] = time_field['datetime']
202     return doujinshi
203
204
205 def old_search_parser(keyword, sorting='date', page=1):
206     logger.debug('Searching doujinshis of keyword {0}'.format(keyword))
207     response = request('get', url=constant.SEARCH_URL, params={'q': keyword, 'page': page, 'sort': sorting}).content
208
209     result = _get_title_and_id(response)
210     if not result:
211         logger.warn('Not found anything of keyword {}'.format(keyword))
212
213     return result
214
215
216 def print_doujinshi(doujinshi_list):
217     if not doujinshi_list:
218         return
219     doujinshi_list = [(i['id'], i['title']) for i in doujinshi_list]
220     headers = ['id', 'doujinshi']
221     logger.info('Search Result\n' +
222                 tabulate(tabular_data=doujinshi_list, headers=headers, tablefmt='rst'))
223
224
225 def search_parser(keyword, sorting, page):
226     logger.debug('Searching doujinshis using keywords {0}'.format(keyword))
227     keyword = '+'.join([i.strip().replace(' ', '-').lower() for i in keyword.split(',')])
228     result = []
229     i = 0
230     while i < 5:
231         try:
232             url = request('get', url=constant.SEARCH_URL, params={'query': keyword, 'page': page, 'sort': sorting}).url
233             response = request('get', url.replace('%2B', '+')).json()
234         except Exception as e:
235             i += 1
236             if not i < 5:
237                 logger.critical(str(e))
238                 logger.warn('If you are in China, please configure the proxy to fu*k GFW.')
239                 exit(1)
240             continue
241         break
242
243     if 'result' not in response:
244         raise Exception('No result in response')
245
246     for row in response['result']:
247         title = row['title']['english']
248         title = title[:85] + '..' if len(title) > 85 else title
249         result.append({'id': row['id'], 'title': title})
250
251     if not result:
252         logger.warn('No results for keywords {}'.format(keyword))
253
254     return result
255
256
257 def __api_suspended_doujinshi_parser(id_):
258     if not isinstance(id_, (int,)) and (isinstance(id_, (str,)) and not id_.isdigit()):
259         raise Exception('Doujinshi id({0}) is not valid'.format(id_))
260
261     id_ = int(id_)
262     logger.log(15, 'Fetching information of doujinshi id {0}'.format(id_))
263     doujinshi = dict()
264     doujinshi['id'] = id_
265     url = '{0}/{1}'.format(constant.DETAIL_URL, id_)
266     i = 0
267     while 5 > i:
268         try:
269             response = request('get', url).json()
270         except Exception as e:
271             i += 1
272             if not i < 5:
273                 logger.critical(str(e))
274                 exit(1)
275             continue
276         break
277
278     doujinshi['name'] = response['title']['english']
279     doujinshi['subtitle'] = response['title']['japanese']
280     doujinshi['img_id'] = response['media_id']
281     doujinshi['ext'] = ''.join([i['t'] for i in response['images']['pages']])
282     doujinshi['pages'] = len(response['images']['pages'])
283
284     # gain information of the doujinshi
285     needed_fields = ['character', 'artist', 'language', 'tag', 'parody', 'group', 'category']
286     for tag in response['tags']:
287         tag_type = tag['type']
288         if tag_type in needed_fields:
289             if tag_type == 'tag':
290                 if tag_type not in doujinshi:
291                     doujinshi[tag_type] = {}
292
293                 tag['name'] = tag['name'].replace(' ', '-')
294                 tag['name'] = tag['name'].lower()
295                 doujinshi[tag_type][tag['name']] = tag['id']
296             elif tag_type not in doujinshi:
297                 doujinshi[tag_type] = tag['name']
298             else:
299                 doujinshi[tag_type] += ', ' + tag['name']
300
301     return doujinshi
302
303
304 if __name__ == '__main__':
305     print(doujinshi_parser("32271"))