Skip to content

Commit

Permalink
Fix for issue #159 (#162)
Browse files Browse the repository at this point in the history
* Fixed the imports of the files in /socli directory to work for both python2.7 and python3

* Fixed the imports by adding the file directory in sys.path for the modules in /socli folder

* Fixed the imports of the files in /socli directory by adding the file directory in sys.path. Now it works for both versions python2 and python3

* Fixed the imports of the files in /socli directory by adding the file…

* Deleted the .vscode directory
  • Loading branch information
anirudnits authored and gautamkrishnar committed Aug 12, 2019
1 parent b785e56 commit 79f128b
Show file tree
Hide file tree
Showing 8 changed files with 94 additions and 63 deletions.
1 change: 1 addition & 0 deletions =27.3
@@ -0,0 +1 @@
Requirement already satisfied: setuptools in /usr/lib/python2.7/dist-packages (20.7.0)
7 changes: 6 additions & 1 deletion socli/__main__.py
@@ -1,4 +1,9 @@
from socli.socli import main
import sys
import os

BASE_DIR = os.path.dirname(os.path.realpath(__file__))
sys.path = [BASE_DIR] + sys.path
from socli import main

if __name__ == '__main__':
main()
3 changes: 2 additions & 1 deletion socli/parser.py
Expand Up @@ -3,7 +3,8 @@
"""
import argparse
import textwrap

import sys
import os

def parse_arguments(command):
"""
Expand Down
9 changes: 8 additions & 1 deletion socli/printer.py
Expand Up @@ -7,11 +7,18 @@
import sys
import textwrap
import urllib
import os

import colorama
import requests

from socli import search as search, tui as tui

BASE_DIR = os.path.dirname(os.path.realpath(__file__))
sys.path = [BASE_DIR] + sys.path


import search as search
import tui as tui

DEBUG = False

Expand Down
105 changes: 54 additions & 51 deletions socli/search.py
Expand Up @@ -11,8 +11,11 @@
import requests
import urwid

import socli.printer
import socli.tui
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
sys.path = [BASE_DIR] + sys.path

import printer as printer
import tui as tui

uas = [] # User agent list
header = {} # Request header
Expand Down Expand Up @@ -42,7 +45,7 @@ def get_questions_for_query(query, count=10):
try:
soup.find_all("div", class_="question-summary")[0] # For explicitly raising exception
except IndexError:
socli.printer.print_warning("No results found...")
printer.print_warning("No results found...")
sys.exit(0)
tmp = (soup.find_all("div", class_="question-summary"))
tmp1 = (soup.find_all("div", class_="excerpt"))
Expand Down Expand Up @@ -76,7 +79,7 @@ def get_questions_for_query_google(query, count=10):
try:
soup.find_all("div", class_="g")[0] # For explicitly raising exception
except IndexError:
socli.printer.print_warning("No results found...")
printer.print_warning("No results found...")
sys.exit(0)
for result in soup.find_all("div", class_="g"):
if i == count:
Expand All @@ -102,7 +105,7 @@ def get_questions_for_query_google(query, count=10):

# Check if there are any valid question posts
if not questions:
socli.printer.print_warning("No results found...")
printer.print_warning("No results found...")
sys.exit(0)
return questions

