By using this site, you agree to have cookies stored on your device, strictly for functional purposes, such as storing your session and preferences.

Dismiss

 celery_tasks.py

View raw Download
text/x-script.python • 9.56 kiB
Python script, ASCII text executable
        
            
1
import common
2
import time
3
import os
4
import config
5
import email_send
6
import shutil
7
from celery import shared_task
8
from app import db, _
9
from smtplib import SMTP
10
from celery.utils.log import get_task_logger
11
from sqlalchemy.orm import make_transient
12
from datetime import datetime
13
14
15
@shared_task(ignore_result=False)
16
def send_notification(user_notification_id):
17
from models import UserNotification, Commit, Post, PullRequest
18
user_notification = db.session.get(UserNotification, user_notification_id)
19
user = user_notification.user
20
notification = user_notification.notification
21
22
if user.email:
23
with (SMTP(config.MAIL_SERVER) as mail):
24
match notification.data.get("type"):
25
case "welcome":
26
message = email_send.make_multipart_message(
27
f"[system] Welcome, {user.username}",
28
config.NOTIFICATION_EMAIL,
29
user.email,
30
"welcome",
31
username=user.username
32
)
33
case "commit":
34
commit = db.session.get(Commit, notification.data.get("commit"))
35
line_separator = "\n\n" # hack so it works in older Pythons
36
newline = "\n"
37
message = email_send.make_multipart_message(
38
f"[commit in {notification.data.get('repo')}] {commit.message.partition(line_separator)[0].replace(newline, ' ')}",
39
config.NOTIFICATION_EMAIL,
40
user.email,
41
"commit",
42
username=user.username,
43
commit=commit,
44
url="https://" if config.suggest_https else "http://" + config.BASE_DOMAIN + "/repo/" + notification.data.get("repo") + "/commit/" + notification.data.get("commit")
45
)
46
case "post":
47
post = db.session.get(Post, notification.data.get("post"))
48
message = email_send.make_multipart_message(
49
f"[post in {notification.data.get('repo')}] {post.subject}",
50
config.NOTIFICATION_EMAIL,
51
user.email,
52
"forum",
53
username=user.username,
54
post=post,
55
url="https://" if config.suggest_https else "http://" + config.BASE_DOMAIN + "/repo/" + notification.data.get("repo") + "/post/" + notification.data.get("post")
56
)
57
case "pr":
58
pr = db.session.get(PullRequest, notification.data.get("pr"))
59
message = email_send.make_multipart_message(
60
f"[PR in {notification.data.get('repo')}] {pr.head_route}:{pr.head_branch} -> {pr.base_route}:{pr.base_branch}",
61
config.NOTIFICATION_EMAIL,
62
user.email,
63
"pr",
64
username=user.username,
65
pr=pr,
66
url="https://" if config.suggest_https else "http://" + config.BASE_DOMAIN + notification.data.get("base") + "/prs/"
67
)
68
69
mail.sendmail(config.NOTIFICATION_EMAIL, user.email, message)
70
71
return 0 # notification sent successfully
72
73
74
@shared_task(ignore_result=False)
75
def merge_heads(head_route, head_branch, base_route, base_branch, simulate=True):
76
from models import Repo, Commit
77
server_repo_location = os.path.join(config.REPOS_PATH, base_route.lstrip("/"))
78
if not os.path.isdir(server_repo_location):
79
raise FileNotFoundError(f"Repo {server_repo_location} not found, cannot merge.")
80
81
if base_route == head_route:
82
common.git_command(server_repo_location, b"", "checkout", f"{base_branch}")
83
if simulate:
84
out, err, merge_exit = common.git_command(server_repo_location, b"", "merge", "--no-commit", "--no-ff", f"heads/{head_branch}",
85
return_err=True, return_exit=True)
86
87
# Undo the merge.
88
common.git_command(server_repo_location, b"", "merge", "--abort")
89
else:
90
out, err, merge_exit = common.git_command(server_repo_location, b"", "merge", f"heads/{head_branch}",
91
return_err=True, return_exit=True)
92
93
new_commits = common.git_command(server_repo_location, b"", "log", "--oneline", f"heads/{base_branch}..heads/{head_branch}")
94
95
return "merge_simulator" if simulate else "merge", out, err, head_route, head_branch, base_route, base_branch, merge_exit, new_commits
96
97
# Otherwise, we need to fetch the head repo.
98
remote_url = "https://" if config.suggest_https else "http://" + os.path.join(config.BASE_DOMAIN + f":{config.port}" if config.port not in {80, 443} else "", "git", head_route.lstrip("/"))
99
100
out, err = b"", b""
101
part_out, part_err = common.git_command(server_repo_location, b"", "remote", "add", "NEW", remote_url, return_err=True)
102
out += part_out
103
err += part_err
104
part_out, part_err = common.git_command(server_repo_location, b"", "remote", "update", return_err=True)
105
out += part_out
106
err += part_err
107
part_out, part_err = common.git_command(server_repo_location, b"", "fetch", "NEW", f"{head_branch}", return_err=True)
108
out += part_out
109
err += part_err
110
part_out, part_err = common.git_command(server_repo_location, b"", "checkout", f"{base_branch}", return_err=True)
111
out += part_out
112
err += part_err
113
new_commits, part_err = common.git_command(server_repo_location, b"", "log", "--pretty=format:\"%H\"", f"heads/{base_branch}..NEW/{head_branch}", "--", return_err=True)
114
new_commits = new_commits.decode().splitlines()
115
err += part_err
116
117
if simulate:
118
part_out, part_err, merge_exit = common.git_command(server_repo_location, b"", "merge", "--allow-unrelated-histories",
119
"--no-commit", "--no-ff", f"NEW/{head_branch}", return_err=True, return_exit=True)
120
else:
121
part_out, part_err, merge_exit = common.git_command(server_repo_location, b"", "merge", "--allow-unrelated-histories",
122
f"NEW/{head_branch}", return_err=True, return_exit=True)
123
124
diff, diff_exit = common.git_command(server_repo_location, b"", "diff", "--check", return_exit=True)
125
126
out += part_out
127
err += part_err
128
part_out, part_err = common.git_command(server_repo_location, b"", "remote", "rm", "NEW", return_err=True)
129
out += part_out
130
err += part_err
131
if simulate:
132
# Undo the merge.
133
common.git_command(server_repo_location, b"", "merge", "--abort")
134
else:
135
# Copy the commits rows from the head repo to the base repo
136
for commit in new_commits:
137
commit_data = Commit.query.filter_by(repo_name=head_route, sha=commit).first()
138
139
db.session.expunge(commit_data)
140
make_transient(commit_data)
141
142
commit_data.repo_name = base_route
143
commit_data.identifier = f"{base_route}/{commit_data.sha}"
144
commit_data.receive_date = datetime.now()
145
db.session.add(commit_data)
146
147
db.session.commit()
148
149
return "merge_simulator" if simulate else "merge", out, err, head_route, head_branch, base_route, base_branch, merge_exit, new_commits
150
151
152
@shared_task(ignore_result=False)
153
def copy_site(route):
154
from models import Repo
155
repo = db.session.get(Repo, route)
156
server_repo_location = os.path.join(config.REPOS_PATH, route.lstrip("/"))
157
subdomain = repo.owner.username
158
subpath = repo.name if repo.has_site != 2 else ""
159
site_location = os.path.join(config.SITE_PATH, subdomain, subpath)
160
# Get the branch to be used for the site; if it somehow doesn't exist, use the default branch.
161
branch = repo.site_branch or repo.default_branch
162
# Make a shallow clone of the repo; this prevents getting the full git database when it's not needed.
163
if os.path.isdir(site_location):
164
# Delete the old site.
165
shutil.rmtree(site_location)
166
167
common.git_command(config.SITE_PATH, b"", "clone", "--depth=1", f"--branch={branch}", os.path.join(os.getcwd(), server_repo_location), os.path.join(subdomain, subpath))
168
169
170
@shared_task(ignore_result=False)
171
def delete_site(route):
172
from models import Repo
173
repo = db.session.get(Repo, route)
174
subdomain = repo.owner.username
175
subpath = repo.name if repo.has_site != 2 else "."
176
site_location = os.path.join(config.SITE_PATH, subdomain, subpath)
177
if os.path.isdir(site_location):
178
shutil.rmtree(site_location)
179
180
# Redo the primary site.
181
primary_site = Repo.query.filter_by(owner=repo.owner, has_site=2).first()
182
if primary_site:
183
copy_site(primary_site.route)
184
185
186
@shared_task(ignore_result=False)
187
def request_email_change(username, email):
188
from models import User, EmailChangeRequest
189
user = db.session.get(User, username)
190
191
request = EmailChangeRequest(user, email)
192
193
db.session.add(request)
194
db.session.commit()
195
196
message = email_send.make_multipart_message(
197
"Email change request for {username}".format(username=username),
198
config.NOTIFICATION_EMAIL,
199
email,
200
"email-change",
201
username=username,
202
code=request.code,
203
new_email=email,
204
url="https://" if config.suggest_https else "http://" + config.BASE_DOMAIN + "/settings/confirm-email/" + request.code
205
)
206
207
with (SMTP(config.MAIL_SERVER) as mail):
208
mail.sendmail(config.NOTIFICATION_EMAIL, email, message)
209