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.logger import logger
15 def request(method, url, **kwargs):
16 if not hasattr(requests, method):
17 raise AttributeError('\'requests\' object has no attribute \'{0}\''.format(method))
19 return requests.__dict__[method](url, proxies=constant.PROXY, verify=False, **kwargs)
22 def login_parser(username, password):
23 s = requests.Session()
24 s.proxies = constant.PROXY
26 s.headers.update({'Referer': constant.LOGIN_URL})
28 s.get(constant.LOGIN_URL)
29 content = s.get(constant.LOGIN_URL).content
30 html = BeautifulSoup(content, 'html.parser').encode("ascii")
31 csrf_token_elem = html.find('input', attrs={'name': 'csrfmiddlewaretoken'})
33 if not csrf_token_elem:
34 raise Exception('Cannot find csrf token to login')
35 csrf_token = csrf_token_elem.attrs['value']
38 'csrfmiddlewaretoken': csrf_token,
39 'username_or_email': username,
42 resp = s.post(constant.LOGIN_URL, data=login_dict)
43 if 'Invalid username (or email) or password' in resp.text:
44 logger.error('Login failed, please check your username and password')
47 html = BeautifulSoup(s.get(constant.FAV_URL).content, 'html.parser').encode("ascii")
48 count = html.find('span', attrs={'class': 'count'})
50 logger.error('Cannot get count of your favorites, maybe login failed.')
52 count = int(count.text.strip('(').strip(')'))
54 pages += 1 if count % (25 * pages) else 0
55 logger.info('Your have %d favorites in %d pages.' % (count, pages))
57 if os.getenv('DEBUG'):
61 doujinshi_id = re.compile('data-id="([\d]+)"')
63 def _callback(request, result):
66 thread_pool = threadpool.ThreadPool(5)
68 for page in range(1, pages+1):
70 logger.info('Getting doujinshi id of page %d' % page)
71 resp = s.get(constant.FAV_URL + '?page=%d' % page).content
72 ids = doujinshi_id.findall(resp)
73 requests_ = threadpool.makeRequests(doujinshi_parser, ids, _callback)
74 [thread_pool.putRequest(req) for req in requests_]
76 except Exception as e:
77 logger.error('Error: %s, continue', str(e))
82 def doujinshi_parser(id_):
83 if not isinstance(id_, (int,)) and (isinstance(id_, (str,)) and not id_.isdigit()):
84 raise Exception('Doujinshi id({0}) is not valid'.format(id_))
87 logger.log(15, 'Fetching doujinshi information of id {0}'.format(id_))
90 url = '{0}/{1}'.format(constant.DETAIL_URL, id_)
93 response = request('get', url).json()
94 except Exception as e:
95 logger.critical(str(e))
98 doujinshi['name'] = str(response['title']['english'].encode('utf-8'))[2:]
99 doujinshi['subtitle'] = response['title']['japanese']
100 doujinshi['img_id'] = response['media_id']
101 doujinshi['ext'] = ''.join(map(lambda s: s['t'], response['images']['pages']))
102 doujinshi['pages'] = len(response['images']['pages'])
104 # gain information of the doujinshi
105 needed_fields = ['character', 'artist', 'language']
106 for tag in response['tags']:
107 tag_type = tag['type']
108 if tag_type in needed_fields:
109 if tag_type not in doujinshi:
110 doujinshi[tag_type] = tag['name']
112 doujinshi[tag_type] += tag['name']
117 def search_parser(keyword, page):
118 logger.debug('Searching doujinshis of keyword {0}'.format(keyword))
121 response = request('get', url=constant.SEARCH_URL, params={'query': keyword, 'page': page}).json()
122 if 'result' not in response:
123 raise Exception('No result in response')
124 except requests.ConnectionError as e:
126 logger.warn('If you are in China, please configure the proxy to fu*k GFW.')
129 for row in response['result']:
130 title = row['title']['english']
131 title = title[:85] + '..' if len(title) > 85 else title
132 result.append({'id': row['id'], 'title': title})
135 logger.warn('Not found anything of keyword {}'.format(keyword))
140 def print_doujinshi(doujinshi_list):
141 if not doujinshi_list:
143 doujinshi_list = [(i['id'], i['title']) for i in doujinshi_list]
144 headers = ['id', 'doujinshi']
145 logger.info('Search Result\n' +
146 tabulate(tabular_data=doujinshi_list, headers=headers, tablefmt='rst'))
149 if __name__ == '__main__':
150 print(doujinshi_parser("32271"))