Skip to content

Commit

Permalink
update. --delete-cookieオプションを付与することで #14 の問題を解消できることを確認.
Browse files Browse the repository at this point in the history
  • Loading branch information
blacknon committed Jul 10, 2023
1 parent 8564a07 commit 20e2910
Show file tree
Hide file tree
Showing 9 changed files with 108 additions and 45 deletions.
1 change: 0 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1 +0,0 @@
f
19 changes: 12 additions & 7 deletions pydork/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,17 @@
# that can be found in the LICENSE file.
# =======================================================

# TODO: 日本語のヘルプメッセージを英語に書き換えて、多言語対応できるように対処する。
from .sub_commands import run_subcommand
from .engine import ENGINES

from pkg_resources import get_distribution
from datetime import datetime

import argparse
import copy
import argparse

from datetime import datetime
from pkg_resources import get_distribution

from .engine import ENGINES
from .subcommands import run_subcommand
# TODO: 日本語のヘルプメッセージを英語に書き換えて、多言語対応できるように対処する。
# TODO: returnではなくyieldに切り替えて、返り値をgeneratorにすることである程度途中状態でも状況を見れるような仕組みとする


# version (setup.pyから取得してくる)
Expand Down Expand Up @@ -138,6 +138,11 @@ def main():
"type": str,
"help": "使用するcookieファイルの格納先ディレクトリのPATH(各検索エンジンごとでcookieファイルを個別保存)"
},
{
"args": ["--delete-cookies"],
"type": bool,
"help": "検索クエリ実行ごとにCookieを削除する"
},
]

