]> git.lizzy.rs Git - nhentai.git/blob - nhentai/parser.py
Merge pull request #21 from mentaterasmus/master
[nhentai.git] / nhentai / parser.py
1 # coding: utf-8
2 from __future__ import unicode_literals, print_function
3
4 import os
5 import re
6 import threadpool
7 import requests
8 from bs4 import BeautifulSoup
9 from tabulate import tabulate
10
11 import nhentai.constant as constant
12 from nhentai.logger import logger
13
14
15 def request(method, url, **kwargs):
16     if not hasattr(requests, method):
17         raise AttributeError('\'requests\' object has no attribute \'{0}\''.format(method))
18
19     return requests.__dict__[method](url, proxies=constant.PROXY, verify=False, **kwargs)
20
21
22 def login_parser(username, password):
23     s = requests.Session()
24     s.proxies = constant.PROXY
25     s.verify = False
26     s.headers.update({'Referer': constant.LOGIN_URL})
27
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'})
32
33     if not csrf_token_elem:
34         raise Exception('Cannot find csrf token to login')
35     csrf_token = csrf_token_elem.attrs['value']
36
37     login_dict = {
38         'csrfmiddlewaretoken': csrf_token,
39         'username_or_email': username,
40         'password': password,
41     }
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')
45         exit(1)
46
47     html = BeautifulSoup(s.get(constant.FAV_URL).content, 'html.parser').encode("ascii")
48     count = html.find('span', attrs={'class': 'count'})
49     if not count:
50         logger.error('Cannot get count of your favorites, maybe login failed.')
51
52     count = int(count.text.strip('(').strip(')'))
53     pages = count / 25
54     pages += 1 if count % (25 * pages) else 0
55     logger.info('Your have %d favorites in %d pages.' % (count, pages))
56
57     if os.getenv('DEBUG'):
58         pages = 1
59
60     ret = []
61     doujinshi_id = re.compile('data-id="([\d]+)"')
62
63     def _callback(request, result):
64         ret.append(result)
65
66     thread_pool = threadpool.ThreadPool(5)
67
68     for page in range(1, pages+1):
69         try:
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_]
75             thread_pool.wait()
76         except Exception as e:
77             logger.error('Error: %s, continue', str(e))
78
79     return ret
80
81
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_))
85
86     id_ = int(id_)
87     logger.log(15, 'Fetching doujinshi information of id {0}'.format(id_))
88     doujinshi = dict()
89     doujinshi['id'] = id_
90     url = '{0}/{1}'.format(constant.DETAIL_URL, id_)
91
92     try:
93         response = request('get', url).json()
94     except Exception as e:
95         logger.critical(str(e))
96         exit(1)
97
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'])
103
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']
111             else:
112                 doujinshi[tag_type] += tag['name']
113
114     return doujinshi
115
116
117 def search_parser(keyword, page):
118     logger.debug('Searching doujinshis of keyword {0}'.format(keyword))
119     result = []
120     try:
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:
125         logger.critical(e)
126         logger.warn('If you are in China, please configure the proxy to fu*k GFW.')
127         exit(1)
128
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})
133
134     if not result:
135         logger.warn('Not found anything of keyword {}'.format(keyword))
136
137     return result
138
139
140 def print_doujinshi(doujinshi_list):
141     if not doujinshi_list:
142         return
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'))
147
148
149 if __name__ == '__main__':
150     print(doujinshi_parser("32271"))