]> git.lizzy.rs Git - nhentai.git/blobdiff - nhentai/parser.py
Merge pull request #96 from symant233/dev
[nhentai.git] / nhentai / parser.py
index d01a7e1baa7a35e98d4a61e9931ba0a1a411323b..3c01af164e1733de6e5b2538b44c6c3f28c1f40d 100644 (file)
-# coding: utf-8\r
-from __future__ import unicode_literals, print_function\r
-\r
-import os\r
-import re\r
-import threadpool\r
-import requests\r
-from bs4 import BeautifulSoup\r
-from tabulate import tabulate\r
-\r
-import nhentai.constant as constant\r
-from nhentai.logger import logger\r
-\r
-\r
-def request(method, url, **kwargs):\r
-    if not hasattr(requests, method):\r
-        raise AttributeError('\'requests\' object has no attribute \'{0}\''.format(method))\r
-\r
-    return requests.__dict__[method](url, proxies=constant.PROXY, verify=False, **kwargs)\r
-\r
-\r
-def login_parser(username, password):\r
-    s = requests.Session()\r
-    s.proxies = constant.PROXY\r
-    s.verify = False\r
-    s.headers.update({'Referer': constant.LOGIN_URL})\r
-\r
-    s.get(constant.LOGIN_URL)\r
-    content = s.get(constant.LOGIN_URL).content\r
-    html = BeautifulSoup(content, 'html.parser')\r
-    csrf_token_elem = html.find('input', attrs={'name': 'csrfmiddlewaretoken'})\r
-\r
-    if not csrf_token_elem:\r
-        raise Exception('Cannot find csrf token to login')\r
-    csrf_token = csrf_token_elem.attrs['value']\r
-\r
-    login_dict = {\r
-        'csrfmiddlewaretoken': csrf_token,\r
-        'username_or_email': username,\r
-        'password': password,\r
-    }\r
-    resp = s.post(constant.LOGIN_URL, data=login_dict)\r
-    if 'Invalid username (or email) or password' in resp.text:\r
-        logger.error('Login failed, please check your username and password')\r
-        exit(1)\r
-\r
-    html = BeautifulSoup(s.get(constant.FAV_URL).content, 'html.parser')\r
-    count = html.find('span', attrs={'class': 'count'})\r
-    if not count:\r
-        logger.error('Cannot get count of your favorites, maybe login failed.')\r
-\r
-    count = int(count.text.strip('(').strip(')'))\r
-    if count == 0:\r
-        logger.warning('No favorites found')\r
-        return []\r
-    pages = int(count / 25)\r
-\r
-    if pages:\r
-        pages += 1 if count % (25 * pages) else 0\r
-    else:\r
-        pages = 1\r
-\r
-    logger.info('Your have %d favorites in %d pages.' % (count, pages))\r
-\r
-    if os.getenv('DEBUG'):\r
-        pages = 1\r
-\r
-    ret = []\r
-    doujinshi_id = re.compile('data-id="([\d]+)"')\r
-\r
-    def _callback(request, result):\r
-        ret.append(result)\r
-\r
-    thread_pool = threadpool.ThreadPool(5)\r
-\r
-    for page in range(1, pages+1):\r
-        try:\r
-            logger.info('Getting doujinshi id of page %d' % page)\r
-            resp = s.get(constant.FAV_URL + '?page=%d' % page).text\r
-            ids = doujinshi_id.findall(resp)\r
-            requests_ = threadpool.makeRequests(doujinshi_parser, ids, _callback)\r
-            [thread_pool.putRequest(req) for req in requests_]\r
-            thread_pool.wait()\r
-        except Exception as e:\r
-            logger.error('Error: %s, continue', str(e))\r
-\r
-    return ret\r
-\r
-\r
-def doujinshi_parser(id_):\r
-    if not isinstance(id_, (int,)) and (isinstance(id_, (str,)) and not id_.isdigit()):\r
-        raise Exception('Doujinshi id({0}) is not valid'.format(id_))\r
-\r
-    id_ = int(id_)\r
-    logger.log(15, 'Fetching doujinshi information of id {0}'.format(id_))\r
-    doujinshi = dict()\r
-    doujinshi['id'] = id_\r
-    url = '{0}/{1}'.format(constant.DETAIL_URL, id_)\r
-\r
-    try:\r
-        response = request('get', url).json()\r
-    except Exception as e:\r
-        logger.critical(str(e))\r
-        exit(1)\r
-\r
-    doujinshi['name'] = response['title']['english']\r
-    doujinshi['subtitle'] = response['title']['japanese']\r
-    doujinshi['img_id'] = response['media_id']\r
-    doujinshi['ext'] = ''.join(map(lambda s: s['t'], response['images']['pages']))\r
-    doujinshi['pages'] = len(response['images']['pages'])\r
-\r
-    # gain information of the doujinshi\r
-    needed_fields = ['character', 'artist', 'language']\r
-    for tag in response['tags']:\r
-        tag_type = tag['type']\r
-        if tag_type in needed_fields:\r
-            if tag_type not in doujinshi:\r
-                doujinshi[tag_type] = tag['name']\r
-            else:\r
-                doujinshi[tag_type] += tag['name']\r
-\r
-    return doujinshi\r
-\r
-\r
-def search_parser(keyword, page):\r
-    logger.debug('Searching doujinshis of keyword {0}'.format(keyword))\r
-    result = []\r
-    try:\r
-        response = request('get', url=constant.SEARCH_URL, params={'query': keyword, 'page': page}).json()\r
-        if 'result' not in response:\r
-            raise Exception('No result in response')\r
-    except requests.ConnectionError as e:\r
-        logger.critical(e)\r
-        logger.warn('If you are in China, please configure the proxy to fu*k GFW.')\r
-        exit(1)\r
-\r
-    for row in response['result']:\r
-        title = row['title']['english']\r
-        title = title[:85] + '..' if len(title) > 85 else title\r
-        result.append({'id': row['id'], 'title': title})\r
-\r
-    if not result:\r
-        logger.warn('Not found anything of keyword {}'.format(keyword))\r
-\r
-    return result\r
-\r
-\r
-def print_doujinshi(doujinshi_list):\r
-    if not doujinshi_list:\r
-        return\r
-    doujinshi_list = [(i['id'], i['title']) for i in doujinshi_list]\r
-    headers = ['id', 'doujinshi']\r
-    logger.info('Search Result\n' +\r
-                tabulate(tabular_data=doujinshi_list, headers=headers, tablefmt='rst'))\r
-\r
-\r
-if __name__ == '__main__':\r
-    print(doujinshi_parser("32271"))\r
+# coding: utf-8
+from __future__ import unicode_literals, print_function
+
+import os
+import re
+import threadpool
+import requests
+import time
+from bs4 import BeautifulSoup
+from tabulate import tabulate
+
+import nhentai.constant as constant
+from nhentai.utils import request
+from nhentai.logger import logger
+
+
+def _get_csrf_token(content):
+    html = BeautifulSoup(content, 'html.parser')
+    csrf_token_elem = html.find('input', attrs={'name': 'csrfmiddlewaretoken'})
+    if not csrf_token_elem:
+        raise Exception('Cannot find csrf token to login')
+    return csrf_token_elem.attrs['value']
+
+
+def login(username, password):
+    logger.warning('This feature is deprecated, please use --cookie to set your cookie.')
+    csrf_token = _get_csrf_token(request('get', url=constant.LOGIN_URL).text)
+    if os.getenv('DEBUG'):
+        logger.info('Getting CSRF token ...')
+
+    if os.getenv('DEBUG'):
+        logger.info('CSRF token is {}'.format(csrf_token))
+
+    login_dict = {
+        'csrfmiddlewaretoken': csrf_token,
+        'username_or_email': username,
+        'password': password,
+    }
+    resp = request('post', url=constant.LOGIN_URL, data=login_dict)
+
+    if 'You\'re loading pages way too quickly.' in resp.text or 'Really, slow down' in resp.text:
+        csrf_token = _get_csrf_token(resp.text)
+        resp = request('post', url=resp.url, data={'csrfmiddlewaretoken': csrf_token, 'next': '/'})
+
+    if 'Invalid username/email or password' in resp.text:
+        logger.error('Login failed, please check your username and password')
+        exit(1)
+
+    if 'You\'re loading pages way too quickly.' in resp.text or 'Really, slow down' in resp.text:
+        logger.error('Using nhentai --cookie \'YOUR_COOKIE_HERE\' to save your Cookie.')
+        exit(2)
+
+
+def _get_title_and_id(response):
+    result = []
+    html = BeautifulSoup(response, 'html.parser')
+    doujinshi_search_result = html.find_all('div', attrs={'class': 'gallery'})
+    for doujinshi in doujinshi_search_result:
+        doujinshi_container = doujinshi.find('div', attrs={'class': 'caption'})
+        title = doujinshi_container.text.strip()
+        title = title if len(title) < 85 else title[:82] + '...'
+        id_ = re.search('/g/(\d+)/', doujinshi.a['href']).group(1)
+        result.append({'id': id_, 'title': title})
+
+    return result
+
+
+def favorites_parser():
+    result = []
+    html = BeautifulSoup(request('get', constant.FAV_URL).content, 'html.parser')
+    count = html.find('span', attrs={'class': 'count'})
+    if not count:
+        logger.error("Can't get your number of favorited doujins. Did the login failed?")
+        return []
+
+    count = int(count.text.strip('(').strip(')').replace(',', ''))
+    if count == 0:
+        logger.warning('No favorites found')
+        return []
+    pages = int(count / 25)
+
+    if pages:
+        pages += 1 if count % (25 * pages) else 0
+    else:
+        pages = 1
+
+    logger.info('You have %d favorites in %d pages.' % (count, pages))
+
+    if os.getenv('DEBUG'):
+        pages = 1
+
+    for page in range(1, pages + 1):
+        try:
+            logger.info('Getting doujinshi ids of page %d' % page)
+            resp = request('get', constant.FAV_URL + '?page=%d' % page).content
+
+            result.extend(_get_title_and_id(resp))
+        except Exception as e:
+            logger.error('Error: %s, continue', str(e))
+
+    return result
+
+
+def doujinshi_parser(id_):
+    if not isinstance(id_, (int,)) and (isinstance(id_, (str,)) and not id_.isdigit()):
+        raise Exception('Doujinshi id({0}) is not valid'.format(id_))
+
+    id_ = int(id_)
+    logger.log(15, 'Fetching doujinshi information of id {0}'.format(id_))
+    doujinshi = dict()
+    doujinshi['id'] = id_
+    url = '{0}/{1}/'.format(constant.DETAIL_URL, id_)
+
+    try:
+        response = request('get', url)
+        if response.status_code in (200, ):
+            response = response.content
+        else:
+            logger.debug('Slow down and retry ({}) ...'.format(id_))
+            time.sleep(1)
+            return doujinshi_parser(str(id_))
+
+    except Exception as e:
+        logger.warn('Error: {}, ignored'.format(str(e)))
+        return None
+
+    html = BeautifulSoup(response, 'html.parser')
+    doujinshi_info = html.find('div', attrs={'id': 'info'})
+
+    title = doujinshi_info.find('h1').text
+    subtitle = doujinshi_info.find('h2')
+
+    doujinshi['name'] = title
+    doujinshi['subtitle'] = subtitle.text if subtitle else ''
+
+    doujinshi_cover = html.find('div', attrs={'id': 'cover'})
+    img_id = re.search('/galleries/([\d]+)/cover\.(jpg|png|gif)$', doujinshi_cover.a.img.attrs['data-src'])
+
+    ext = []
+    for i in html.find_all('div', attrs={'class': 'thumb-container'}):
+        _, ext_name = os.path.basename(i.img.attrs['data-src']).rsplit('.', 1)
+        ext.append(ext_name)
+
+    if not img_id:
+        logger.critical('Tried yo get image id failed')
+        exit(1)
+
+    doujinshi['img_id'] = img_id.group(1)
+    doujinshi['ext'] = ext
+
+    pages = 0
+    for _ in doujinshi_info.find_all('div', class_=''):
+        pages = re.search('([\d]+) pages', _.text)
+        if pages:
+            pages = pages.group(1)
+            break
+    doujinshi['pages'] = int(pages)
+
+    # gain information of the doujinshi
+    information_fields = doujinshi_info.find_all('div', attrs={'class': 'field-name'})
+    needed_fields = ['Characters', 'Artists', 'Languages', 'Tags', 'Parodies', 'Groups', 'Categories']
+    for field in information_fields:
+        field_name = field.contents[0].strip().strip(':')
+        if field_name in needed_fields:
+            data = [sub_field.contents[0].strip() for sub_field in
+                    field.find_all('a', attrs={'class': 'tag'})]
+            doujinshi[field_name.lower()] = ', '.join(data)
+
+    time_field = doujinshi_info.find('time')
+    if time_field.has_attr('datetime'):
+        doujinshi['date'] = time_field['datetime']
+    return doujinshi
+
+
+def search_parser(keyword, sorting='date', page=1):
+    logger.debug('Searching doujinshis of keyword {0}'.format(keyword))
+    response = request('get', url=constant.SEARCH_URL, params={'q': keyword, 'page': page, 'sort': sorting}).content
+
+    result = _get_title_and_id(response)
+    if not result:
+        logger.warn('Not found anything of keyword {}'.format(keyword))
+
+    return result
+
+
+def print_doujinshi(doujinshi_list):
+    if not doujinshi_list:
+        return
+    doujinshi_list = [(i['id'], i['title']) for i in doujinshi_list]
+    headers = ['id', 'doujinshi']
+    logger.info('Search Result\n' +
+                tabulate(tabular_data=doujinshi_list, headers=headers, tablefmt='rst'))
+
+
+def tag_parser(tag_name, sorting='date', max_page=1, index=0):
+    result = []
+    tag_name = tag_name.lower()
+    if ',' in tag_name:
+        tag_name = [i.strip().replace(' ', '-') for i in tag_name.split(',')]
+    else:
+        tag_name = tag_name.strip().replace(' ', '-')
+    if sorting == 'date':
+        sorting = ''
+
+    for p in range(1, max_page + 1):
+        if isinstance(tag_name, str):
+            logger.debug('Fetching page {0} for doujinshi with tag \'{1}\''.format(p, tag_name))
+            response = request('get', url='%s/%s/%s?page=%d' % (constant.TAG_URL[index], tag_name, sorting, p)).content
+            result += _get_title_and_id(response)
+        else:
+            for i in tag_name:
+                logger.debug('Fetching page {0} for doujinshi with tag \'{1}\''.format(p, i))
+                response = request('get',
+                                   url='%s/%s/%s?page=%d' % (constant.TAG_URL[index], i, sorting, p)).content
+                result += _get_title_and_id(response)
+
+        if not result:
+            logger.error('Cannot find doujinshi id of tag \'{0}\''.format(tag_name))
+            return
+
+    if not result:
+        logger.warn('No results for tag \'{}\''.format(tag_name))
+
+    return result
+
+
+def __api_suspended_search_parser(keyword, sorting, page):
+    logger.debug('Searching doujinshis using keywords {0}'.format(keyword))
+    result = []
+    i = 0
+    while i < 5:
+        try:
+            response = request('get', url=constant.SEARCH_URL, params={'query': keyword, 'page': page, 'sort': sorting}).json()
+        except Exception as e:
+            i += 1
+            if not i < 5:
+                logger.critical(str(e))
+                logger.warn('If you are in China, please configure the proxy to fu*k GFW.')
+                exit(1)
+            continue
+        break
+
+    if 'result' not in response:
+        raise Exception('No result in response')
+
+    for row in response['result']:
+        title = row['title']['english']
+        title = title[:85] + '..' if len(title) > 85 else title
+        result.append({'id': row['id'], 'title': title})
+
+    if not result:
+        logger.warn('No results for keywords {}'.format(keyword))
+
+    return result
+
+
+def __api_suspended_tag_parser(tag_id, sorting, max_page=1):
+    logger.info('Searching for doujinshi with tag id {0}'.format(tag_id))
+    result = []
+    response = request('get', url=constant.TAG_API_URL, params={'sort': sorting, 'tag_id': tag_id}).json()
+    page = max_page if max_page <= response['num_pages'] else int(response['num_pages'])
+
+    for i in range(1, page + 1):
+        logger.info('Getting page {} ...'.format(i))
+
+        if page != 1:
+            response = request('get', url=constant.TAG_API_URL,
+                               params={'sort': sorting, 'tag_id': tag_id}).json()
+    for row in response['result']:
+        title = row['title']['english']
+        title = title[:85] + '..' if len(title) > 85 else title
+        result.append({'id': row['id'], 'title': title})
+
+    if not result:
+        logger.warn('No results for tag id {}'.format(tag_id))
+
+    return result
+
+
+def __api_suspended_doujinshi_parser(id_):
+    if not isinstance(id_, (int,)) and (isinstance(id_, (str,)) and not id_.isdigit()):
+        raise Exception('Doujinshi id({0}) is not valid'.format(id_))
+
+    id_ = int(id_)
+    logger.log(15, 'Fetching information of doujinshi id {0}'.format(id_))
+    doujinshi = dict()
+    doujinshi['id'] = id_
+    url = '{0}/{1}'.format(constant.DETAIL_URL, id_)
+    i = 0
+    while 5 > i:
+        try:
+            response = request('get', url).json()
+        except Exception as e:
+            i += 1
+            if not i < 5:
+                logger.critical(str(e))
+                exit(1)
+            continue
+        break
+
+    doujinshi['name'] = response['title']['english']
+    doujinshi['subtitle'] = response['title']['japanese']
+    doujinshi['img_id'] = response['media_id']
+    doujinshi['ext'] = ''.join([i['t'] for i in response['images']['pages']])
+    doujinshi['pages'] = len(response['images']['pages'])
+
+    # gain information of the doujinshi
+    needed_fields = ['character', 'artist', 'language', 'tag', 'parody', 'group', 'category']
+    for tag in response['tags']:
+        tag_type = tag['type']
+        if tag_type in needed_fields:
+            if tag_type == 'tag':
+                if tag_type not in doujinshi:
+                    doujinshi[tag_type] = {}
+
+                tag['name'] = tag['name'].replace(' ', '-')
+                tag['name'] = tag['name'].lower()
+                doujinshi[tag_type][tag['name']] = tag['id']
+            elif tag_type not in doujinshi:
+                doujinshi[tag_type] = tag['name']
+            else:
+                doujinshi[tag_type] += ', ' + tag['name']
+
+    return doujinshi
+
+
+if __name__ == '__main__':
+    print(doujinshi_parser("32271"))