Skip to content

Commit

Permalink
I don't remember
Browse files Browse the repository at this point in the history
  • Loading branch information
VideoGameDesignTSATeam committed Jul 10, 2019
1 parent 9b1e0c4 commit 113348b
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 39 deletions.
77 changes: 44 additions & 33 deletions Database.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,6 @@

from pymongo import MongoClient

client = MongoClient('localhost', 27017)
db = client.dates

users = db.users


def parse_date(date: str) -> tuple:
"""
Expand All @@ -26,7 +21,7 @@ def parse_date(date: str) -> tuple:
is_date = compiled_regex.match(date_section)
if not is_date:
if len(split_date[0]) != 4:
raise SyntaxError(
raise ValueError(
f"Invalid Syntax: The date inputed ({date}) should be in YYYY-MM-DD format"
)

Expand All @@ -35,7 +30,7 @@ def parse_date(date: str) -> tuple:

is_date = compiled_regex.match(date_section)
if not is_date:
raise SyntaxError(
raise ValueError(
f"Invalid Syntax: The date inputed ({date}) should be in YYYY-MM-DD format"
)

Expand All @@ -45,11 +40,12 @@ def parse_date(date: str) -> tuple:
return (int_dates, split_date)


def update_or_reset_user(user_id: str,
# ? Deprecated
"""def update_or_reset_user(user_id: str,
name: str,
start: int = None,
end: int = None):
"""Resets user if {start} and {end} field are taken. Otherwise changes the values of the user"""
\"""Resets user if {start} and {end} field are taken. Otherwise changes the values of the user\"""
if start is not None and end is not None:
assert start <= end
else:
Expand All @@ -62,26 +58,23 @@ def update_or_reset_user(user_id: str,
'start_date': parse_date(start),
'end_date': parse_date(end)
}
users.update_one({'_id': user_id}, {'$set': user}, upsert=True)

users.update_one({'_id': user_id}, {'$set': user}, upsert=True)"""

# DEBUG CODE. # * REMOVE LATER
# for document in users.find():
# pprint(document)
# test_dates = ("2019-10-12", "2012-04-33", "2019-22-3", "2019-11-09", "2222-12-31")
# parse_dates(test_dates)


def taken(user_id: str, start: int, end: int, max_amount: int) -> bool:
"""
"""def taken(user_id: str, start: int, end: int, max_amount: int) -> bool:
\"""
Checks if dates are taken
:param user_id: originally pulled from slack
:param start: start date of availability
:param max_amount: start date of availability
:param end: end date of availability
:rtype: bool
"""
\"""
assert user_id is not None and start <= end
current_scheduled = 0
Expand All @@ -93,6 +86,7 @@ def taken(user_id: str, start: int, end: int, max_amount: int) -> bool:
and current_scheduled < max_amount):
current_scheduled += 1
return True if current_scheduled <= max_amount else False
"""


class MongoTools():
Expand All @@ -107,7 +101,8 @@ def __init__(self,
port=27017,
**kwargs):
self.buffer = []
self.database = MongoClient(host, port)[database]
self.mc = MongoClient(host, port)
self.database = self.mc[database]
self.BUFFER_SIZE = buffer_size

def clear_buffer(self):
Expand All @@ -119,36 +114,43 @@ def append(self, other):
:param other: either a list of dicts or another MongoBuffer
"""
# for documents in other: # * Need to know how to use __iter__
# for documents in other: # * Need to figure out how to use __iter__
# assert documents is dict
assert other is list or other is MongoTools
assert type(other) is list or type(other) is MongoTools # Fixed
if len(self.buffer) + len(other) > self.BUFFER_SIZE:
self.push_to_collection("scheduled_users")

self.buffer = [*self.buffer, *other
] if other is list else [*self.buffer, *other.buffer]
self.buffer = [*self.buffer, *other] if type(other) is list else [
*self.buffer, *other.buffer
]
self.remove_duplicates()

def remove_duplicates(self, id_list=None):

if id_list is None:
id_list = self.get_ids()
nd_set = set(self.buffer)
if len(id_list) == len(nd_set):
id_set = set(id_list)
if len(id_list) == len(id_set):
print("no duplicates to remove!")
else:
dif = sorted(id_list) - nd_set
dif = sorted(id_list) - id_set
# print(dif) # * DEBUG

assert len(self.buffer) >= dif
assert len(self.buffer) >= len(dif)
u_buffer = []
for index, r_id in enumerate(dif):
if self.buffer[index].get("user_id") != r_id:
u_buffer.append(self.buffer[index])
for i, r_id in enumerate(dif):
if self.buffer[i].get("user_id") != r_id:
u_buffer.append(self.buffer[i])

self.buffer = u_buffer

# self.buffer = [
# dict(t) for t in {tuple(d.items())
# for d in self.buffer}
# ]

def is_duplicates(self, remove_dupes=False) -> bool:
assert self.buffer > 0
assert len(self.buffer) > 0
ids = self.get_ids(self.buffer)
if ids != set(ids):
if remove_dupes:
Expand All @@ -165,20 +167,29 @@ def get_ids(self, buffer: list = None) -> list:
return ids

def push_to_collection(self, collection: str):
"""
:param collection: The MongoDB Collection
"""
col = self.database[collection]

if self.is_duplicates():
self.remove_duplicates(id_list=self.get_ids(buffer=self.buffer))

col.update_many(filter={}, update={"$set": self.buffer}, upsert=True)
for doc in self.buffer:
col.update(filter={doc['user_id']},
update={"$set": doc},
upsert=True)
self.clear_buffer()

def __add__(self, other):
assert other is list or other is MongoTools
assert type(other) is list or isinstance(other, MongoTools) # Fixed
if len(self.buffer) + len(other) > self.BUFFER_SIZE:
self.push_to_collection("scheduled_users")
self.buffer = [*self.buffer, *other
] if other is list else [*self.buffer, *other.buffer]
self.buffer = [*self.buffer, *other] if type(other) is list else [
*self.buffer, *other.buffer
]
self.remove_duplicates()

def __len__(self) -> int:
Expand Down
6 changes: 3 additions & 3 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from slackeventsapi import SlackEventAdapter

from BlockCreator import BlockBuilder
from Database import MongoTools, parse_date # , update_or_reset_user
from Database import MongoTools, parse_date # , update_or_reset_user # Unkown if needed

app = Flask(__name__)

Expand Down Expand Up @@ -110,12 +110,12 @@ def handle_interaction():
continue
start_date, end_date = handle_date_selection(datepickers[0],
datepickers[1])
db.append({
db.append([{
"user_id": user.get('id'),
"name": user.get('name'),
"start_date": start_date,
"end_date": end_date
})
}])
logging.debug(pformat(db))
handle_button_click(value, user.get('id'), channel, m_ts,
user.get('name'))
Expand Down
4 changes: 2 additions & 2 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<img width=200px height=200px src="https://i.imgur.com/FxL5qM0.jpg" alt="Bot logo"></a>
</p>

<h3 align="center">Project Title</h3>
<h3 align="center">Slack Scheduler</h3>

<!--
<div align="center">
Expand All @@ -19,7 +19,7 @@

---

<p align="center"> 🤖 A Bot which schedules who's on call
<p align="center"> 🤖 A bot which schedules who's on call
<br>
</p>

Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

setup(
name="Slack Scheduler Bot",
version="0.0.1-ALPHA",
version="0.0.4-ALPHA",
packages=['flask', 'slackeventsapi', 'slackclient', 'pymongo'],
long_description=open("readme.md").read(),
)

0 comments on commit 113348b

Please sign in to comment.