Expand Down Expand Up @@ -175,44 +178,44 @@ def socli_interactive_windows(query):
tmp1 = (soup.find_all("div", class_="excerpt"))
i = 0
question_local_url = []
print(socli.printer.bold("\nSelect a question below:\n"))
print(printer.bold("\nSelect a question below:\n"))
while i < len(tmp):
if i == 10: break # limiting results
question_text = ' '.join((tmp[i].a.get_text()).split())
question_text = question_text.replace("Q: ", "")
question_desc = (tmp1[i].get_text()).replace("'\r\n", "")
question_desc = ' '.join(question_desc.split())
socli.printer.print_warning(str(i + 1) + ". " + socli.printer.display_str(question_text))
printer.print_warning(str(i + 1) + ". " + printer.display_str(question_text))
question_local_url.append(tmp[i].a.get("href"))
print(" " + socli.printer.display_str(question_desc) + "\n")
print(" " + printer.display_str(question_desc) + "\n")
i = i + 1
try:
op = int(socli.printer.inputs("\nType the option no to continue or any other key to exit:"))
op = int(printer.inputs("\nType the option no to continue or any other key to exit:"))
while 1:
if (op > 0) and (op <= i):
socli.printer.display_results(so_url + question_local_url[op - 1])
printer.display_results(so_url + question_local_url[op - 1])
cnt = 1 # this is because the 1st post is the question itself
while 1:
global tmpsoup
qna = socli.printer.inputs(
"Type " + socli.printer.bold("o") + " to open in browser, " + socli.printer.bold("n") + " to next answer, " + socli.printer.bold(
#global tmpsoup
qna = printer.inputs(
"Type " + printer.bold("o") + " to open in browser, " + printer.bold("n") + " to next answer, " + printer.bold(
"b") + " for previous answer or any other key to exit:")
if qna in ["n", "N"]:
try:
answer = (tmpsoup.find_all("div", class_="post-text")[cnt + 1].get_text())
socli.printer.print_green("\n\nAnswer:\n")
answer = (tmp.find_all("div", class_="post-text")[cnt + 1].get_text())
printer.print_green("\n\nAnswer:\n")
print("-------\n" + answer + "\n-------\n")
cnt = cnt + 1
except IndexError as e:
socli.printer.print_warning(" No more answers found for this question. Exiting...")
printer.print_warning(" No more answers found for this question. Exiting...")
sys.exit(0)
continue
elif qna in ["b", "B"]:
if cnt == 1:
socli.printer.print_warning(" You cant go further back. You are on the first answer!")
printer.print_warning(" You cant go further back. You are on the first answer!")
continue
answer = (tmpsoup.find_all("div", class_="post-text")[cnt - 1].get_text())
socli.printer.print_green("\n\nAnswer:\n")
answer = (tmp.find_all("div", class_="post-text")[cnt - 1].get_text())
printer.print_green("\n\nAnswer:\n")
print("-------\n" + answer + "\n-------\n")
cnt = cnt - 1
continue
Expand All @@ -222,28 +225,28 @@ def socli_interactive_windows(query):
browser = webbrowser.get('safari')
else:
browser = webbrowser.get()
socli.printer.print_warning("Opening in your browser...")
printer.print_warning("Opening in your browser...")
browser.open(so_url + question_local_url[op - 1])
else:
break
sys.exit(0)
else:
op = int(input("\n\nWrong option. select the option no to continue:"))
except Exception as e:
socli.printer.showerror(e)
socli.printer.print_warning("\n Exiting...")
printer.showerror(e)
printer.print_warning("\n Exiting...")
sys.exit(0)
except IndexError:
socli.printer.print_warning("No results found...")
printer.print_warning("No results found...")
sys.exit(0)

except UnicodeEncodeError:
socli.printer.print_warning("\n\nEncoding error: Use \"chcp 65001\" command before using socli...")
printer.print_warning("\n\nEncoding error: Use \"chcp 65001\" command before using socli...")
sys.exit(0)
except requests.exceptions.ConnectionError:
socli.printer.print_fail("Please check your internet connectivity...")
printer.print_fail("Please check your internet connectivity...")
except Exception as e:
socli.printer.showerror(e)
printer.showerror(e)
sys.exit(0)


Expand All @@ -269,14 +272,14 @@ def __init__(self, questions):
self.questions = questions
self.cachedQuestions = [None for _ in range(10)]
widgets = [self.display_text(i, q) for i, q in enumerate(questions)]
self.questions_box = socli.tui.ScrollableTextBox(widgets)
self.header = socli.tui.UnicodeText(('less-important', 'Select a question below:\n'))
self.questions_box = tui.ScrollableTextBox(widgets)
self.header = tui.UnicodeText(('less-important', 'Select a question below:\n'))
self.footerText = '0-' + str(len(self.questions) - 1) + ': select a question, any other key: exit.'
self.errorText = socli.tui.UnicodeText.to_unicode('Question numbers range from 0-' +
self.errorText = tui.UnicodeText.to_unicode('Question numbers range from 0-' +
str(len(self.questions) - 1) +
". Please select a valid question number.")
self.footer = socli.tui.UnicodeText(self.footerText)
self.footerText = socli.tui.UnicodeText.to_unicode(self.footerText)
self.footer = tui.UnicodeText(self.footerText)
self.footerText = tui.UnicodeText.to_unicode(self.footerText)
frame = urwid.Frame(header=self.header,
body=urwid.Filler(self.questions_box, height=('relative', 100), valign='top'),
footer=self.footer)
Expand All @@ -301,34 +304,34 @@ def keypress(self, size, key):

def select_question(self, url, index):
if self.cachedQuestions[index] is not None:
socli.tui.question_post = self.cachedQuestions[index]
socli.tui.MAIN_LOOP.widget = socli.tui.question_post
tui.question_post = self.cachedQuestions[index]
tui.MAIN_LOOP.widget = tui.question_post
else:
if not google_search:
url = so_url + url
question_title, question_desc, question_stats, answers = get_question_stats_and_answer(url)
socli.tui.question_post = socli.tui.QuestionPage((answers, question_title, question_desc, question_stats, url))
self.cachedQuestions[index] = socli.tui.question_post
socli.tui.MAIN_LOOP.widget = socli.tui.question_post
tui.question_post = tui.QuestionPage((answers, question_title, question_desc, question_stats, url))
self.cachedQuestions[index] = tui.question_post
tui.MAIN_LOOP.widget = tui.question_post

socli.tui.display_header = socli.tui.Header()
tui.display_header = tui.Header()

try:
if google_search:
questions = get_questions_for_query_google(query)
else:
questions = get_questions_for_query(query)
question_page = SelectQuestionPage(questions)
socli.tui.MAIN_LOOP = socli.tui.EditedMainLoop(question_page, socli.printer.palette)
socli.tui.MAIN_LOOP.run()
tui.MAIN_LOOP = tui.EditedMainLoop(question_page, printer.palette)
tui.MAIN_LOOP.run()

except UnicodeEncodeError:
socli.printer.print_warning("\n\nEncoding error: Use \"chcp 65001\" command before using socli...")
printer.print_warning("\n\nEncoding error: Use \"chcp 65001\" command before using socli...")
sys.exit(0)
except requests.exceptions.ConnectionError:
socli.printer.print_fail("Please check your internet connectivity...")
printer.print_fail("Please check your internet connectivity...")
except Exception as e:
socli.printer.showerror(e)
printer.showerror(e)
print("exiting...")
sys.exit(0)

Expand All @@ -341,10 +344,10 @@ def socli_manual_search(query, rn):
:return:
"""
if rn < 1:
socli.printer.print_warning(
printer.print_warning(
"Count starts from 1. Use: \"socli -i 2 -q python for loop\" for the 2nd result for the query")
sys.exit(0)
query = socli.printer.urlencode(query)
query = printer.urlencode(query)
try:
random_headers()
# Set count = 99 so you can choose question numbers higher than 10
Expand All @@ -357,18 +360,18 @@ def socli_manual_search(query, rn):
else:
questions = get_questions_for_query(query, count)
res_url = so_url + questions[rn - 1][2]
socli.printer.display_results(res_url)
printer.display_results(res_url)
except IndexError:
socli.printer.print_warning("No results found...")
printer.print_warning("No results found...")
sys.exit(1)
except UnicodeEncodeError:
socli.printer.print_warning("Encoding error: Use \"chcp 65001\" command before "
printer.print_warning("Encoding error: Use \"chcp 65001\" command before "
"using socli...")
sys.exit(0)
except requests.exceptions.ConnectionError:
socli.printer.print_fail("Please check your internet connectivity...")
printer.print_fail("Please check your internet connectivity...")
except Exception as e:
socli.printer.showerror(e)
printer.showerror(e)
sys.exit(0)


Expand Down Expand Up @@ -414,11 +417,11 @@ def captcha_check(url):
"Use the -s tag to search via Stack Overflow instead."
# Check if google detects user as a bot
if re.search(r"ipv4\.google\.com/sorry", url):
socli.printer.print_warning(google_error_display_msg)
printer.print_warning(google_error_display_msg)
exit(0)
else:
if re.search(r"\.com/nocaptcha", url): # Searching for stackoverflow captcha check
socli.printer.print_warning("StackOverflow captcha check triggered. Please wait a few seconds before trying again.")
printer.print_warning("StackOverflow captcha check triggered. Please wait a few seconds before trying again.")
exit(0)


Expand Down
17 changes: 10 additions & 7 deletions socli/socli.py
Expand Up @@ -21,14 +21,17 @@
except AttributeError:
JSONDecodeError = ValueError

# Importing SoCli modules
import socli.tui as tui
import socli.user as user_module
import socli.search as search
import socli.printer as printer
from socli.parser import parse_arguments
from socli.printer import display_results

# Importing SoCli modules
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
sys.path = [BASE_DIR] + sys.path

import tui as tui
import user as user_module
import search as search
import printer as printer
from parser import parse_arguments
from printer import display_results

tag = "" # tag based search
query = "" # Query
Expand Down
8 changes: 7 additions & 1 deletion socli/tui.py
Expand Up @@ -5,15 +5,21 @@
import sys
import subprocess
import urwid
import os

import socli.printer as pr
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
sys.path = [BASE_DIR] + sys.path

import printer as pr

question_post = None
question_page = None
display_header = None
MAIN_LOOP = None




class UnicodeText(urwid.Text):
""" encode all text to utf-8 """

Expand Down
7 changes: 6 additions & 1 deletion socli/user.py
Expand Up @@ -4,8 +4,13 @@

import json
import os
import sys

import socli.printer as pr
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
sys.path = [BASE_DIR] + sys.path


import printer as pr

app_data = dict() # Data file dictionary
data_file = os.path.join(os.path.dirname(__file__), "data.json") # Data file location
Expand Down

0 comments on commit 79f128b

Please sign in to comment.