app.py
Python script, Unicode text, UTF-8 text executable
1__version__ = "0.4.0" 2 3import os 4import shutil 5import random 6import subprocess 7import platform 8 9import PIL 10import git 11import mimetypes 12import magic 13import flask 14import cairosvg 15import celery 16import shlex 17from functools import wraps 18from datetime import datetime 19from enum import Enum 20from cairosvg import svg2png 21from flask_sqlalchemy import SQLAlchemy 22from flask_bcrypt import Bcrypt 23from markupsafe import escape, Markup 24from flask_migrate import Migrate 25from PIL import Image 26from flask_httpauth import HTTPBasicAuth 27import config 28import markdown 29from common import git_command 30from flask_babel import Babel, gettext, ngettext, force_locale 31from jinja2_fragments.flask import render_block 32 33import logging 34 35 36class No304(logging.Filter): 37def filter(self, record): 38return not record.getMessage().strip().endswith("304 -") 39 40 41logging.getLogger("werkzeug").addFilter(No304()) 42 43_ = gettext 44n_ = ngettext 45 46app = flask.Flask(__name__) 47app.config.from_mapping( 48CELERY=dict( 49broker_url=config.REDIS_URI, 50result_backend=config.REDIS_URI, 51task_ignore_result=True, 52), 53) 54 55auth = HTTPBasicAuth() 56 57app.config["SQLALCHEMY_DATABASE_URI"] = config.DB_URI 58app.config["SECRET_KEY"] = config.DB_PASSWORD 59app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False 60app.config["BABEL_TRANSLATION_DIRECTORIES"] = "i18n" 61app.config["MAX_CONTENT_LENGTH"] = config.MAX_PAYLOAD_SIZE 62app.config["SESSION_COOKIE_SAMESITE"] = "Lax" 63app.config["SESSION_COOKIE_SECURE"] = config.suggest_https # only send cookies over HTTPS if the server is configured for it 64app.config["SESSION_COOKIE_HTTPONLY"] = True # don't allow JS to access the cookie 65if config.restrict_cookie_domain: 66app.config["SESSION_COOKIE_DOMAIN"] = config.BASE_DOMAIN # don't share across subdomains, since user content is hosted there 67 68db = SQLAlchemy(app) 69bcrypt = Bcrypt(app) 70migrate = Migrate(app, db) 71 72from misc_utils import * 73 74import git_http 75import api 76import jinja_utils 77import celery_tasks 78from celery import Celery, Task 79import celery_integration 80import pathlib 81 82from models import * 83 84babel = Babel(app) 85 86 87def get_locale(): 88if flask.request.cookies.get("language"): 89return flask.request.cookies.get("language") 90return flask.request.accept_languages.best_match(config.available_locales) 91 92 93babel.init_app(app, locale_selector=get_locale) 94 95with app.app_context(): 96locale_names = {} 97for language in config.available_locales: 98with force_locale(language): 99# NOTE: Translate this to the language's name in that language, for example in French you would use français 100locale_names[language] = gettext("English") 101 102worker = celery_integration.init_celery_app(app) 103 104repositories = flask.Blueprint("repository", __name__, template_folder="templates/repository/") 105 106app.jinja_env.add_extension("jinja2.ext.do") 107app.jinja_env.add_extension("jinja2.ext.loopcontrols") 108app.jinja_env.add_extension("jinja2.ext.debug") 109 110 111@app.context_processor 112def default(): 113username = flask.session.get("username") 114 115user_object = User.query.filter_by(username=username).first() 116 117return { 118"logged_in_user": username, 119"user_object": user_object, 120"Notification": Notification, 121"unread": UserNotification.query.filter_by(user_username=username).filter( 122UserNotification.attention_level > 0).count(), 123"config": config, 124"Markup": Markup, 125"locale_names": locale_names, 126"set": set, # since using {} is impossible in Jinja 127"request": flask.request, 128"get_visibility": get_visibility, 129"get_permission_level": get_permission_level, 130} 131 132 133@app.route("/") 134def main(): 135if flask.session.get("username"): 136return flask.render_template("home.html") 137else: 138return flask.render_template("no-home.html") 139 140 141@app.route("/userstyle") 142def userstyle(): 143if flask.session.get("username") and os.path.exists( 144os.path.join(config.REPOS_PATH, flask.session.get("username"), ".config", 145"theme.css")): 146return flask.send_from_directory( 147os.path.join(config.REPOS_PATH, flask.session.get("username"), ".config"), 148"theme.css") 149else: 150return flask.Response("", mimetype="text/css") 151 152 153@app.route("/about/") 154def about(): 155return flask.render_template("about.html", platform=platform, version=__version__) 156 157 158@app.route("/search") 159def search(): 160query = flask.request.args.get("q") 161page_number = flask.request.args.get("page", 1, type=int) 162if flask.session.get("username"): 163default_page_length = db.session.get(User, flask.session.get("username")).default_page_length 164else: 165default_page_length = 16 166page_length = flask.request.args.get("per_page", default_page_length, type=int) 167if not query: 168flask.abort(400) 169 170results = Repo.query.filter(Repo.name.ilike(f"%{query}%")).filter_by(visibility=2).paginate( 171page=page_number, per_page=page_length) 172 173if results.has_next: 174next_page = results.next_num 175else: 176next_page = None 177 178if results.has_prev: 179prev_page = results.prev_num 180else: 181prev_page = None 182 183return flask.render_template("search.html", results=results, query=query, 184page_number=page_number, 185page_length=page_length, 186next_page=next_page, 187prev_page=prev_page, 188num_pages=results.pages) 189 190 191@app.route("/language", methods=["POST"]) 192def set_locale(): 193response = flask.redirect(flask.request.referrer if flask.request.referrer else "/", 194code=303) 195if not flask.request.form.get("language"): 196response.delete_cookie("language") 197else: 198response.set_cookie("language", flask.request.form.get("language")) 199 200return response 201 202 203@app.route("/cookie-dismiss") 204def dismiss_banner(): 205response = flask.redirect(flask.request.referrer if flask.request.referrer else "/", 206code=303) 207response.set_cookie("cookie-banner", "1") 208return response 209 210 211@app.route("/help/") 212def help_redirect(): 213return flask.redirect(config.help_url, code=302) 214 215 216@app.route("/settings/") 217def settings(): 218if not flask.session.get("username"): 219flask.abort(401) 220user = User.query.filter_by(username=flask.session.get("username")).first() 221 222return flask.render_template("user-settings.html", user=user) 223 224 225@app.route("/settings/confirm-email/<code>") 226def confirm_email(code): 227request = EmailChangeRequest.query.filter_by(code=code).first() 228if not request: 229flask.abort(404) 230 231user = db.session.get(User, request.user_username) 232user.email = request.new_email 233db.session.delete(request) 234db.session.commit() 235 236return flask.redirect("/settings", code=303) 237 238 239@app.route("/settings/profile", methods=["POST"]) 240def settings_profile(): 241user = User.query.filter_by(username=flask.session.get("username")).first() 242 243user.display_name = flask.request.form["displayname"] 244user.URL = flask.request.form["url"] 245user.company = flask.request.form["company"] 246user.company_URL = flask.request.form["companyurl"] 247if not flask.request.form.get("email"): 248# Deleting the email can be instant; no need to confirm 249user.email = "" 250elif flask.request.form.get("email") != user.email: 251# Changing the email requires confirmation from the address holder 252celery_tasks.request_email_change.delay(user.username, flask.request.form["email"]) 253user.location = flask.request.form["location"] 254user.show_mail = True if flask.request.form.get("showmail") else False 255user.bio = flask.request.form.get("bio") 256 257db.session.commit() 258 259flask.flash( 260Markup("<iconify-icon icon='mdi:check'></iconify-icon>" + _("Settings saved")), 261category="success") 262return flask.redirect(f"/{flask.session.get('username')}", code=303) 263 264 265@app.route("/settings/preferences", methods=["POST"]) 266def settings_prefs(): 267user = User.query.filter_by(username=flask.session.get("username")).first() 268 269user.default_page_length = int(flask.request.form["page_length"]) 270user.max_post_nesting = int(flask.request.form["max_post_nesting"]) 271 272db.session.commit() 273 274flask.flash( 275Markup("<iconify-icon icon='mdi:check'></iconify-icon>" + _("Settings saved")), 276category="success") 277return flask.redirect(f"/{flask.session.get('username')}", code=303) 278 279 280@app.route("/favourites/", methods=["GET", "POST"]) 281def favourites(): 282if not flask.session.get("username"): 283flask.abort(401) 284if flask.request.method == "GET": 285relationships = RepoFavourite.query.filter_by( 286user_username=flask.session.get("username")) 287 288return flask.render_template("favourites.html", favourites=relationships) 289 290 291@app.route("/favourites/<int:id>", methods=["POST"]) 292def favourite_edit(id): 293if not flask.session.get("username"): 294flask.abort(401) 295favourite = db.session.get(RepoFavourite, id) 296if favourite.user_username != flask.session.get("username"): 297flask.abort(403) 298data = flask.request.form 299favourite.notify_commit = js_to_bool(data.get("commit")) 300favourite.notify_forum = js_to_bool(data.get("forum")) 301favourite.notify_pr = js_to_bool(data.get("pull_request")) 302favourite.notify_admin = js_to_bool(data.get("administrative")) 303db.session.commit() 304return flask.render_template_string( 305""" 306<tr hx-post="/favourites/{{ favourite.id }}" hx-trigger="change" hx-include="#commit-{{ favourite.id }}, #forum-{{ favourite.id }}, #pull_request-{{ favourite.id }}, #administrative-{{ favourite.id }}" hx-headers='{"Content-Type": "application/json"}' hx-swap="outerHTML"> 307<td><a href="{{ favourite.repo.route }}">{{ favourite.repo.owner.username }}/{{ favourite.repo.name }}</a></td> 308<td style="text-align: center;"><input type="checkbox" name="commit" id="commit-{{ favourite.id }}" value="true" {% if favourite.notify_commit %}checked{% endif %}></td> 309<td style="text-align: center;"><input type="checkbox" name="forum" id="forum-{{ favourite.id }}" value="true" {% if favourite.notify_forum %}checked{% endif %}></td> 310<td style="text-align: center;"><input type="checkbox" name="pull_request" id="pull_request-{{ favourite.id }}" value="true" {% if favourite.notify_pr %}checked{% endif %}></td> 311<td style="text-align: center;"><input type="checkbox" name="administrative" id="administrative-{{ favourite.id }}" value="true" {% if favourite.notify_admin %}checked{% endif %}></td> 312</tr> 313""", 314favourite=favourite 315) 316 317 318@app.route("/notifications/", methods=["GET", "POST"]) 319def notifications(): 320if not flask.session.get("username"): 321flask.abort(401) 322if flask.request.method == "GET": 323page_number = flask.request.args.get("page", 1, type=int) 324if flask.session.get("username"): 325default_page_length = db.session.get(User, flask.session.get( 326"username")).default_page_length 327else: 328default_page_length = 16 329page_length = flask.request.args.get("per_page", default_page_length, type=int) 330 331results = UserNotification.query.filter_by( 332user_username=flask.session.get("username")).order_by(UserNotification.id.desc()).paginate( 333page=page_number, per_page=page_length) 334 335if results.has_next: 336next_page = results.next_num 337else: 338next_page = None 339 340if results.has_prev: 341prev_page = results.prev_num 342else: 343prev_page = None 344 345return flask.render_template("notifications.html", 346notifications=results, 347db=db, Commit=Commit, Post=Post, PullRequest=PullRequest, 348page_number=page_number, 349page_length=page_length, 350next_page=next_page, 351prev_page=prev_page, 352num_pages=results.pages 353) 354 355 356@app.route("/notifications/<int:notification_id>/read", methods=["POST"]) 357def mark_read(notification_id): 358if not flask.session.get("username"): 359flask.abort(401) 360notification = UserNotification.query.filter_by(id=notification_id).first() 361if notification.user_username != flask.session.get("username"): 362flask.abort(403) 363notification.mark_read() 364db.session.commit() 365return flask.render_template_string( 366"<button hx-post='/notifications/{{ notification.id }}/unread' hx-swap='outerHTML'>Mark as unread</button>", 367notification=notification), 200 368 369 370@app.route("/notifications/<int:notification_id>/unread", methods=["POST"]) 371def mark_unread(notification_id): 372if not flask.session.get("username"): 373flask.abort(401) 374notification = UserNotification.query.filter_by(id=notification_id).first() 375if notification.user_username != flask.session.get("username"): 376flask.abort(403) 377notification.mark_unread() 378db.session.commit() 379return flask.render_template_string( 380"<button hx-post='/notifications/{{ notification.id }}/read' hx-swap='outerHTML'>Mark as read</button>", 381notification=notification), 200 382 383 384@app.route("/notifications/mark-all-read", methods=["POST"]) 385def mark_all_read(): 386if not flask.session.get("username"): 387flask.abort(401) 388 389notifications = UserNotification.query.filter_by( 390user_username=flask.session.get("username")) 391for notification in notifications: 392notification.mark_read() 393db.session.commit() 394return flask.redirect("/notifications/", code=303) 395 396 397@app.route("/accounts/", methods=["GET", "POST"]) 398def login(): 399if flask.request.method == "GET": 400return flask.render_template("login.html") 401else: 402if "login" in flask.request.form: 403username = flask.request.form["username"] 404password = flask.request.form["password"] 405 406user = User.query.filter_by(username=username).first() 407 408if user and bcrypt.check_password_hash(user.password_hashed, password): 409flask.session["username"] = user.username 410flask.flash( 411Markup("<iconify-icon icon='mdi:account'></iconify-icon>" + _( 412"Successfully logged in as {username}").format( 413username=username)), 414category="success") 415return flask.redirect("/", code=303) 416elif not user: 417flask.flash(Markup( 418"<iconify-icon icon='mdi:account-question'></iconify-icon>" + _( 419"User not found")), 420category="alert") 421return flask.render_template("login.html") 422else: 423flask.flash(Markup( 424"<iconify-icon icon='mdi:account-question'></iconify-icon>" + _( 425"Invalid password")), 426category="error") 427return flask.render_template("login.html") 428if "signup" in flask.request.form: 429username = flask.request.form["username"] 430password = flask.request.form["password"] 431password2 = flask.request.form["password2"] 432email = flask.request.form.get("email") 433email2 = flask.request.form.get("email2") # repeat email is a honeypot 434name = flask.request.form.get("name") 435 436if not only_chars(username, 437"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-"): 438flask.flash(Markup( 439_("Usernames may only contain Latin alphabet, numbers and '-'")), 440category="error") 441return flask.render_template("login.html") 442if "--" in username: 443flask.flash(Markup( 444_("Usernames may not contain consecutive hyphens")), 445category="error") 446return flask.render_template("login.html") 447if username.startswith("-") or username.endswith("-"): 448flask.flash(Markup( 449_("Usernames may not start or end with a hyphen")), 450category="error") 451return flask.render_template("login.html") 452if username in config.RESERVED_NAMES: 453flask.flash( 454Markup( 455_("Sorry, {username} is a system path").format( 456username=username)), 457category="error") 458return flask.render_template("login.html") 459 460if not username.islower(): 461if not name: # infer display name from the wanted username if not customised 462display_name = username 463username = username.lower() 464flask.flash(Markup( 465_("Usernames must be lowercase, so it's been converted automatically")), 466category="info") 467 468user_check = User.query.filter_by(username=username).first() 469if user_check or email2: # make the honeypot look like a normal error 470flask.flash( 471Markup( 472_( 473"The username {username} is taken").format( 474username=username)), 475category="error") 476return flask.render_template("login.html") 477 478if password2 != password: 479flask.flash(Markup(_( 480"Make sure the passwords match")), 481category="error") 482return flask.render_template("login.html") 483 484user = User(username, password, email, name) 485db.session.add(user) 486db.session.commit() 487flask.session["username"] = user.username 488flask.flash(Markup( 489_( 490"Successfully created and logged in as {username}").format( 491username=username)), 492category="success") 493 494notification = Notification({"type": "welcome"}) 495db.session.add(notification) 496db.session.commit() 497 498return flask.redirect("/", code=303) 499 500 501@app.route("/newrepo/", methods=["GET", "POST"]) 502def new_repo(): 503if not flask.session.get("username"): 504flask.abort(401) 505if flask.request.method == "GET": 506return flask.render_template("new-repo.html") 507else: 508name = flask.request.form["name"] 509visibility = int(flask.request.form["visibility"]) 510 511if not only_chars(name, 512"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_."): 513flask.flash(Markup( 514"<iconify-icon icon='mdi:error'></iconify-icon>" + _( 515"Repository names may only contain Latin alphabet, numbers, '-', '_' and '.'")), 516category="error") 517return flask.render_template("new-repo.html") 518 519user = User.query.filter_by(username=flask.session.get("username")).first() 520 521repo = Repo(user, name, visibility) 522db.session.add(repo) 523db.session.commit() 524 525flask.flash(Markup(_("Successfully created repository {name}").format(name=name)), 526category="success") 527return flask.redirect(repo.route, code=303) 528 529 530@app.route("/logout") 531def logout(): 532flask.session.clear() 533flask.flash(Markup( 534"<iconify-icon icon='mdi:account'></iconify-icon>" + _("Successfully logged out")), 535category="info") 536return flask.redirect("/", code=303) 537 538 539@app.route("/<username>/", methods=["GET", "POST"]) 540def user_profile(username): 541if db.session.get(User, username) is None: 542flask.abort(404) 543old_relationship = UserFollow.query.filter_by( 544follower_username=flask.session.get("username"), 545followed_username=username).first() 546if flask.request.method == "GET": 547user = User.query.filter_by(username=username).first() 548match flask.request.args.get("action"): 549case "repositories": 550repos = Repo.query.filter_by(owner_name=username, visibility=2) 551return flask.render_template("user-profile-repositories.html", user=user, 552repos=repos, 553relationship=old_relationship) 554case "followers": 555return flask.render_template("user-profile-followers.html", user=user, 556relationship=old_relationship) 557case "follows": 558return flask.render_template("user-profile-follows.html", user=user, 559relationship=old_relationship) 560case _: 561return flask.render_template("user-profile-overview.html", user=user, 562relationship=old_relationship) 563 564elif flask.request.method == "POST": 565match flask.request.args.get("action"): 566case "follow": 567if username == flask.session.get("username"): 568flask.abort(403) 569if old_relationship: 570db.session.delete(old_relationship) 571else: 572relationship = UserFollow( 573flask.session.get("username"), 574username 575) 576db.session.add(relationship) 577db.session.commit() 578 579user = db.session.get(User, username) 580author = db.session.get(User, flask.session.get("username")) 581notification = Notification({"type": "update", "version": "0.0.0"}) 582db.session.add(notification) 583db.session.commit() 584 585db.session.commit() 586return flask.redirect("?", code=303) 587 588 589@app.route("/<username>/<repository>/") 590def repository_index(username, repository): 591return flask.redirect("./tree", code=302) 592 593 594@app.route("/info/<username>/avatar") 595def user_avatar(username): 596server_userdata_location = os.path.join(config.USERDATA_PATH, username) 597if not os.path.exists(server_userdata_location): 598return flask.render_template("errors/not-found.html"), 404 599 600return flask.send_from_directory(server_userdata_location, "avatar.png") 601 602 603@app.route("/info/<username>/avatar", methods=["POST"]) 604def user_avatar_upload(username): 605server_userdata_location = os.path.join(config.USERDATA_PATH, username) 606 607if not os.path.exists(server_userdata_location): 608flask.abort(404) 609if not flask.session.get("username") == username: 610flask.abort(403) 611 612# Convert image to PNG 613try: 614image = Image.open(flask.request.files["avatar"]) 615except PIL.UnidentifiedImageError: 616flask.abort(400) 617image.save(os.path.join(server_userdata_location, "avatar.png")) 618 619return flask.redirect(f"/{username}", code=303) 620 621 622@app.route("/<username>/<repository>/raw/<branch>/<path:subpath>") 623def repository_raw(username, repository, branch, subpath): 624server_repo_location = os.path.join(config.REPOS_PATH, username, repository) 625if not os.path.exists(server_repo_location): 626flask.abort(404) 627if not (get_visibility(username, repository) or get_permission_level( 628flask.session.get("username"), username, 629repository) is not None): 630flask.abort(403) 631 632if not os.path.exists(server_repo_location): 633return flask.render_template("errors/not-found.html"), 404 634 635repo = git.Repo(server_repo_location) 636repo_data = Repo.query.filter_by(route=f"/{username}/{repository}").first() 637if not repo_data.default_branch: 638if repo.heads: 639repo_data.default_branch = repo.heads[0].name 640else: 641return flask.render_template("empty.html", 642remote=f"http://{config.BASE_DOMAIN}/git/{username}/{repository}"), 200 643if not branch: 644branch = repo_data.default_branch 645return flask.redirect(f"./{branch}", code=302) 646 647if branch.startswith("tag:"): 648ref = f"tags/{branch[4:]}" 649elif branch.startswith("~"): 650ref = branch[1:] 651else: 652ref = f"heads/{branch}" 653 654ref = ref.replace("~", "/") # encode slashes for URL support 655 656try: 657repo.git.checkout("-f", ref) 658except git.exc.GitCommandError: 659return flask.render_template("errors/not-found.html"), 404 660 661return flask.send_from_directory(config.REPOS_PATH, 662os.path.join(username, repository, subpath)) 663 664 665@repositories.route("/<username>/<repository>/tree/", defaults={"branch": None, "subpath": ""}) 666@repositories.route("/<username>/<repository>/tree/<branch>/", defaults={"subpath": ""}) 667@repositories.route("/<username>/<repository>/tree/<branch>/<path:subpath>") 668def repository_tree(username, repository, branch, subpath): 669server_repo_location = os.path.join(config.REPOS_PATH, username, repository) 670if not os.path.exists(server_repo_location): 671flask.abort(404) 672if not (get_visibility(username, repository) or get_permission_level( 673flask.session.get("username"), username, 674repository) is not None): 675flask.abort(403) 676 677repo = git.Repo(server_repo_location) 678repo_data = Repo.query.filter_by(route=f"/{username}/{repository}").first() 679if not repo_data.default_branch: 680if repo.heads: 681repo_data.default_branch = repo.heads[0].name 682else: 683return flask.render_template("empty.html", 684remote=f"{config.www_protocol}://{config.BASE_DOMAIN}/git/{username}/{repository}"), 200 685if not branch: 686branch = repo_data.default_branch 687return flask.redirect(f"./{branch}", code=302) 688 689if branch.startswith("tag:"): 690ref = f"tags/{branch[4:]}" 691elif branch.startswith("~"): 692ref = branch[1:] 693else: 694ref = f"heads/{branch}" 695 696ref = ref.replace("~", "/") # encode slashes for URL support 697 698try: 699repo.git.checkout("-f", ref) 700except git.exc.GitCommandError: 701return flask.render_template("errors/not-found.html"), 404 702 703branches = repo.heads 704 705all_refs = [] 706for ref in repo.heads: 707all_refs.append((ref, "head")) 708for ref in repo.tags: 709all_refs.append((ref, "tag")) 710 711if os.path.isdir(os.path.join(server_repo_location, subpath)): 712files = [] 713blobs = [] 714 715for entry in os.listdir(os.path.join(server_repo_location, subpath)): 716if not os.path.basename(entry) == ".git": 717files.append(os.path.join(subpath, entry)) 718 719infos = [] 720 721for file in files: 722path = os.path.join(server_repo_location, file) 723mimetype = guess_mime(path) 724 725text = git_command(server_repo_location, None, "log", "--format='%H\n'", 726shlex.quote(file)).decode() 727 728sha = text.split("\n")[0] 729identifier = f"/{username}/{repository}/{sha}" 730 731last_commit = db.session.get(Commit, identifier) 732 733info = { 734"name": os.path.basename(file), 735"serverPath": path, 736"relativePath": file, 737"link": os.path.join(f"/{username}/{repository}/tree/{branch}/", file), 738"size": human_size(os.path.getsize(path)), 739"mimetype": f"{mimetype}{f' ({mimetypes.guess_type(path)[1]})' if mimetypes.guess_type(path)[1] else ''}", 740"commit": last_commit, 741"shaSize": 7, 742} 743 744special_icon = config.match_icon(os.path.basename(file)) 745if special_icon: 746info["icon"] = special_icon 747elif os.path.isdir(path): 748info["icon"] = config.folder_icon 749info["size"] = _("{} files").format(len(os.listdir(path))) 750elif mimetypes.guess_type(path)[0] in config.file_icons: 751info["icon"] = config.file_icons[mimetypes.guess_type(path)[0]] 752else: 753info["icon"] = config.unknown_icon 754 755if os.path.isdir(path): 756infos.insert(0, info) 757else: 758infos.append(info) 759 760return flask.render_template( 761"repo-tree.html", 762username=username, 763repository=repository, 764files=infos, 765subpath=os.path.join("/", subpath), 766branches=all_refs, 767current=branch, 768remote=f"http{'s' if config.suggest_https else ''}://{config.BASE_DOMAIN}/git/{username}/{repository}", 769is_favourite=get_favourite(flask.session.get("username"), username, repository), 770repo_data=repo_data, 771) 772else: 773path = os.path.join(server_repo_location, subpath) 774 775if not os.path.exists(path): 776return flask.render_template("errors/not-found.html"), 404 777 778mimetype = guess_mime(path) 779mode = mimetype.split("/", 1)[0] 780size = human_size(os.path.getsize(path)) 781 782special_icon = config.match_icon(os.path.basename(path)) 783if special_icon: 784icon = special_icon 785elif os.path.isdir(path): 786icon = config.folder_icon 787elif mimetypes.guess_type(path)[0] in config.file_icons: 788icon = config.file_icons[mimetypes.guess_type(path)[0]] 789else: 790icon = config.unknown_icon 791 792contents = None 793if mode == "text": 794contents = convert_to_html(path) 795 796return flask.render_template( 797"repo-file.html", 798username=username, 799repository=repository, 800file=os.path.join(f"/{username}/{repository}/raw/{branch}/", subpath), 801branches=all_refs, 802current=branch, 803mode=mode, 804mimetype=mimetype, 805detailedtype=magic.from_file(path), 806size=size, 807icon=icon, 808subpath=os.path.join("/", subpath), 809extension=pathlib.Path(path).suffix, 810basename=os.path.basename(path), 811contents=contents, 812remote=f"http{'s' if config.suggest_https else ''}://{config.BASE_DOMAIN}/git/{username}/{repository}", 813is_favourite=get_favourite(flask.session.get("username"), username, repository), 814repo_data=repo_data, 815) 816 817 818@repositories.route("/<username>/<repository>/commit/<sha>") 819def repository_commit(username, repository, sha): 820server_repo_location = os.path.join(config.REPOS_PATH, username, repository) 821if not os.path.exists(server_repo_location): 822flask.abort(404) 823if not (get_visibility(username, repository) or get_permission_level( 824flask.session.get("username"), username, 825repository) is not None): 826flask.abort(403) 827 828if not os.path.exists(server_repo_location): 829return flask.render_template("errors/not-found.html"), 404 830 831repo = git.Repo(server_repo_location) 832repo_data = Repo.query.filter_by(route=f"/{username}/{repository}").first() 833 834files = git_command(os.path.join(server_repo_location, ".git"), None, "diff-tree", "-r", 835"--name-only", "--no-commit-id", sha).decode().split("\n")[:-1] 836 837return flask.render_template( 838"repo-commit.html", 839username=username, 840repository=repository, 841remote=f"http{'s' if config.suggest_https else ''}://{config.BASE_DOMAIN}/git/{username}/{repository}", 842is_favourite=get_favourite(flask.session.get("username"), username, repository), 843diff={file: git_command(os.path.join(server_repo_location, ".git"), None, "diff", 844str(sha) + "^!", "--", file).decode().split("\n") for 845file in files}, 846data=db.session.get(Commit, f"/{username}/{repository}/{sha}"), 847repo_data=repo_data, 848comment_query=Comment.query, 849permission_level=get_permission_level(flask.session.get("username"), username, repository), 850) 851 852 853@repositories.route("/<username>/<repository>/commit/<sha>/add_comment", methods=["POST"]) 854def repository_commit_add_comment(username, repository, sha): 855server_repo_location = os.path.join(config.REPOS_PATH, username, repository) 856if not os.path.exists(server_repo_location): 857flask.abort(404) 858if not (get_visibility(username, repository) or get_permission_level( 859flask.session.get("username"), username, 860repository) is not None): 861flask.abort(403) 862 863comment = Comment( 864db.session.get(User, flask.session.get("username")), 865db.session.get(Repo, f"/{username}/{repository}"), 866db.session.get(Commit, f"/{username}/{repository}/{sha}"), 867flask.request.form["comment"], 868flask.request.form["file"], 869flask.request.form["line"], 870) 871 872db.session.add(comment) 873db.session.commit() 874 875return flask.redirect( 876flask.url_for(".repository_commit", username=username, repository=repository, sha=sha), 877code=303 878) 879 880 881@repositories.route("/<username>/<repository>/commit/<sha>/delete_comment/<int:id>", methods=["POST"]) 882def repository_commit_delete_comment(username, repository, sha, id): 883repo_data = Repo.query.filter_by(route=f"/{username}/{repository}").first() 884comment = Comment.query.filter_by(identifier=f"/{username}/{repository}/{id}").first() 885commit = Commit.query.filter_by(identifier=f"/{username}/{repository}/{sha}").first() 886if ( 887comment.owner.username == flask.session.get("username") 888or get_permission_level(flask.session.get("username"), username, repository) >= 2 889or comment.commit.owner.username == flask.session.get("username") 890): 891db.session.delete(comment) 892db.session.commit() 893 894return flask.redirect( 895flask.url_for(".repository_commit", username=username, repository=repository, sha=sha), 896code=303 897) 898 899 900@repositories.route("/<username>/<repository>/commit/<sha>/resolve_comment/<int:id>", methods=["POST"]) 901def repository_commit_resolve_comment(username, repository, sha, id): 902comment = Comment.query.filter_by(identifier=f"/{username}/{repository}/{id}").first() 903if ( 904comment.commit.owner.username == flask.session.get("username") 905or get_permission_level(flask.session.get("username"), username, repository) >= 2 906or comment.owner.username == flask.session.get("username") 907): 908comment.state = int(not comment.state) 909db.session.commit() 910 911return flask.redirect( 912flask.url_for(".repository_commit", username=username, repository=repository, sha=sha), 913code=303 914) 915 916 917@repositories.route("/<username>/<repository>/forum/") 918def repository_forum(username, repository): 919server_repo_location = os.path.join(config.REPOS_PATH, username, repository) 920if not os.path.exists(server_repo_location): 921flask.abort(404) 922if not (get_visibility(username, repository) or get_permission_level( 923flask.session.get("username"), username, 924repository) is not None): 925flask.abort(403) 926 927if not os.path.exists(server_repo_location): 928return flask.render_template("errors/not-found.html"), 404 929 930repo = git.Repo(server_repo_location) 931repo_data = Repo.query.filter_by(route=f"/{username}/{repository}").first() 932user = User.query.filter_by(username=flask.session.get("username")).first() 933relationships = RepoAccess.query.filter_by(repo=repo_data) 934user_relationship = RepoAccess.query.filter_by(repo=repo_data, user=user).first() 935 936return flask.render_template( 937"repo-forum.html", 938username=username, 939repository=repository, 940repo_data=repo_data, 941relationships=relationships, 942repo=repo, 943user_relationship=user_relationship, 944Post=Post, 945remote=f"http{'s' if config.suggest_https else ''}://{config.BASE_DOMAIN}/git/{username}/{repository}", 946is_favourite=get_favourite(flask.session.get("username"), username, repository), 947default_branch=repo_data.default_branch 948) 949 950 951@repositories.route("/<username>/<repository>/forum/topic/<int:id>") 952def repository_forum_topic(username, repository, id): 953server_repo_location = os.path.join(config.REPOS_PATH, username, repository) 954if not os.path.exists(server_repo_location): 955flask.abort(404) 956if not (get_visibility(username, repository) or get_permission_level( 957flask.session.get("username"), username, 958repository) is not None): 959flask.abort(403) 960 961if not os.path.exists(server_repo_location): 962return flask.render_template("errors/not-found.html"), 404 963 964repo_data = Repo.query.filter_by(route=f"/{username}/{repository}").first() 965user = User.query.filter_by(username=flask.session.get("username")).first() 966relationships = RepoAccess.query.filter_by(repo=repo_data) 967user_relationship = RepoAccess.query.filter_by(repo=repo_data, user=user).first() 968 969post = Post.query.filter_by(id=id).first() 970 971return flask.render_template( 972"repo-topic.html", 973username=username, 974repository=repository, 975repo_data=repo_data, 976relationships=relationships, 977user_relationship=user_relationship, 978post=post, 979remote=f"http{'s' if config.suggest_https else ''}://{config.BASE_DOMAIN}/git/{username}/{repository}", 980is_favourite=get_favourite(flask.session.get("username"), username, repository), 981default_branch=repo_data.default_branch 982) 983 984 985@repositories.route("/<username>/<repository>/forum/new", methods=["POST", "GET"]) 986def repository_forum_new(username, repository): 987server_repo_location = os.path.join(config.REPOS_PATH, username, repository) 988if not os.path.exists(server_repo_location): 989flask.abort(404) 990if not ((flask.session.get("username") and get_visibility(username, repository)) or get_permission_level( 991flask.session.get("username"), username, 992repository) is not None): 993flask.abort(403) 994 995if not os.path.exists(server_repo_location): 996return flask.render_template("errors/not-found.html"), 404 997 998repo = git.Repo(server_repo_location) 999repo_data = Repo.query.filter_by(route=f"/{username}/{repository}").first() 1000user = User.query.filter_by(username=flask.session.get("username")).first() 1001relationships = RepoAccess.query.filter_by(repo=repo_data) 1002user_relationship = RepoAccess.query.filter_by(repo=repo_data, user=user).first() 1003 1004post = Post(user, repo_data, None, flask.request.form["subject"], 1005flask.request.form["message"]) 1006 1007db.session.add(post) 1008db.session.commit() 1009 1010return flask.redirect( 1011flask.url_for(".repository_forum_thread", username=username, repository=repository, 1012post_id=post.number), 1013code=303) 1014 1015 1016@repositories.route("/<username>/<repository>/forum/<int:post_id>") 1017def repository_forum_thread(username, repository, post_id): 1018server_repo_location = os.path.join(config.REPOS_PATH, username, repository) 1019if not os.path.exists(server_repo_location): 1020flask.abort(404) 1021if not (get_visibility(username, repository) or get_permission_level( 1022flask.session.get("username"), username, 1023repository) is not None): 1024flask.abort(403) 1025 1026if not os.path.exists(server_repo_location): 1027return flask.render_template("errors/not-found.html"), 404 1028 1029repo = git.Repo(server_repo_location) 1030repo_data = Repo.query.filter_by(route=f"/{username}/{repository}").first() 1031user = User.query.filter_by(username=flask.session.get("username")).first() 1032relationships = RepoAccess.query.filter_by(repo=repo_data) 1033user_relationship = RepoAccess.query.filter_by(repo=repo_data, user=user).first() 1034 1035if user: 1036max_post_nesting = user.max_post_nesting 1037else: 1038max_post_nesting = 2 1039 1040return flask.render_template( 1041"repo-forum-thread.html", 1042username=username, 1043repository=repository, 1044repo_data=repo_data, 1045relationships=relationships, 1046repo=repo, 1047Post=Post, 1048user_relationship=user_relationship, 1049post_id=post_id, 1050max_post_nesting=max_post_nesting, 1051remote=f"http{'s' if config.suggest_https else ''}://{config.BASE_DOMAIN}/git/{username}/{repository}", 1052is_favourite=get_favourite(flask.session.get("username"), username, repository), 1053parent=Post.query.filter_by(repo=repo_data, number=post_id).first(), 1054has_permission=not ((not get_permission_level(flask.session.get("username"), username, 1055repository)) and db.session.get(Post, 1056f"/{username}/{repository}/{post_id}").owner.username != flask.session.get("username")), 1057) 1058 1059 1060@repositories.route("/<username>/<repository>/forum/<int:post_id>/change-state", 1061methods=["POST"]) 1062def repository_forum_change_state(username, repository, post_id): 1063server_repo_location = os.path.join(config.REPOS_PATH, username, repository) 1064if not os.path.exists(server_repo_location): 1065flask.abort(404) 1066if (not get_permission_level(flask.session.get("username"), username, repository)) and db.session.get(Post, f"/{username}/{repository}/{post_id}").owner.username != flask.session.get("username"): 1067flask.abort(403) 1068 1069repo = git.Repo(server_repo_location) 1070repo_data = Repo.query.filter_by(route=f"/{username}/{repository}").first() 1071user = User.query.filter_by(username=flask.session.get("username")).first() 1072relationships = RepoAccess.query.filter_by(repo=repo_data) 1073user_relationship = RepoAccess.query.filter_by(repo=repo_data, user=user).first() 1074 1075post = Post.query.filter_by(identifier=f"/{username}/{repository}/{post_id}").first() 1076 1077if not post: 1078flask.abort(404) 1079 1080post.state = int(flask.request.form["new-state"]) 1081 1082db.session.commit() 1083 1084return flask.redirect( 1085flask.url_for(".repository_forum_thread", username=username, repository=repository, 1086post_id=post_id), 1087code=303) 1088 1089 1090@repositories.route("/<username>/<repository>/forum/<int:post_id>/reply", methods=["POST"]) 1091def repository_forum_reply(username, repository, post_id): 1092server_repo_location = os.path.join(config.REPOS_PATH, username, repository) 1093if not os.path.exists(server_repo_location): 1094flask.abort(404) 1095if not ((flask.session.get("username") and get_visibility(username, repository)) or get_permission_level( 1096flask.session.get("username"), username, 1097repository) is not None): 1098flask.abort(403) 1099 1100if not os.path.exists(server_repo_location): 1101return flask.render_template("errors/not-found.html"), 404 1102 1103repo = git.Repo(server_repo_location) 1104repo_data = Repo.query.filter_by(route=f"/{username}/{repository}").first() 1105user = User.query.filter_by(username=flask.session.get("username")).first() 1106relationships = RepoAccess.query.filter_by(repo=repo_data) 1107user_relationship = RepoAccess.query.filter_by(repo=repo_data, user=user).first() 1108if not user: 1109flask.abort(401) 1110 1111parent = Post.query.filter_by(identifier=f"/{username}/{repository}/{post_id}").first() 1112post = Post(user, repo_data, parent, flask.request.form["subject"], 1113flask.request.form["message"]) 1114 1115db.session.add(post) 1116post.update_date() 1117db.session.commit() 1118 1119return flask.redirect( 1120flask.url_for(".repository_forum_thread", username=username, repository=repository, 1121post_id=post_id), 1122code=303) 1123 1124 1125@repositories.route("/<username>/<repository>/forum/<int:post_id>/edit", methods=["POST"]) 1126def repository_forum_edit(username, repository, post_id): 1127server_repo_location = os.path.join(config.REPOS_PATH, username, repository) 1128if not os.path.exists(server_repo_location): 1129flask.abort(404) 1130if not (get_visibility(username, repository) or get_permission_level( 1131flask.session.get("username"), username, 1132repository) is not None): 1133flask.abort(403) 1134 1135if not os.path.exists(server_repo_location): 1136return flask.render_template("errors/not-found.html"), 404 1137 1138repo = git.Repo(server_repo_location) 1139repo_data = Repo.query.filter_by(route=f"/{username}/{repository}").first() 1140user = User.query.filter_by(username=flask.session.get("username")).first() 1141relationships = RepoAccess.query.filter_by(repo=repo_data) 1142user_relationship = RepoAccess.query.filter_by(repo=repo_data, user=user).first() 1143if not user: 1144flask.abort(401) 1145post = db.session.get(Post, f"/{username}/{repository}/{post_id}") 1146if user != post.owner: 1147flask.abort(403) 1148 1149post.subject = flask.request.form["subject"] 1150post.message = flask.request.form["message"] 1151post.html = markdown.markdown2html(post.message).prettify() 1152post.update_date() 1153db.session.commit() 1154 1155return flask.redirect( 1156flask.url_for(".repository_forum_thread", username=username, repository=repository, 1157post_id=post_id), 1158code=303) 1159 1160 1161@repositories.route("/<username>/<repository>/forum/<int:post_id>/edit", methods=["GET"]) 1162def repository_forum_edit_form(username, repository, post_id): 1163server_repo_location = os.path.join(config.REPOS_PATH, username, repository) 1164if not os.path.exists(server_repo_location): 1165flask.abort(404) 1166if not (get_visibility(username, repository) or get_permission_level( 1167flask.session.get("username"), username, 1168repository) is not None): 1169flask.abort(403) 1170 1171if not os.path.exists(server_repo_location): 1172return flask.render_template("errors/not-found.html"), 404 1173 1174repo = git.Repo(server_repo_location) 1175repo_data = Repo.query.filter_by(route=f"/{username}/{repository}").first() 1176user = User.query.filter_by(username=flask.session.get("username")).first() 1177relationships = RepoAccess.query.filter_by(repo=repo_data) 1178user_relationship = RepoAccess.query.filter_by(repo=repo_data, user=user).first() 1179if not user: 1180flask.abort(401) 1181post = db.session.get(Post, f"/{username}/{repository}/{post_id}") 1182if user != post.owner: 1183flask.abort(403) 1184 1185return flask.render_template( 1186"repo-forum-edit.html", 1187username=username, 1188repository=repository, 1189repo_data=repo_data, 1190relationships=relationships, 1191repo=repo, 1192user_relationship=user_relationship, 1193post=post, 1194remote=f"http{'s' if config.suggest_https else ''}://{config.BASE_DOMAIN}/git/{username}/{repository}", 1195is_favourite=get_favourite(flask.session.get("username"), username, repository), 1196default_branch=repo_data.default_branch 1197) 1198 1199@repositories.route("/<username>/<repository>/forum/<int:post_id>/voteup", 1200defaults={"score": 1}) 1201@repositories.route("/<username>/<repository>/forum/<int:post_id>/votedown", 1202defaults={"score": -1}) 1203@repositories.route("/<username>/<repository>/forum/<int:post_id>/votes", defaults={"score": 0}) 1204def repository_forum_vote(username, repository, post_id, score): 1205server_repo_location = os.path.join(config.REPOS_PATH, username, repository) 1206if not os.path.exists(server_repo_location): 1207flask.abort(404) 1208if not (get_visibility(username, repository) or get_permission_level( 1209flask.session.get("username"), username, 1210repository) is not None): 1211flask.abort(403) 1212 1213if not os.path.exists(server_repo_location): 1214return flask.render_template("errors/not-found.html"), 404 1215 1216repo = git.Repo(server_repo_location) 1217repo_data = Repo.query.filter_by(route=f"/{username}/{repository}").first() 1218user = User.query.filter_by(username=flask.session.get("username")).first() 1219relationships = RepoAccess.query.filter_by(repo=repo_data) 1220user_relationship = RepoAccess.query.filter_by(repo=repo_data, user=user).first() 1221if not user: 1222flask.abort(401) 1223 1224post = Post.query.filter_by(identifier=f"/{username}/{repository}/{post_id}").first() 1225 1226if score: 1227old_relationship = PostVote.query.filter_by(user_username=user.username, 1228post_identifier=post.identifier).first() 1229if old_relationship: 1230if score == old_relationship.vote_score: 1231db.session.delete(old_relationship) 1232post.vote_sum -= old_relationship.vote_score 1233else: 1234post.vote_sum -= old_relationship.vote_score 1235post.vote_sum += score 1236old_relationship.vote_score = score 1237else: 1238relationship = PostVote(user, post, score) 1239post.vote_sum += score 1240db.session.add(relationship) 1241 1242db.session.commit() 1243 1244user_vote = PostVote.query.filter_by(user_username=user.username, 1245post_identifier=post.identifier).first() 1246response = flask.make_response( 1247str(post.vote_sum) + " " + str(user_vote.vote_score if user_vote else 0)) 1248response.content_type = "text/plain" 1249 1250return response 1251 1252 1253@repositories.route("/<username>/<repository>/favourite") 1254def repository_favourite(username, repository): 1255server_repo_location = os.path.join(config.REPOS_PATH, username, repository) 1256if not os.path.exists(server_repo_location): 1257flask.abort(404) 1258if not (get_visibility(username, repository) or get_permission_level( 1259flask.session.get("username"), username, 1260repository) is not None): 1261flask.abort(403) 1262 1263if not os.path.exists(server_repo_location): 1264return flask.render_template("errors/not-found.html"), 404 1265 1266repo = git.Repo(server_repo_location) 1267repo_data = Repo.query.filter_by(route=f"/{username}/{repository}").first() 1268user = User.query.filter_by(username=flask.session.get("username")).first() 1269relationships = RepoAccess.query.filter_by(repo=repo_data) 1270user_relationship = RepoAccess.query.filter_by(repo=repo_data, user=user).first() 1271if not user: 1272flask.abort(401) 1273 1274old_relationship = RepoFavourite.query.filter_by(user_username=user.username, 1275repo_route=repo_data.route).first() 1276if old_relationship: 1277db.session.delete(old_relationship) 1278else: 1279relationship = RepoFavourite(user, repo_data) 1280db.session.add(relationship) 1281 1282db.session.commit() 1283 1284return flask.redirect(flask.url_for("favourites"), code=303) 1285 1286 1287@repositories.route("/<username>/<repository>/users/", methods=["GET", "POST"]) 1288def repository_users(username, repository): 1289server_repo_location = os.path.join(config.REPOS_PATH, username, repository) 1290if not os.path.exists(server_repo_location): 1291flask.abort(404) 1292if not (get_visibility(username, repository) or get_permission_level( 1293flask.session.get("username"), username, 1294repository) is not None): 1295flask.abort(403) 1296 1297if not os.path.exists(server_repo_location): 1298return flask.render_template("errors/not-found.html"), 404 1299 1300repo = git.Repo(server_repo_location) 1301repo_data = Repo.query.filter_by(route=f"/{username}/{repository}").first() 1302user = User.query.filter_by(username=flask.session.get("username")).first() 1303relationships = RepoAccess.query.filter_by(repo=repo_data) 1304user_relationship = RepoAccess.query.filter_by(repo=repo_data, user=user).first() 1305 1306if flask.request.method == "GET": 1307return flask.render_template( 1308"repo-users.html", 1309username=username, 1310repository=repository, 1311repo_data=repo_data, 1312relationships=relationships, 1313repo=repo, 1314user_relationship=user_relationship, 1315remote=f"http{'s' if config.suggest_https else ''}://{config.BASE_DOMAIN}/git/{username}/{repository}", 1316is_favourite=get_favourite(flask.session.get("username"), username, repository) 1317) 1318else: 1319if get_permission_level(flask.session.get("username"), username, repository) != 2: 1320flask.abort(401) 1321 1322if flask.request.form.get("new-username"): 1323# Create new relationship 1324new_user = User.query.filter_by( 1325username=flask.request.form.get("new-username")).first() 1326relationship = RepoAccess(new_user, repo_data, flask.request.form.get("new-level")) 1327db.session.add(relationship) 1328db.session.commit() 1329if flask.request.form.get("update-username"): 1330# Create new relationship 1331updated_user = User.query.filter_by( 1332username=flask.request.form.get("update-username")).first() 1333relationship = RepoAccess.query.filter_by(repo=repo_data, user=updated_user).first() 1334if flask.request.form.get("update-level") == -1: 1335relationship.delete() 1336else: 1337relationship.access_level = flask.request.form.get("update-level") 1338db.session.commit() 1339 1340return flask.redirect( 1341app.url_for(".repository_users", username=username, repository=repository)) 1342 1343 1344@repositories.route("/<username>/<repository>/branches/") 1345def repository_branches(username, repository): 1346server_repo_location = os.path.join(config.REPOS_PATH, username, repository) 1347if not os.path.exists(server_repo_location): 1348flask.abort(404) 1349if not (get_visibility(username, repository) or get_permission_level( 1350flask.session.get("username"), username, 1351repository) is not None): 1352flask.abort(403) 1353 1354if not os.path.exists(server_repo_location): 1355return flask.render_template("errors/not-found.html"), 404 1356 1357repo = git.Repo(server_repo_location) 1358repo_data = Repo.query.filter_by(route=f"/{username}/{repository}").first() 1359 1360return flask.render_template( 1361"repo-branches.html", 1362username=username, 1363repository=repository, 1364repo_data=repo_data, 1365repo=repo, 1366remote=f"http{'s' if config.suggest_https else ''}://{config.BASE_DOMAIN}/git/{username}/{repository}", 1367is_favourite=get_favourite(flask.session.get("username"), username, repository) 1368) 1369 1370 1371@repositories.route("/<username>/<repository>/log/", defaults={"branch": None}) 1372@repositories.route("/<username>/<repository>/log/<branch>/") 1373def repository_log(username, repository, branch): 1374server_repo_location = os.path.join(config.REPOS_PATH, username, repository) 1375if not os.path.exists(server_repo_location): 1376flask.abort(404) 1377if not (get_visibility(username, repository) or get_permission_level( 1378flask.session.get("username"), username, 1379repository) is not None): 1380flask.abort(403) 1381 1382if not os.path.exists(server_repo_location): 1383return flask.render_template("errors/not-found.html"), 404 1384 1385repo = git.Repo(server_repo_location) 1386repo_data = Repo.query.filter_by(route=f"/{username}/{repository}").first() 1387if not repo_data.default_branch: 1388if repo.heads: 1389repo_data.default_branch = repo.heads[0].name 1390else: 1391return flask.render_template("empty.html", 1392remote=f"http{'s' if config.suggest_https else ''}://{config.BASE_DOMAIN}/git/{username}/{repository}"), 200 1393if not branch: 1394branch = repo_data.default_branch 1395return flask.redirect(f"./{branch}", code=302) 1396 1397if branch.startswith("tag:"): 1398ref = f"tags/{branch[4:]}" 1399elif branch.startswith("~"): 1400ref = branch[1:] 1401else: 1402ref = f"heads/{branch}" 1403 1404ref = ref.replace("~", "/") # encode slashes for URL support 1405 1406try: 1407repo.git.checkout("-f", ref) 1408except git.exc.GitCommandError: 1409return flask.render_template("errors/not-found.html"), 404 1410 1411branches = repo.heads 1412 1413all_refs = [] 1414for ref in repo.heads: 1415all_refs.append((ref, "head")) 1416for ref in repo.tags: 1417all_refs.append((ref, "tag")) 1418 1419commit_list = [f"/{username}/{repository}/{sha}" for sha in 1420git_command(server_repo_location, None, "log", 1421"--format='%H'").decode().split("\n")] 1422 1423commits = Commit.query.filter(Commit.identifier.in_(commit_list)).order_by(Commit.author_date.desc()) 1424page_number = flask.request.args.get("page", 1, type=int) 1425if flask.session.get("username"): 1426default_page_length = db.session.get(User, flask.session.get("username")).default_page_length 1427else: 1428default_page_length = 16 1429page_length = flask.request.args.get("per_page", default_page_length, type=int) 1430page_listing = db.paginate(commits, page=page_number, per_page=page_length) 1431 1432if page_listing.has_next: 1433next_page = page_listing.next_num 1434else: 1435next_page = None 1436 1437if page_listing.has_prev: 1438prev_page = page_listing.prev_num 1439else: 1440prev_page = None 1441 1442return flask.render_template( 1443"repo-log.html", 1444username=username, 1445repository=repository, 1446branches=all_refs, 1447current=branch, 1448repo_data=repo_data, 1449repo=repo, 1450commits=page_listing, 1451remote=f"http{'s' if config.suggest_https else ''}://{config.BASE_DOMAIN}/git/{username}/{repository}", 1452is_favourite=get_favourite(flask.session.get("username"), username, repository), 1453page_number=page_number, 1454page_length=page_length, 1455next_page=next_page, 1456prev_page=prev_page, 1457num_pages=page_listing.pages 1458) 1459 1460 1461@repositories.route("/<username>/<repository>/prs/", methods=["GET", "POST"]) 1462def repository_prs(username, repository): 1463server_repo_location = os.path.join(config.REPOS_PATH, username, repository) 1464if not os.path.exists(server_repo_location): 1465flask.abort(404) 1466if not (get_visibility(username, repository) or get_permission_level( 1467flask.session.get("username"), username, 1468repository) is not None): 1469flask.abort(403) 1470 1471if not os.path.exists(server_repo_location): 1472return flask.render_template("errors/not-found.html"), 404 1473 1474if flask.request.method == "GET": 1475repo = git.Repo(server_repo_location) 1476repo_data = Repo.query.filter_by(route=f"/{username}/{repository}").first() 1477user = User.query.filter_by(username=flask.session.get("username")).first() 1478 1479return flask.render_template( 1480"repo-prs.html", 1481username=username, 1482repository=repository, 1483repo_data=repo_data, 1484repo=repo, 1485PullRequest=PullRequest, 1486remote=f"http{'s' if config.suggest_https else ''}://{config.BASE_DOMAIN}/git/{username}/{repository}", 1487is_favourite=get_favourite(flask.session.get("username"), username, repository), 1488default_branch=repo_data.default_branch, 1489branches=repo.branches 1490) 1491 1492elif "id" not in flask.request.form: 1493repo_data = Repo.query.filter_by(route=f"/{username}/{repository}").first() 1494head = flask.request.form.get("head") 1495head_route = flask.request.form.get("headroute") 1496base = flask.request.form.get("base") 1497 1498if not head and base and head_route: 1499return flask.redirect(".", 400) 1500 1501head_repo = git.Repo(os.path.join(config.REPOS_PATH, head_route.lstrip("/"))) 1502base_repo = git.Repo(server_repo_location) 1503 1504if head not in head_repo.branches or base not in base_repo.branches: 1505flask.flash(Markup( 1506"<iconify-icon icon='mdi:error'></iconify-icon>" + _("Bad branch name")), 1507category="error") 1508return flask.redirect(".", 303) 1509 1510head_data = db.session.get(Repo, head_route) 1511if not head_data.visibility: 1512flask.flash(Markup( 1513"<iconify-icon icon='mdi:error'></iconify-icon>" + _( 1514"Head can't be restricted")), 1515category="error") 1516return flask.redirect(".", 303) 1517 1518pull_request = PullRequest(head_data, head, repo_data, base, 1519db.session.get(User, flask.session["username"])) 1520 1521db.session.add(pull_request) 1522db.session.commit() 1523 1524# Create the notification 1525notification = Notification({"type": "pr", "head": pull_request.head.route, "base": pull_request.base.route, "pr": pull_request.id}) 1526db.session.add(notification) 1527db.session.commit() 1528 1529# Send a notification to all users who have enabled PR notifications for this repo 1530for relationship in RepoFavourite.query.filter_by(repo_route=pull_request.base.route, notify_pr=True).all(): 1531user = relationship.user 1532user_notification = UserNotification(user, notification, 1) 1533db.session.add(user_notification) 1534db.session.commit() 1535celery_tasks.send_notification.apply_async(args=[user_notification.id]) 1536 1537return flask.redirect(".", 303) 1538else: 1539id = flask.request.form.get("id") 1540pull_request = db.session.get(PullRequest, id) 1541 1542if not pull_request: 1543flask.abort(404) 1544 1545if not (get_visibility(username, repository) or get_permission_level( 1546flask.session.get("username"), username, 1547repository) >= 1 or pull_request.owner.username == flask.session.get("username")): 1548flask.abort(403) 1549 1550if not get_permission_level(flask.session.get("username"), username, repository): 1551flask.abort(401) 1552 1553repo_data = Repo.query.filter_by(route=f"/{username}/{repository}").first() 1554 1555if pull_request: 1556pull_request.resolves_list = flask.request.form.get("resolves") 1557db.session.commit() 1558 1559return flask.redirect(".", 303) 1560 1561 1562@repositories.route("/<username>/<repository>/prs/merge", methods=["POST"]) 1563def repository_prs_merge(username, repository): 1564server_repo_location = os.path.join(config.REPOS_PATH, username, repository) 1565if not os.path.exists(server_repo_location): 1566flask.abort(404) 1567if not (get_visibility(username, repository) or get_permission_level( 1568flask.session.get("username"), username, 1569repository) is not None): 1570flask.abort(403) 1571 1572if not get_permission_level(flask.session.get("username"), username, repository): 1573flask.abort(401) 1574 1575repo_data = Repo.query.filter_by(route=f"/{username}/{repository}").first() 1576repo = git.Repo(server_repo_location) 1577id = flask.request.form.get("id") 1578 1579pull_request = db.session.get(PullRequest, id) 1580 1581if pull_request: 1582result = celery_tasks.merge_heads.delay( 1583pull_request.head_route, 1584pull_request.head_branch, 1585pull_request.base_route, 1586pull_request.base_branch, 1587pull_request.id, 1588simulate=True 1589) 1590task_result = worker.AsyncResult(result.id) 1591 1592return flask.redirect(f"/task/{result.id}?pr-id={id}", 303) # should be 202 Accepted but we must use a redirect 1593# db.session.delete(pull_request) 1594# db.session.commit() 1595else: 1596flask.abort(400) 1597 1598 1599@repositories.route("/<username>/<repository>/prs/<int:id>/merge") 1600def repository_prs_merge_stage_two(username, repository, id): 1601server_repo_location = os.path.join(config.REPOS_PATH, username, repository) 1602if not os.path.exists(server_repo_location): 1603flask.abort(404) 1604if not (get_visibility(username, repository) or get_permission_level( 1605flask.session.get("username"), username, 1606repository) is not None): 1607flask.abort(403) 1608 1609if not get_permission_level(flask.session.get("username"), username, repository): 1610flask.abort(401) 1611 1612repo_data = Repo.query.filter_by(route=f"/{username}/{repository}").first() 1613repo = git.Repo(server_repo_location) 1614 1615pull_request = db.session.get(PullRequest, id) 1616 1617if pull_request: 1618result = celery_tasks.merge_heads.delay( 1619pull_request.head_route, 1620pull_request.head_branch, 1621pull_request.base_route, 1622pull_request.base_branch, 1623pull_request.id, 1624simulate=False 1625) 1626task_result = worker.AsyncResult(result.id) 1627 1628db.session.commit() 1629 1630return flask.redirect(f"/task/{result.id}?pr-id={id}", 303) 1631# db.session.delete(pull_request) 1632else: 1633flask.abort(400) 1634 1635 1636@app.route("/task/<task_id>") 1637def task_monitor(task_id): 1638task_result = worker.AsyncResult(task_id) 1639 1640if flask.request.args.get("partial"): 1641# htmx partial update 1642return render_block("task-monitor.html", "content", result=task_result, query_string=flask.request.query_string.decode(), delay=1000) 1643 1644# Since most tasks finish rather quickly, the initial delay is faster, so it doesn't wait for too long 1645return flask.render_template("task-monitor.html", result=task_result, query_string=flask.request.query_string.decode(), delay=125) 1646 1647 1648@repositories.route("/<username>/<repository>/prs/delete", methods=["POST"]) 1649def repository_prs_delete(username, repository): 1650server_repo_location = os.path.join(config.REPOS_PATH, username, repository) 1651if not os.path.exists(server_repo_location): 1652flask.abort(404) 1653if not (get_visibility(username, repository) or get_permission_level( 1654flask.session.get("username"), username, 1655repository) is not None): 1656flask.abort(403) 1657 1658if not get_permission_level(flask.session.get("username"), username, repository): 1659flask.abort(401) 1660 1661repo_data = Repo.query.filter_by(route=f"/{username}/{repository}").first() 1662repo = git.Repo(server_repo_location) 1663id = flask.request.form.get("id") 1664 1665pull_request = db.session.get(PullRequest, id) 1666 1667if pull_request: 1668pull_request.state = 2 1669db.session.commit() 1670 1671return flask.redirect(".", 303) 1672 1673 1674@repositories.route("/<username>/<repository>/settings/") 1675def repository_settings(username, repository): 1676if get_permission_level(flask.session.get("username"), username, repository) != 2: 1677flask.abort(401) 1678 1679repo = git.Repo(os.path.join(config.REPOS_PATH, username, repository)) 1680 1681site_link = Markup(f"<code>http{'s' if config.suggest_https else ''}://{username}.{config.BASE_DOMAIN}/{repository}</code>") 1682primary_site_link = Markup(f"<code>http{'s' if config.suggest_https else ''}://{username}.{config.BASE_DOMAIN}/</code>") 1683 1684return flask.render_template("repo-settings.html", username=username, repository=repository, 1685repo_data=db.session.get(Repo, f"/{username}/{repository}"), 1686branches=[branch.name for branch in repo.branches], 1687site_link=site_link, primary_site_link=primary_site_link, 1688remote=f"http{'s' if config.suggest_https else ''}://{config.BASE_DOMAIN}/git/{username}/{repository}", 1689is_favourite=get_favourite(flask.session.get("username"), username, repository), 1690) 1691 1692 1693@repositories.route("/<username>/<repository>/settings/", methods=["POST"]) 1694def repository_settings_post(username, repository): 1695if get_permission_level(flask.session.get("username"), username, repository) != 2: 1696flask.abort(401) 1697 1698repo = db.session.get(Repo, f"/{username}/{repository}") 1699 1700repo.visibility = flask.request.form.get("visibility", type=int) 1701repo.info = flask.request.form.get("description") 1702repo.default_branch = flask.request.form.get("default_branch") 1703repo.url = flask.request.form.get("url") 1704 1705# Update site settings 1706had_site = repo.has_site 1707old_branch = repo.site_branch 1708if flask.request.form.get("site_branch"): 1709repo.site_branch = flask.request.form.get("site_branch") 1710if flask.request.form.get("primary_site"): 1711if had_site != 2: 1712# Remove primary site from other repos 1713for other_repo in Repo.query.filter_by(owner=repo.owner, has_site=2): 1714other_repo.has_site = 1 # switch it to a regular site 1715flask.flash(Markup( 1716_("Your repository {repository} has been demoted from a primary site to a regular site because there can only be one primary site per user.").format( 1717repository=other_repo.route 1718)), category="warning") 1719repo.has_site = 2 1720else: 1721repo.has_site = 1 1722else: 1723repo.site_branch = None 1724repo.has_site = 0 1725 1726db.session.commit() 1727 1728if not (had_site, old_branch) == (repo.has_site, repo.site_branch): 1729# Deploy the newly activated site 1730result = celery_tasks.copy_site.delay(repo.route) 1731 1732if had_site and not repo.has_site: 1733# Remove the site 1734result = celery_tasks.delete_site.delay(repo.route) 1735 1736if repo.has_site == 2 or (had_site == 2 and had_site != repo.has_site): 1737# Deploy all other sites which were destroyed by the primary site 1738for other_repo in Repo.query.filter_by(owner=repo.owner, has_site=1): 1739result = celery_tasks.copy_site.delay(other_repo.route) 1740 1741return flask.redirect(f"/{username}/{repository}/settings", 303) 1742 1743 1744@repositories.route("/<username>/<repository>/settings/add-label", methods=["POST"]) 1745def repository_settings_add_label(username, repository): 1746if get_permission_level(flask.session.get("username"), username, repository) != 2: 1747flask.abort(401) 1748 1749repo_data = db.session.get(Repo, f"/{username}/{repository}") 1750 1751label = Label(repo_data, flask.request.form.get("label"), flask.request.form.get("colour")) 1752db.session.add(label) 1753db.session.commit() 1754 1755return flask.redirect(f"/{username}/{repository}/settings", 303) 1756 1757 1758@repositories.route("/<username>/<repository>/settings/delete-label", methods=["POST"]) 1759def repository_settings_delete_label(username, repository): 1760if get_permission_level(flask.session.get("username"), username, repository) != 2: 1761flask.abort(401) 1762 1763repo_data = db.session.get(Repo, f"/{username}/{repository}") 1764 1765label = db.session.get(Label, flask.request.form.get("id")) 1766 1767db.session.delete(label) 1768db.session.commit() 1769 1770return flask.redirect(f"/{username}/{repository}/settings", 303) 1771 1772 1773@repositories.route("/<username>/<repository>/settings/edit-label", methods=["POST"]) 1774def repository_settings_edit_label(username, repository): 1775if get_permission_level(flask.session.get("username"), username, repository) != 2: 1776flask.abort(401) 1777 1778repo_data = db.session.get(Repo, f"/{username}/{repository}") 1779 1780label = db.session.get(Label, flask.request.form.get("id")) 1781 1782label.name = flask.request.form.get("label") 1783label.colour_hex = flask.request.form.get("colour") 1784 1785db.session.commit() 1786 1787return flask.redirect(f"/{username}/{repository}/settings", 303) 1788 1789 1790@repositories.route("/<username>/<repository>/settings/delete", methods=["POST"]) 1791def repository_settings_delete(username, repository): 1792if username != flask.session.get("username"): 1793flask.abort(401) 1794 1795repo = db.session.get(Repo, f"/{username}/{repository}") 1796 1797if not repo: 1798flask.abort(404) 1799 1800user = db.session.get(User, flask.session.get("username")) 1801 1802if not bcrypt.check_password_hash(user.password_hashed, flask.request.form.get("password")): 1803flask.flash(_("Incorrect password"), category="error") 1804flask.abort(401) 1805 1806if repo.has_site: 1807celery_tasks.delete_site.delay(repo.route) 1808 1809db.session.delete(repo) 1810db.session.commit() 1811 1812shutil.rmtree(os.path.join(config.REPOS_PATH, username, repository)) 1813 1814return flask.redirect(f"/{username}", 303) 1815 1816 1817@app.errorhandler(404) 1818def e404(error): 1819return flask.render_template("errors/not-found.html"), 404 1820 1821 1822@app.errorhandler(401) 1823def e401(error): 1824return flask.render_template("errors/unauthorised.html"), 401 1825 1826 1827@app.errorhandler(403) 1828def e403(error): 1829return flask.render_template("errors/forbidden.html"), 403 1830 1831 1832@app.errorhandler(418) 1833def e418(error): 1834return flask.render_template("errors/teapot.html"), 418 1835 1836 1837@app.errorhandler(405) 1838def e405(error): 1839return flask.render_template("errors/method-not-allowed.html"), 405 1840 1841 1842@app.errorhandler(500) 1843def e500(error): 1844return flask.render_template("errors/server-error.html"), 500 1845 1846 1847@app.errorhandler(400) 1848def e400(error): 1849return flask.render_template("errors/bad-request.html"), 400 1850 1851 1852@app.errorhandler(410) 1853def e410(error): 1854return flask.render_template("errors/gone.html"), 410 1855 1856 1857@app.errorhandler(415) 1858def e415(error): 1859return flask.render_template("errors/media-type.html"), 415 1860 1861 1862if __name__ == "__main__": 1863app.run(debug=True, port=8080, host="0.0.0.0") 1864 1865app.register_blueprint(repositories) 1866