2 from __future__ import unicode_literals, print_function
8 from bs4 import BeautifulSoup
9 from tabulate import tabulate
11 import nhentai.constant as constant
12 from nhentai.utils import request
13 from nhentai.logger import logger
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']
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 ...')
30 if os.getenv('DEBUG'):
31 logger.info('CSRF token is {}'.format(csrf_token))
34 'csrfmiddlewaretoken': csrf_token,
35 'username_or_email': username,
38 resp = request('post', url=constant.LOGIN_URL, data=login_dict)
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': '/'})
44 if 'Invalid username/email or password' in resp.text:
45 logger.error('Login failed, please check your username and password')
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.')
53 def _get_title_and_id(response):
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})
67 def favorites_parser(page_range=''):
69 html = BeautifulSoup(request('get', constant.FAV_URL).content, 'html.parser')
70 count = html.find('span', attrs={'class': 'count'})
72 logger.error("Can't get your number of favorited doujins. Did the login failed?")
75 count = int(count.text.strip('(').strip(')').replace(',', ''))
77 logger.warning('No favorites found')
79 pages = int(count / 25)
82 pages += 1 if count % (25 * pages) else 0
86 logger.info('You have %d favorites in %d pages.' % (count, pages))
88 if os.getenv('DEBUG'):
91 page_range_list = range(1, pages + 1)
93 logger.info('page range is {0}'.format(page_range))
94 page_range_list = page_range_parser(page_range, pages)
96 for page in page_range_list:
98 logger.info('Getting doujinshi ids of page %d' % page)
99 resp = request('get', constant.FAV_URL + '?page=%d' % page).content
101 result.extend(_get_title_and_id(resp))
102 except Exception as e:
103 logger.error('Error: %s, continue', str(e))
108 def page_range_parser(page_range, max_page_num):
110 ranges = str.split(page_range, ',')
111 for range_str in ranges:
112 idx = range_str.find('-')
115 page = int(range_str)
116 if page <= max_page_num:
119 logger.error('page range({0}) is not valid'.format(page_range))
122 left = int(range_str[:idx])
123 right = int(range_str[idx + 1:])
124 if right > max_page_num:
126 for page in range(left, right + 1):
129 logger.error('page range({0}) is not valid'.format(page_range))
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_))
139 logger.log(15, 'Fetching doujinshi information of id {0}'.format(id_))
141 doujinshi['id'] = id_
142 url = '{0}/{1}/'.format(constant.DETAIL_URL, id_)
145 response = request('get', url)
146 if response.status_code in (200,):
147 response = response.content
149 logger.debug('Slow down and retry ({}) ...'.format(id_))
151 return doujinshi_parser(str(id_))
153 except Exception as e:
154 logger.warn('Error: {}, ignored'.format(str(e)))
157 html = BeautifulSoup(response, 'html.parser')
158 doujinshi_info = html.find('div', attrs={'id': 'info'})
160 title = doujinshi_info.find('h1').text
161 subtitle = doujinshi_info.find('h2')
163 doujinshi['name'] = title
164 doujinshi['subtitle'] = subtitle.text if subtitle else ''
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'])
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)
175 logger.critical('Tried yo get image id failed')
178 doujinshi['img_id'] = img_id.group(1)
179 doujinshi['ext'] = ext
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)
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)
196 time_field = doujinshi_info.find('time')
197 if time_field.has_attr('datetime'):
198 doujinshi['date'] = time_field['datetime']
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
206 result = _get_title_and_id(response)
208 logger.warn('Not found anything of keyword {}'.format(keyword))
213 def print_doujinshi(doujinshi_list):
214 if not doujinshi_list:
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'))
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(',')])
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))
236 if 'result' not in response:
237 raise Exception('No result in response')
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})
245 logger.warn('No results for keywords {}'.format(keyword))
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_))
255 logger.log(15, 'Fetching information of doujinshi id {0}'.format(id_))
257 doujinshi['id'] = id_
258 url = '{0}/{1}'.format(constant.DETAIL_URL, id_)
262 response = request('get', url).json()
263 except Exception as e:
266 logger.critical(str(e))
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'])
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] = {}
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']
292 doujinshi[tag_type] += ', ' + tag['name']
297 if __name__ == '__main__':
298 print(doujinshi_parser("32271"))