diff --git a/.gitignore b/.gitignore index 82f9275..bc4bc86 100644 --- a/.gitignore +++ b/.gitignore @@ -159,4 +159,5 @@ cython_debug/ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore # and can be added to the global gitignore or merged into this file. For a more nuclear # option (not recommended) you can uncomment the following to ignore the entire idea folder. -#.idea/ +.idea/ +.vscode/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..aeeaf2f --- /dev/null +++ b/README.md @@ -0,0 +1,309 @@ +# Getting Started + +실행 방법은 레포지토리의 최상위 폴더에서 아래의 명령어를 수행하면 된다. + +```bash +python -m otoeic +``` + + +# Class Diagram + +```mermaid +classDiagram +direction LR + +note for Page "visit()은 다음에 방문해야 할\n페이지의 객체를 반환한다." +note for Exception "Python의 built-in 클래스이다." +note for UnauthorizedException "주로 사용자가 로그인 되어있지 않은 경우 발생" +note for AuthenticationFailedException "주로 로그인에 실패할 경우 발생" +note for Repository "Service 클래스에서 사용할 각 엔티티별 레포지토리의 구현체는\n본 다이어그램에 나타나있지 않지만 구현할 필요가 있다." +note for ValueError "Python의 built-in 클래스이다.\n주로 값이 잘못 세팅되어 있을 경우 발생\n(특히 DTO)" +note for Streak "(user_id, date)에 대해 고유하다.\n(Unique Constraint)" +note for Entity "아직 Repository에 저장되지 않은\nEntity의 id는 None이다.\n\n저장이 될때 id를 할당 받는다.\n(Autoincrement)\n\ndao는 클래스 변수이다.\n\nsave()/delete()는 해당 엔티티\n인스턴스를 dao에서 저장/제거한다." + +Application *-- Page : uses + +Page <|.. LoginPage : implements +Page <|.. HomePage : implements +Page --> Service : uses +Page --> ServiceException : handles + +UnauthorizedException --|> ServiceException : extends +AuthenticationFailedException --|> ServiceException : extends +Exception <|-- ServiceException : extends +Exception <|-- ValueError : extends +ServiceException <-- Service : raises + +StreakDTO <-- Service : serves +UserDTO <-- Service : serves +ExamDTO <-- Service : serves +SubmittedExamDTO <-- Service : serves +WordDTO <-- Service : serves + +ExamDTO --> WordLevel +QuestionDTO --o ExamDTO : contains +QuestionDTO --> WordType + +SubmittedExamDTO --> WordLevel +SubmittedQuestionDTO --o SubmittedExamDTO : contains +SubmittedQuestionDTO --> WordType + +WordDTO --> WordType +WordDTO --> WordLevel + +Service --> Streak : uses +Service --> User : uses +Service --> Exam : uses +Service --> Question : uses +Service --> Word : uses + +Streak --|> Entity +User --|> Entity +Exam --|> Entity +Question --|> Entity +Word --|> Entity + +Entity --o Repository : manages + +Streak *-- Repository : accesses +User *-- Repository : accesses +Exam *-- Repository : accesses +Question *-- Repository : accesses +Word *-- Repository : accesses + +WordType <-- Word +WordLevel <-- Word + +namespace Pages { + class Page + class LoginPage + class HomePage +} + +namespace Exceptions { + class Exception + class ServiceException + class UnauthorizedException + class AuthenticationFailedException +} + +namespace DTOs { + class UserDTO + class StreakDTO + class WordDTO + class ExamDTO + class QuestionDTO + class SubmittedExamDTO + class SubmittedQuestionDTO +} + +namespace Enums { + class WordType + class WordLevel +} + +namespace Models { + class Repository + class Entity + + class User + class Streak + class Word + class Exam + class Question +} + +class Application { + +run() +} + +class Page { + <> + +visit() Page +} + +class Service { + <> + -current_user_id Optional~int~ + -update_streak_graph() + + +sign_in(str username, str password) + +sign_up(str username, str password) UserDTO + +sign_out() + +get_current_user() UserDTO + + +list_words() List~WordDTO~ + +save_word(WordDTO) WordDTO + +delete_word(WordDTO) + + +get_streak_graph() List~StreakDTO~ + +get_streak_count_of_today() int + +is_streak_filled_today() bool + +buy_streak_freeze(int amount) UserDTO + +get_is_streak_freeze_enabled() bool + +set_is_streak_freeze_enabled(bool) + + +list_exam_history() List~SubmittedExamDTO~ + +create_exam(ExamDTO) ExamDTO + +submit_exam(ExamDTO) SubmittedExamDTO +} + +class UserDTO { + +get_id() Optional~int~ + +get_username() str + +get_coins() int + +get_streak_freeze() int + +get_is_streak_freeze_enabled() bool + +set_is_streak_freeze_enabled(bool) + +get_is_admin() bool +} + +class WordDTO { + +get_id() Optional~int~ + +get_english() str + +set_english(str) + +get_korean() str + +set_korean(str) + +get_type() WordType + +set_type(WordType) + +get_level() WordLevel + +set_level(WordLevel) + +get_created_at() datetime +} + +class ExamDTO { + +get_id() Optional~int~ + +get_level() WordLevel + +set_level(WordLevel) + +get_number_of_questions() int + +set_number_of_questions(int) + +get_questions() List~QuestionDTO~ +} + + +class QuestionDTO { + +get_id() Optional~int~ + +get_question_number() int + +get_korean() str + +get_type() WordType + +get_english_submitted() str + +set_english_submitted(str) +} + +class SubmittedExamDTO { + +get_id() Optional~int~ + +get_level() WordLevel + +get_number_of_questions() int + +get_questions() List~SubmittedQuestionDTO~ + +get_total_reward_coins() int +} + +class SubmittedQuestionDTO { + +get_id() Optional~int~ + +get_question_number() int + +get_korean() str + +get_type() WordType + +get_english_answer() str + +get_english_submitted() str + +get_is_correct() bool + +get_reward_coins() int +} + +class StreakDTO { + +get_date() date + +get_value() int + +get_is_freezed() bool + +get_previous() Optional~StreakDTO~ +} + +class Repository~E~ { + <> + +get(int id) E + +all() List~E~ + +save(E entity) + +delete(E entity) +} + +class Entity~E~ { + <> + +dao Repository~E~* + +Optional~int~ id + +save() + +delete() +} + +class User { + +dao Repository~User~$ + +Optional~int~ id + +str username + +str password + +bool is_admin + +int coin + +int streak_freeze + +bool is_streak_freeze_enabled + +save() + +delete() +} + +class Streak { + +dao Repository~Streak~$ + +Optional~int~ id + +int user_id + +date date + +int value + +bool is_freezed + +save() + +delete() +} + +class Word { + +dao Repository~Word~$ + +Optional~int~ id + +str english + +str korean + +WordType type + +WordLevel level + +datetime created_at + +save() + +delete() +} + +class Exam { + +dao Repository~Exam~$ + +Optional~int~ id + +int user_id + +datetime created_at + +datetime submitted_at + +save() + +delete() +} + +class Question { + +dao Repository~Question~$ + +Optional~int~ id + +int exam_id + +int word_id + +int question_number + +str english_submitted + +int reward_coins + +save() + +delete() +} + +class WordType { + <> + +str NOUN + +str VERB + +str ADJ + +str ADV +} + +class WordLevel { + <> + +int EASY + +int NORMAL + +int HARD + +int VERY_HARD +} +``` diff --git a/otoeic/__init__.py b/otoeic/__init__.py new file mode 100644 index 0000000..03643b4 --- /dev/null +++ b/otoeic/__init__.py @@ -0,0 +1,3 @@ +__version__ = "1.0.0" +__author__ = ["김동주", "이찬민", "양효인"] +__description__ = "상명대학교 2024년도 소프트웨어공학 DevOops조 리팩토링 프로젝트" diff --git a/otoeic/__main__.py b/otoeic/__main__.py new file mode 100644 index 0000000..dd91ca7 --- /dev/null +++ b/otoeic/__main__.py @@ -0,0 +1,5 @@ +from otoeic.app import Application + + +if __name__ == "__main__": + Application().run() diff --git a/otoeic/app.py b/otoeic/app.py new file mode 100644 index 0000000..2cf1418 --- /dev/null +++ b/otoeic/app.py @@ -0,0 +1,8 @@ +from otoeic.pages import get_page + + +class Application: + def run(self): + page = get_page('landing') + while page is not None: + page = page.visit() diff --git a/otoeic/dtos/__init__.py b/otoeic/dtos/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/otoeic/enums.py b/otoeic/enums.py new file mode 100644 index 0000000..aa16e98 --- /dev/null +++ b/otoeic/enums.py @@ -0,0 +1,35 @@ +from enum import Enum + + +class WordType(Enum): + NOUN = 1 # 명사 + VERB = 2 # 동사 + ADJECTIVE = 3 # 형용사 + ADVERB = 4 # 부사 + PRONOUN = 5 # 대명사 + PREPOSITION = 6 # 전치사 + CONJUNCTION = 7 # 접속사 + INTERJECTION = 8 # 감탄사 + DETERMINER = 9 # 한정사 + NUMERAL = 10 # 수사 + PARTICLE = 11 # 조사 + ARTICLE = 12 # 관사 + MODAL = 13 # 조동사 + PHRASAL_VERB = 14 # 구동사 + IDIOM = 15 # 관용구 + + +class WordLevel(Enum): + """ + TODO: 코파일럿이 추천해준 아래의 5단계는 어떤지 토론해볼 것 + + BASIC = 1 # 초급 + INTERMEDIATE = 2 # 중급 + ADVANCED = 3 # 고급 + PROFESSIONAL = 4 # 전문가 + NATIVE = 5 # 원어민 + """ + EASY = 1 # 쉬움 + NORMAL = 2 # 보통 + HARD = 3 # 어려움 + VERY_HARD = 4 # 매우 어려움 diff --git a/otoeic/exceptions.py b/otoeic/exceptions.py new file mode 100644 index 0000000..c5689e7 --- /dev/null +++ b/otoeic/exceptions.py @@ -0,0 +1,45 @@ +from textwrap import dedent + + +class ServiceException(Exception): + """Base class for exceptions in this module.""" + pass + + +class InvalidPageNameError(ServiceException): + """Raised when a page name is not registered.""" + + def __init__(self, page_name: str): + self.page_name = page_name + super().__init__(dedent(f""" + -------------------------------- + 다음의 이름으로 등록된 페이지가 없습니다: + '{page_name}' + -------------------------------- + 혹시 페이지를 등록하는 것을 잊지 않으셨나요? + 페이지 등록 방법 예시: + -------------------------------- + from src.pages import * + + @register_page('{page_name}') + class {page_name.capitalize()}Page(Page): + def visit(self) -> Page: + ... + return get_page('home') + + -------------------------------- + """)) + + +class UnauthorizedException(ServiceException): + """Raised when a user is not authorized to perform an action.""" + + def __init__(self): + super().__init__(f"이 작업을 수행하기 위한 권한이 없습니다. 로그인 여부를 확인하세요.") + + +class AuthenticationFailedException(ServiceException): + """Raised when a user fails to authenticate.""" + + def __init__(self, username: str): + super().__init__(f"사용자명 '{username}' 에 대한 인증이 실패했습니다.") diff --git a/otoeic/models/__init__.py b/otoeic/models/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/otoeic/pages/__init__.py b/otoeic/pages/__init__.py new file mode 100644 index 0000000..c6c2dba --- /dev/null +++ b/otoeic/pages/__init__.py @@ -0,0 +1,68 @@ +from __future__ import annotations +from glob import glob +from pathlib import Path +from typing import Type + +from otoeic.exceptions import InvalidPageNameError + + +__all__ = ( + "Page", + "register_page", + "get_page", +) + + +def get_page(page_name: str) -> Page: + try: + return _PAGE_REGISTRY[page_name] + except KeyError: + # 하이~! 유독 이 곳에 자주 방문하게 되지 않나요? + # 이왕 온 것 기분 좋게 가는게 좋을 것 같아 여기에 인사를 남깁니다. + # 반갑습니다, 좋은 하루~! + raise InvalidPageNameError(page_name) + + +def register_page(page_name: str, page_class: Type[Page] = None): + """페이지간 의존성 역전을 위한 데코레이터 + + 사용 예시: + + ```python + from src.pages import * + + @register_page('login') + class LoginPage(Page): + def visit(self) -> Page: + ... + return get_page('home') + ``` + """ + def decorator(page_class: Type[Page]): + assert issubclass(page_class, Page) + _PAGE_REGISTRY[page_name] = page_class() # makes instance + return page_class + if page_class is not None: + decorator(page_class) + return decorator + + +class Page: + def visit(self) -> Page | None: + """페이지를 방문하고 다음으로 방문할 페이지를 반환한다.""" + raise NotImplementedError + + +_PAGE_REGISTRY = {} + + +# 자동으로 모든 페이지를 등록한다. +# 현재 파일이 있는 디렉토리에서 모든 .py 파일을 찾아서 import 한다. +DIR = Path(__file__).resolve().parent +for page_file in glob((DIR / "*.py").as_posix()): + if page_file.endswith("__init__.py"): + continue + page_file = Path(page_file).relative_to(DIR).as_posix() + sub_module_name = page_file.replace("/", ".").replace(".py", "") + module_name = __name__ + "." + sub_module_name + __import__(module_name) diff --git a/otoeic/pages/landing.py b/otoeic/pages/landing.py new file mode 100644 index 0000000..73edb8b --- /dev/null +++ b/otoeic/pages/landing.py @@ -0,0 +1,20 @@ +from otoeic import ( + __version__, + __author__, + __description__, +) +from otoeic.pages import * + + +@register_page('landing') +class LandingPage(Page): + def visit(self) -> Page | None: + print('=' * 64) + print('오토익(OToeic)에 오신 것을 환영합니다!') + print() + print('{}'.format(__description__)) + print() + print('Ver. {}'.format(__version__)) + print('By {}'.format(', '.join(__author__))) + print('=' * 64) + return get_page('login')