# サブコマンド `search` の引数
Expand Down
3 changes: 2 additions & 1 deletion pydork/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def out(self, text: str, is_bold=False, is_underline=False, is_reverse=False, is
class Message:
"""Message
メッセージの出力を簡易化するためのClass(未完成...).
メッセージの出力を簡易化するためのClass.
Examples:
Expand Down Expand Up @@ -208,6 +208,7 @@ def print_text(self, text, mode='message', use_header=True, separator=' ', file=
text = self.replace(text)

# case
text_color: Color = Color(Color.END)
if mode == 'message': # modeが `message` のとき
text_color = Color(Color.WHITE)

Expand Down
24 changes: 20 additions & 4 deletions pydork/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@
from string import ascii_lowercase, digits
from datetime import datetime

from .common import Color
from .common import Message
from .common import Color, Message
from .common import set_counter
from .engine_baidu import Baidu
from .engine_bing import Bing
Expand Down Expand Up @@ -208,6 +207,19 @@ def set_cookie_files(self, cookie_dir: str):
# ENGINEのself変数にセットする
self.ENGINE.COOKIE_FILE = cookie_file

# クエリ実行ごとにCookieを削除して作り直しさせるかを指定する関数
def set_cookie_files_delete(self, is_delete_cookie: bool):
"""set_cookie_files_delete
Function that specifies whether the cookie should be deleted and recreated each time the query is executed.
Args:
is_delete_cookie (bool): delete flag.
"""

# ENGINEのself変数にセットする
self.ENGINE.COOKIE_FILE_DELETE = is_delete_cookie

# 検索エンジンにわたす言語・国の設定を受け付ける
def set_lang(self, lang: str = "ja", locale: str = "JP"):
"""set_lang
Expand Down Expand Up @@ -488,6 +500,10 @@ def search(self, keyword: str, type='text', maximum=100):
if self.ENGINE.COOKIE_FILE != '':
self.ENGINE.write_cookies()

# delete cookie file
if self.ENGINE.COOKIE_FILE_DELETE:
os.remove(self.ENGINE.COOKIE_FILE)

# sessionを終了
self.ENGINE.close_session()

Expand Down Expand Up @@ -516,10 +532,10 @@ def suggest(self, keyword: str, jap=False, alph=False, num=False):
chars = ['', ' ']

# japフラグが有効な場合、キーワードに日本語を含めてサジェストを検索
chars += [' ' + chr(i) for i in range(12353, 12436)] if jap else[]
chars += [' ' + chr(i) for i in range(12353, 12436)] if jap else []

# alphフラグが有効な場合、キーワードにアルファベットを含めてサジェストを検索
chars += [' ' + char for char in ascii_lowercase] if alph else[]
chars += [' ' + char for char in ascii_lowercase] if alph else []

# numフラグが有効な場合、キーワードに数字を含めてサジェストを検索
chars += [' ' + char for char in digits] if num else []
Expand Down
3 changes: 2 additions & 1 deletion pydork/engine_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ def __init__(self):
# 初期値の作成
self.LOCK = None
self.COOKIE_FILE = ''
self.COOKIE_FILE_DELETE = False
self.SPLASH_URI = ''
self.PROXY = ''
self.USER_AGENT = ''
Expand All @@ -61,7 +62,7 @@ def __init__(self):
self.IS_DEBUG = False
self.IS_COMMAND = False
self.IS_DISABLE_HEADLESS = False
self.MESSAGE = False
self.MESSAGE: Message
self.IGNORE_SSL_VERIFY = False

# ReCaptcha画面かどうかの識別用(初期値(ブランク))
Expand Down
13 changes: 13 additions & 0 deletions pydork/engine_yandex.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,16 @@
"""engine_yandex
* Yandex(yandex.com)用の検索用Classを持つモジュール.
"""

from .common import Color
from .engine_common import CommonEngine


class Yandex(CommonEngine):
"""DuckDuckGo
DuckDuckGo用の検索エンジン用Class.
"""

def __init__(self):
None
10 changes: 10 additions & 0 deletions pydork/messages.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2023 Blacknon. All rights reserved.
# Use of this source code is governed by an MIT license
# that can be found in the LICENSE file.
# =======================================================

"""common
* commandでのhelp messageを英語・日本語対応させるためのテキストデータを持つモジュール.
"""
79 changes: 48 additions & 31 deletions pydork/subcommands.py → pydork/sub_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
# that can be found in the LICENSE file.
# =======================================================

"""subcommand
"""subcommands
* pydorkをコマンドとして動作させる際の処理を記載しているモジュール
"""

Expand All @@ -16,6 +16,8 @@
import os
import pathlib

from typing import List
from argparse import Namespace
from jinja2 import Template

from .engine import SearchEngine, ENGINES
Expand All @@ -37,31 +39,32 @@ def run_subcommand(subcommand, args):

# query及びfileがともに指定なしの場合、エラーにして返す
if args.query == "" and args.file == "" and args.template_file == "":
print("Error: クエリもしくはファイルを指定してください.")
print("Error: クエリもしくはファイルを指定してください.", file=sys.stderr)
return

# args.fileのチェック
if args.file != "":
if not os.path.exists(args.file):
print("Error: ファイルが存在しません.")
print("Error: ファイルが存在しません.", file=sys.stderr)
return

# args.fileのチェック
# args.template_fileのチェック
if args.template_file != "":
if not os.path.exists(args.template_file):
print("Error: ファイルが存在しません.")
print("Error: ファイルが存在しません.", file=sys.stderr)
return

if args.template_variable == "":
print("Error: テンプレート変数が指定されていません.")
print("Error: テンプレート変数が指定されていません.", file=sys.stderr)
return

try:
template_variable = json.loads(args.template_variable)
except Exception:
print("Error: テンプレート変数の形式がまちがっています.")
print("Error: テンプレート変数の形式がまちがっています.", file=sys.stderr)
return

# 各サブコマンドのチェック
target = None
search_mode = ''
if subcommand == 'search':
Expand All @@ -72,32 +75,18 @@ def run_subcommand(subcommand, args):
file=sys.stderr
)
return
target = search
target = run_search
search_mode = 'text'

elif subcommand == 'image':
target = search
target = run_search
search_mode = 'image'

elif subcommand == 'suggest':
target = suggest
target = run_suggest

# create query_list
query_list = list()

# append query
if args.query != "":
query_list.append(args.query)

# append query in file
if args.file != "":
# fileのfull pathを取得
file = pathlib.Path(args.file).expanduser()

# ファイルを開いて1行ずつqueryに追加する
with open(file) as f:
file_querys = [s.strip() for s in f.readlines()]
query_list.extend(file_querys)
query_list = generate_query_list(args)

# append query in template file
if args.template_file != "":
Expand Down Expand Up @@ -160,7 +149,7 @@ def run_subcommand(subcommand, args):


# SearchEngineのオプション設定用関数
def set_se_options(se, args):
def set_se_options(se: SearchEngine, args: Namespace):
"""set_se_options
Args:
Expand Down Expand Up @@ -223,11 +212,14 @@ def set_se_options(se, args):
# set cookie driver(last set)
se.set_cookie_files(args.cookies)

# set cookie file delete
se.set_cookie_files_delete(args.delete_cookies)

return se


# 検索結果を出力する
def print_search_result(result, args, message):
def print_search_result(result, args: Namespace, message: Message):
"""print_search_result
Expand Down Expand Up @@ -282,8 +274,33 @@ def print_search_result(result, args, message):
message.print_line(*data, separator=sep)


# generate
def generate_query_list(args: Namespace):
"""generate_query_list
"""
# create query_list
query_list: List[str] = list()

# append query
if args.query != "":
query_list.append(args.query)

# append query in file
if args.file != "":
# fileのfull pathを取得
file = pathlib.Path(args.file).expanduser()

# ファイルを開いて1行ずつqueryに追加する
with open(file) as f:
file_querys = [s.strip() for s in f.readlines()]
query_list.extend(file_querys)

return query_list


# 検索
def search(engine: str, query_list: list, args, thread_result: dict, cmd=False, lock=None, mode='text'):
def run_search(engine: str, query_list: list, args, thread_result: dict, cmd=False, lock=None, mode='text'):
"""search
Args:
Expand All @@ -296,7 +313,7 @@ def search(engine: str, query_list: list, args, thread_result: dict, cmd=False,
type (str, optional): 検索タイプ. `text` or `image`.
"""

# start search engine class
# start SearchEngine class
se = SearchEngine()

# Set Engine
Expand Down Expand Up @@ -356,7 +373,7 @@ def search(engine: str, query_list: list, args, thread_result: dict, cmd=False,


# サジェスト
def suggest(engine: str, query_list: list, args, thread_result: dict, cmd=False, lock=None, mode=''):
def run_suggest(engine: str, query_list: list, args: Namespace, thread_result: dict, cmd=False, lock=None, mode=''):
"""suggest
Args:
Expand All @@ -366,7 +383,7 @@ def suggest(engine: str, query_list: list, args, thread_result: dict, cmd=False,
thread_result(dict): 結果を1箇所に集約するためのresult dict. json出力するときのみ使用.
cmd (bool, optional): commandで実行しているか否か. Defaults to False.
lock (threading.Lock): threadingのマルチスレッドで使用するLock.現在は未使用. Defaults to None.
mode (str, optional): マルチスレッドでsearchとある程度共用で使えるようにするための引数. 利用していない. Defaults to ''.
mode (str, optional): マルチスレッドでsearchある程度共用で使えるようにするための引数. 利用していない. Defaults to ''.
"""

# start search engine class
Expand Down
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ def get_completefile_install_location(shell):
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'License :: OSI Approved :: MIT License',
],
data_files=get_data_files(),
Expand Down

0 comments on commit 20e2910

Please sign in to comment.