Skip to content

Commit 68f38b1

Browse files
authored
Merge pull request #13 from coder-inbox/fix-auth
mv send_emails nylas users, fix language selection...
2 parents 5beb42b + 46259bc commit 68f38b1

File tree

5 files changed

+116
-63
lines changed

5 files changed

+116
-63
lines changed

src/nylas/router.py

Lines changed: 7 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,5 @@
11
"""Nylas router module."""
22

3-
from apscheduler.schedulers.background import (
4-
BackgroundScheduler,
5-
)
6-
from asyncio import (
7-
ensure_future,
8-
)
93
from fastapi import (
104
APIRouter,
115
Depends,
@@ -73,33 +67,7 @@ async def exchange_code_for_token(
7367
Exchanges an authorization code for an access token.
7468
"""
7569
try:
76-
from src.main import (
77-
code_app,
78-
)
79-
80-
scheduler = BackgroundScheduler()
81-
response = await nylas_crud.login_user(request.token, session)
82-
83-
if response:
84-
# send a welcome email in the background
85-
ensure_future(
86-
nylas_crud.send_welcome_email(response["user"]["email"])
87-
)
88-
# send an algorithm email in the background
89-
ensure_future(
90-
code_app.state.openai.async_send_algorithm_email(
91-
response["user"]["email"], "python"
92-
)
93-
)
94-
scheduler.add_job(
95-
code_app.state.openai.send_algorithm_email,
96-
"interval",
97-
hours=24,
98-
args=(response["user"]["email"], "python"),
99-
)
100-
scheduler.start()
101-
return response
102-
return {"message": "An error occurred while exchanging the token."}
70+
return await nylas_crud.login_user(request.token, session)
10371
except Exception as e:
10472
print(e)
10573
return {"message": "An error occurred while exchanging the token."}
@@ -134,7 +102,7 @@ async def fetch_emails(
134102
status_code=200,
135103
name="nylas:mail",
136104
)
137-
def get_message(
105+
async def get_message(
138106
mailId: str,
139107
current_user: users_schemas.UserObjectSchema = Depends(
140108
dependencies.get_current_user
@@ -157,7 +125,7 @@ def get_message(
157125
status_code=200,
158126
name="nylas:send-email",
159127
)
160-
def send_email(
128+
async def send_email(
161129
request_body: nylas_schemas.SendEmailSchema,
162130
current_user: users_schemas.UserObjectSchema = Depends(
163131
dependencies.get_current_user
@@ -236,7 +204,7 @@ async def delete_label(
236204
status_code=200,
237205
name="nylas:send-email",
238206
)
239-
def create_label(
207+
async def create_label(
240208
request_body: nylas_schemas.CreateLabelSchema,
241209
current_user: users_schemas.UserObjectSchema = Depends(
242210
dependencies.get_current_user
@@ -262,7 +230,7 @@ def create_label(
262230
status_code=200,
263231
name="nylas:folders",
264232
)
265-
def update_folder(
233+
async def update_folder(
266234
items: List[str],
267235
current_user: users_schemas.UserObjectSchema = Depends(
268236
dependencies.get_current_user
@@ -282,7 +250,7 @@ def update_folder(
282250
status_code=200,
283251
name="nylas:reply-email",
284252
)
285-
def reply_email(
253+
async def reply_email(
286254
request_body: nylas_schemas.ReplyEmailSchema,
287255
current_user: users_schemas.UserObjectSchema = Depends(
288256
dependencies.get_current_user
@@ -316,7 +284,7 @@ def reply_email(
316284
status_code=200,
317285
name="nylas:contacts",
318286
)
319-
def read_contacts(
287+
async def read_contacts(
320288
current_user: users_schemas.UserObjectSchema = Depends(
321289
dependencies.get_current_user
322290
),

src/users/crud.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ async def update_user_info(
112112
{
113113
"full_name": personal_info.full_name,
114114
"bio": personal_info.bio,
115-
"proramming_language": personal_info.proramming_language,
115+
"programming_language": personal_info.programming_language,
116116
"modified_date": datetime.utcnow(),
117117
}
118118
)

src/users/router.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,12 @@
2323
2424
"""
2525

26+
from apscheduler.schedulers.background import (
27+
BackgroundScheduler,
28+
)
29+
from asyncio import (
30+
ensure_future,
31+
)
2632
from deta import Deta
2733
from fastapi import (
2834
APIRouter,
@@ -43,6 +49,9 @@
4349
from src.config import (
4450
settings,
4551
)
52+
from src.nylas import (
53+
crud as nylas_crud,
54+
)
4655
from src.users import (
4756
crud as users_crud,
4857
schemas as users_schemas,
@@ -160,3 +169,56 @@ async def update_personal_information(
160169
}
161170
except Exception:
162171
return {"status_code": 400, "message": "Something went wrong!"}
172+
173+
174+
@router.put(
175+
"/user/language",
176+
response_model=Dict[str, Any],
177+
status_code=200,
178+
name="user:language",
179+
)
180+
async def update_language(
181+
request_body: users_schemas.LanguageSchema,
182+
current_user: users_schemas.UserObjectSchema = Depends(
183+
dependencies.get_current_user
184+
),
185+
session: AIOSession = Depends(dependencies.get_db_transactional_session),
186+
) -> Dict[str, Any]:
187+
"""
188+
Set the programming language for a specific user using their access token.
189+
"""
190+
try:
191+
from src.main import (
192+
code_app,
193+
)
194+
195+
scheduler = BackgroundScheduler()
196+
user_info = users_schemas.PersonalInfo(
197+
full_name=current_user.full_name,
198+
bio=current_user.bio,
199+
programming_language=request_body.language,
200+
)
201+
await users_crud.update_user_info(user_info, current_user, session)
202+
# send a welcome email in the background
203+
ensure_future(nylas_crud.send_welcome_email(current_user.email))
204+
# send an algorithm email in the background
205+
ensure_future(
206+
code_app.state.openai.async_send_algorithm_email(
207+
current_user.email, request_body.language
208+
)
209+
)
210+
# send an algorithm email every 24 hours
211+
scheduler.add_job(
212+
code_app.state.openai.send_algorithm_email,
213+
"interval",
214+
hours=24,
215+
args=(current_user.email, request_body.language),
216+
)
217+
scheduler.start()
218+
return {
219+
"status_code": 200,
220+
"message": "Your programming language has been updated successfully!",
221+
}
222+
except Exception as e:
223+
print(e)
224+
return {"status_code": 400, "message": "Something went wrong!"}

src/users/schemas.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,3 +112,14 @@ class LogoutSchema(BaseModel):
112112
"""
113113

114114
token: str = Field(..., example="123456789", description="User's token.")
115+
116+
117+
class LanguageSchema(BaseModel):
118+
"""Languge Schema
119+
120+
A Pydantic class that defines the language schema for updating the programming language for a user.
121+
"""
122+
123+
language: str = Field(
124+
..., example="python", description="User's programming language."
125+
)

src/utils/openai_api.py

Lines changed: 35 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ class OpenAIAPI:
3838
api_token: str
3939
model: str = "gpt-3.5-turbo"
4040
temperature: float = 0
41-
max_tokens: int = 128
41+
max_tokens: int = 512
4242
top_p: float = 1
4343
frequency_penalty: float = 0
4444
presence_penalty: float = 0.6
@@ -56,31 +56,43 @@ def __post_init__(self) -> None:
5656
self.prompt = """ # noqa: E501
5757
**Task Prompt:**
5858
59-
As an algorithm expert, your task is to generate a comprehensive algorithm tutorial. The tutorial should cover a specific algorithmic topic of your choice (e.g., sorting algorithms, search algorithms, dynamic programming, graph algorithms, etc.) and provide in-depth explanations, code samples in {programming_language}, and relevant external links for further reading.
59+
As an algorithm expert, your mission is to craft a comprehensive algorithm tutorial. Your tutorial should delve into a specific algorithmic topic of your choice, such as sorting algorithms, search algorithms, dynamic programming, graph algorithms, or any other area of expertise you possess.
6060
6161
**Instructions:**
6262
63-
1. Choose an algorithmic topic that you are knowledgeable about or interested in.
64-
2. Create a tutorial that covers the selected topic in detail.
65-
3. Your tutorial should be structured as an HTML page and include the following sections:
66-
67-
- Title: A clear and informative title for the tutorial.
68-
- Introduction: Briefly introduce the algorithmic topic you will be covering and explain its importance or relevance.
69-
- Overview: Provide an overview of the key concepts and principles related to the algorithm.
70-
- Detailed Explanations: Break down the algorithm into its components and explain each step or concept thoroughly. Use clear and concise language.
71-
- {programming_language} Code Samples: Include {programming_language} code examples that illustrate how the algorithm works. Ensure that the code is well-commented and easy to understand.
72-
- Visualizations (optional): If applicable, include visual representations or diagrams to aid in understanding.
73-
- Complexity Analysis: Discuss the time and space complexity of the algorithm and analyze its efficiency.
74-
- Applications: Describe real-world applications or scenarios where the algorithm is commonly used.
75-
- External Links: Provide links to external resources, research papers, or additional reading materials for those who want to explore the topic further.
76-
- Conclusion: Summarize the key takeaways from the tutorial and reiterate the significance of the algorithm.
77-
78-
4. Ensure that your HTML page is well-structured, with appropriate headings, paragraphs, and code formatting.
79-
5. Use hyperlinks to connect sections, references, and external links.
80-
6. Make use of proper HTML tags for formatting and styling, such as headings, lists, and code blocks.
81-
7. Proofread and edit your tutorial for clarity, accuracy, and completeness.
82-
83-
**Note:** Make sure to choose a unique algorithmic topic every day. Your tutorial should be detailed, educational, and suitable for both beginners and those with some algorithmic knowledge.
63+
1. **Choose Your Algorithm:** Select a unique, different algorithmic topic each time that piques your interest or falls within your domain of expertise.
64+
65+
2. **Craft Your Tutorial:** Your tutorial should be structured as an HTML document, and it must encompass the following sections:
66+
67+
- **Title:** Create a captivating and informative title that encapsulates the essence of your tutorial.
68+
69+
- **Introduction:** Begin with a concise introduction to the chosen algorithmic topic. Explain why this algorithm is significant and relevant in the world of computer science.
70+
71+
- **Overview:** Provide an overview that outlines the fundamental principles and concepts related to the algorithm. Offer a high-level understanding before diving into the specifics.
72+
73+
- **In-Depth Explanation:** Break down the algorithm into its core components, and meticulously elucidate each step or concept. Utilize clear and succinct language to ensure your readers can grasp the material effortlessly.
74+
75+
- **{programming_language} Code Samples:** Embed code examples written in {programming_language} to illustrate the algorithm's inner workings. Ensure your code is well-commented and easily comprehensible. Make sure that your code samples are written in {programming_language}. Don't use any other programming language.
76+
77+
- **Visualizations (optional):** If applicable, consider incorporating visual aids such as diagrams or flowcharts to facilitate understanding.
78+
79+
- **Complexity Analysis:** Engage in a comprehensive discussion about the time and space complexity of the algorithm. Analyze its efficiency and performance.
80+
81+
- **Real-World Applications:** Explore real-world scenarios and use cases where the algorithm finds common application. Make the algorithm's practicality tangible to your readers.
82+
83+
- **External Resources:** Enhance your tutorial by offering links to external resources, research papers, or supplementary reading materials for those eager to delve deeper into the subject.
84+
85+
- **Conclusion:** Summarize the key takeaways from your tutorial, reaffirming the algorithm's importance and relevance.
86+
87+
3. **Structural Integrity:** Ensure that your HTML page is meticulously structured with appropriate headings, well-organized paragraphs, and clean code formatting.
88+
89+
4. **Hyperlink Integration:** Employ hyperlinks to seamlessly connect sections, cross-reference content, and provide quick access to external resources.
90+
91+
5. **HTML Tags for Enhancement:** Utilize proper HTML tags to enhance formatting and styling. Leverage headings, lists, and code blocks to make your content visually appealing and reader-friendly.
92+
93+
6. **Proofreading and Refinement:** Before finalizing your tutorial, meticulously proofread and edit it to guarantee clarity, accuracy, and comprehensiveness.
94+
95+
**Note:** Challenge yourself to explore a unique algorithmic topic each day. Your tutorial should serve as an educational resource catering to both beginners and those possessing some prior knowledge of algorithms. Also, make sure that your tutorial code samples are written in {programming_language}. Don't use any other programming language.
8496
"""
8597

8698
def send_algorithm_email(self, to: str, language: str) -> None:

0 commit comments

Comments
 (0)