Skip to content

Commit

Permalink
Merge pull request InstaPy#2627 from uluQulu/master
Browse files Browse the repository at this point in the history
Solve misbehaviours of InstaPy#2605 🐝
  • Loading branch information
timgrossmann authored Aug 8, 2018
2 parents 1645d61 + c7d9e85 commit 5e5282e
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 50 deletions.
109 changes: 66 additions & 43 deletions instapy/database_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,16 @@

from .settings import Settings



SELECT_FROM_PROFILE_WHERE_NAME = "SELECT * FROM profiles WHERE name = :name"

INSERT_INTO_PROFILE = "INSERT INTO profiles (name) VALUES (?)"

SQL_CREATE_PROFILE_TABLE = """CREATE TABLE IF NOT EXISTS `profiles` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`name` TEXT NOT NULL);"""

SQL_CREATE_RECORD_ACTIVITY_TABLE = """CREATE TABLE IF NOT EXISTS `recordActivity` (
`profile_id` INTEGER REFERENCES `profiles` (id),
`likes` SMALLINT UNSIGNED NOT NULL,
Expand All @@ -16,80 +21,90 @@
`unfollows` SMALLINT UNSIGNED NOT NULL,
`server_calls` INT UNSIGNED NOT NULL,
`created` DATETIME NOT NULL);"""

SQL_CREATE_FOLLOW_RESTRICTION_TABLE = """CREATE TABLE IF NOT EXISTS `followRestriction` (
`profile_id` INTEGER REFERENCES `profiles` (id),
`username` TEXT NOT NULL,
`times` TINYINT UNSIGNED NOT NULL);"""


def get_database():
_id = Settings.profile["id"]

def get_database(make=False):
address = Settings.database_location
return address, _id
logger = Settings.logger
credentials = Settings.profile

id, name = credentials["id"], credentials['name']
address = validate_database_address()

if not os.path.isfile(address) or make:
create_database(address, logger, name)

id = get_profile(name, address, logger) if id is None or make else id

return address, id

def initialize_database():
logger = Settings.logger
name = Settings.profile['name']
address = validate_database_file_address()
create_database_directories(address)
create_database(address, logger, name)
update_profile_settings(name, address, logger)


def create_database(address, logger, name):
if not os.path.isfile(address):
try:
connection = sqlite3.connect(address)
with connection:
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
try:
connection = sqlite3.connect(address)
with connection:
connection.row_factory = sqlite3.Row
cursor = connection.cursor()

create_profiles_table(cursor)
create_record_activity_table(cursor)
create_follow_restriction_table(cursor)
create_tables(cursor, ["profiles",
"recordActivity",
"followRestriction"
])

connection.commit()
connection.commit()

except Exception as exc:
logger.warning(
"Wah! Error occured while getting a DB for '{}':\n\t{}".format(name, str(exc).encode("utf-8")))
except Exception as exc:
logger.warning(
"Wah! Error occured while getting a DB for '{}':\n\t{}".format(name, str(exc).encode("utf-8")))

finally:
if connection:
# close the open connection
connection.close()
finally:
if connection:
# close the open connection
connection.close()


def create_follow_restriction_table(cursor):
cursor.execute(SQL_CREATE_FOLLOW_RESTRICTION_TABLE)

def create_tables(cursor, tables):
if "profiles" in tables:
cursor.execute(SQL_CREATE_PROFILE_TABLE)

def create_record_activity_table(cursor):
cursor.execute(SQL_CREATE_RECORD_ACTIVITY_TABLE)
if "recordActivity" in tables:
cursor.execute(SQL_CREATE_RECORD_ACTIVITY_TABLE)

if "followRestriction" in tables:
cursor.execute(SQL_CREATE_FOLLOW_RESTRICTION_TABLE)

def create_profiles_table(cursor):
cursor.execute(SQL_CREATE_PROFILE_TABLE)


def create_database_directories(address):
def verify_database_directories(address):
db_dir = os.path.dirname(address)
if not os.path.exists(db_dir):
os.makedirs(db_dir)


def validate_database_file_address():

def validate_database_address():
address = Settings.database_location
if not address.endswith(".db"):
slash = "\\" if "\\" in address else "/"
address = address if address.endswith(slash) else address + slash
address += "instapy.db"
Settings.database_location = address

verify_database_directories(address)

return address


def update_profile_settings(name, address, logger):

def get_profile(name, address, logger):
try:
conn = sqlite3.connect(address)
with conn:
Expand All @@ -99,9 +114,9 @@ def update_profile_settings(name, address, logger):
profile = select_profile_by_username(cursor, name)

if profile is None:
profile = insert_profile(conn, cursor, name)

Settings.update_settings_with_profile(dict(profile))
add_profile(conn, cursor, name)
# reselect the table after adding data to get the proper `id`
profile = select_profile_by_username(cursor, name)

except Exception as exc:
logger.warning("Heeh! Error occured while getting a DB profile for '{}':\n\t{}".format(name, str(exc).encode("utf-8")))
Expand All @@ -111,19 +126,27 @@ def update_profile_settings(name, address, logger):
# close the open connection
conn.close()

profile = dict(profile)
id = profile["id"]

def insert_profile(conn, cursor, name):
# assign the id to its child in `Settings` class
Settings.profile["id"] = id

return id



def add_profile(conn, cursor, name):
cursor.execute(INSERT_INTO_PROFILE, (name,))
# commit the latest changes
conn.commit()
# reselect the table after adding data to get the proper `id`
profile = select_profile_by_username(cursor, name)
return profile



def select_profile_by_username(cursor, name):
cursor.execute(SELECT_FROM_PROFILE_WHERE_NAME, {"name": name})
profile = cursor.fetchone()

return profile


Expand Down
4 changes: 2 additions & 2 deletions instapy/instapy.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@
from .relationship_tools import get_nonfollowers
from .relationship_tools import get_fans
from .relationship_tools import get_mutual_following
from .database_engine import initialize_database
from .database_engine import get_database



Expand Down Expand Up @@ -187,7 +187,7 @@ def __init__(self,
# Assign logger
self.logger = self.get_instapy_logger(self.show_logs)

initialize_database()
get_database(make=True)

if self.selenium_local_session == True:
self.set_selenium_local_session()
Expand Down
5 changes: 0 additions & 5 deletions instapy/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,3 @@ class Settings:
logger = None
# Set current profile credentials for DB operations
profile = {"id":None, "name":None}

@staticmethod
def update_settings_with_profile(profile):
Settings.profile["id"] = profile["id"]
Settings.profile["name"] = profile["name"]

0 comments on commit 5e5282e

Please sign in to comment.