]> git.lizzy.rs Git - nhentai.git/blob - nhentai/parser.py
bd60e7a003fb9c479485923082142fe70a2c505e
[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=None):
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 page:
82         page_range_list = page
83     else:
84         if pages:
85             pages += 1 if count % (25 * pages) else 0
86         else:
87             pages = 1
88
89         logger.info('You have %d favorites in %d pages.' % (count, pages))
90
91         if os.getenv('DEBUG'):
92             pages = 1
93
94         page_range_list = range(1, pages + 1)
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 doujinshi_parser(id_):
109     if not isinstance(id_, (int,)) and (isinstance(id_, (str,)) and not id_.isdigit()):
110         raise Exception('Doujinshi id({0}) is not valid'.format(id_))
111
112     id_ = int(id_)
113     logger.log(15, 'Fetching doujinshi information of id {0}'.format(id_))
114     doujinshi = dict()
115     doujinshi['id'] = id_
116     url = '{0}/{1}/'.format(constant.DETAIL_URL, id_)
117
118     try:
119         response = request('get', url)
120         if response.status_code in (200,):
121             response = response.content
122         else:
123             logger.debug('Slow down and retry ({}) ...'.format(id_))
124             time.sleep(1)
125             return doujinshi_parser(str(id_))
126
127     except Exception as e:
128         logger.warn('Error: {}, ignored'.format(str(e)))
129         return None
130
131     html = BeautifulSoup(response, 'html.parser')
132     doujinshi_info = html.find('div', attrs={'id': 'info'})
133
134     title = doujinshi_info.find('h1').text
135     subtitle = doujinshi_info.find('h2')
136
137     doujinshi['name'] = title
138     doujinshi['subtitle'] = subtitle.text if subtitle else ''
139
140     doujinshi_cover = html.find('div', attrs={'id': 'cover'})
141     img_id = re.search('/galleries/([\d]+)/cover\.(jpg|png|gif)$', doujinshi_cover.a.img.attrs['data-src'])
142
143     ext = []
144     for i in html.find_all('div', attrs={'class': 'thumb-container'}):
145         _, ext_name = os.path.basename(i.img.attrs['data-src']).rsplit('.', 1)
146         ext.append(ext_name)
147
148     if not img_id:
149         logger.critical('Tried yo get image id failed')
150         exit(1)
151
152     doujinshi['img_id'] = img_id.group(1)
153     doujinshi['ext'] = ext
154
155     for _ in doujinshi_info.find_all('div', class_='tag-container field-name'):
156         if re.search('Pages:', _.text):
157             pages = _.find('span', class_='name').string
158     doujinshi['pages'] = int(pages)
159
160     # gain information of the doujinshi
161     information_fields = doujinshi_info.find_all('div', attrs={'class': 'field-name'})
162     needed_fields = ['Characters', 'Artists', 'Languages', 'Tags', 'Parodies', 'Groups', 'Categories']
163     for field in information_fields:
164         field_name = field.contents[0].strip().strip(':')
165         if field_name in needed_fields:
166             data = [sub_field.find('span', attrs={'class': 'name'}).contents[0].strip() for sub_field in
167                     field.find_all('a', attrs={'class': 'tag'})]
168             doujinshi[field_name.lower()] = ', '.join(data)
169
170     time_field = doujinshi_info.find('time')
171     if time_field.has_attr('datetime'):
172         doujinshi['date'] = time_field['datetime']
173     return doujinshi
174
175
176 def old_search_parser(keyword, sorting='date', page=1):
177     logger.debug('Searching doujinshis of keyword {0}'.format(keyword))
178     response = request('get', url=constant.SEARCH_URL, params={'q': keyword, 'page': page, 'sort': sorting}).content
179
180     result = _get_title_and_id(response)
181     if not result:
182         logger.warn('Not found anything of keyword {}'.format(keyword))
183
184     return result
185
186
187 def print_doujinshi(doujinshi_list):
188     if not doujinshi_list:
189         return
190     doujinshi_list = [(i['id'], i['title']) for i in doujinshi_list]
191     headers = ['id', 'doujinshi']
192     logger.info('Search Result || Found %i doujinshis \n' % doujinshi_list.__len__() +
193                 tabulate(tabular_data=doujinshi_list, headers=headers, tablefmt='rst'))
194
195
196 def search_parser(keyword, sorting, page):
197     # keyword = '+'.join([i.strip().replace(' ', '-').lower() for i in keyword.split(',')])
198     result = []
199     if not page:
200         page = [1]
201
202     for p in page:
203         i = 0
204         logger.info('Searching doujinshis using keywords "{0}" on page {1}'.format(keyword, p))
205         while i < 3:
206             try:
207                 url = request('get', url=constant.SEARCH_URL, params={'query': keyword,
208                                                                       'page': p, 'sort': sorting}).url
209                 response = request('get', url.replace('%2B', '+')).json()
210             except Exception as e:
211                 logger.critical(str(e))
212
213             break
214
215         if 'result' not in response:
216             logger.warn('No result in response in page {}'.format(p))
217             break
218
219         for row in response['result']:
220             title = row['title']['english']
221             title = title[:85] + '..' if len(title) > 85 else title
222             result.append({'id': row['id'], 'title': title})
223
224         if not result:
225             logger.warn('No results for keywords {}'.format(keyword))
226
227     return result
228
229
230 def search_parser_all(keyword):
231     logger.debug('Searching doujinshis using keywords {0}'.format(keyword))
232
233     result = []
234
235     url = request('get', url=constant.SEARCH_URL, params={'query': keyword}).url
236     init_response = request('get', url.replace('%2B', '+')).json()
237
238     for page in range(init_response['num_pages']):
239         try:
240             url = request('get', url=constant.SEARCH_URL, params={'query': keyword, 'page': page+1}).url
241             response = request('get', url.replace('%2B', '+')).json()
242
243             print('Obtained %d / %d pages.' % (page+1, init_response['num_pages']), end='\r')
244
245         except Exception as e:
246             logger.critical(str(e))
247
248         if 'result' not in response:
249             raise Exception('No result in response')
250
251         for row in response['result']:
252             title = row['title']['english']
253             title = title[:85] + '..' if len(title) > 85 else title
254             result.append({'id': row['id'], 'title': title})
255
256         if not result:
257             logger.warn('No results for keywords {}'.format(keyword))
258
259     return result
260
261
262 def __api_suspended_doujinshi_parser(id_):
263     if not isinstance(id_, (int,)) and (isinstance(id_, (str,)) and not id_.isdigit()):
264         raise Exception('Doujinshi id({0}) is not valid'.format(id_))
265
266     id_ = int(id_)
267     logger.log(15, 'Fetching information of doujinshi id {0}'.format(id_))
268     doujinshi = dict()
269     doujinshi['id'] = id_
270     url = '{0}/{1}'.format(constant.DETAIL_URL, id_)
271     i = 0
272     while 5 > i:
273         try:
274             response = request('get', url).json()
275         except Exception as e:
276             i += 1
277             if not i < 5:
278                 logger.critical(str(e))
279                 exit(1)
280             continue
281         break
282
283     doujinshi['name'] = response['title']['english']
284     doujinshi['subtitle'] = response['title']['japanese']
285     doujinshi['img_id'] = response['media_id']
286     doujinshi['ext'] = ''.join([i['t'] for i in response['images']['pages']])
287     doujinshi['pages'] = len(response['images']['pages'])
288
289     # gain information of the doujinshi
290     needed_fields = ['character', 'artist', 'language', 'tag', 'parody', 'group', 'category']
291     for tag in response['tags']:
292         tag_type = tag['type']
293         if tag_type in needed_fields:
294             if tag_type == 'tag':
295                 if tag_type not in doujinshi:
296                     doujinshi[tag_type] = {}
297
298                 tag['name'] = tag['name'].replace(' ', '-')
299                 tag['name'] = tag['name'].lower()
300                 doujinshi[tag_type][tag['name']] = tag['id']
301             elif tag_type not in doujinshi:
302                 doujinshi[tag_type] = tag['name']
303             else:
304                 doujinshi[tag_type] += ', ' + tag['name']
305
306     return doujinshi
307
308
309 if __name__ == '__main__':
310     print(doujinshi_parser("32271"))