feat: add file preview and improve project structure

- Added file preview functionality, enabling users to view images, text, and markdown files directly within the app.
- Updated project metadata: changed author to "Private.coffee Team" and updated URLs.
- Introduced a main function to allow customizable host and port via environment variables.
- Enhanced raw file serving with MIME type checks and content disposition for better file handling.
- Fixed URL formats in templates for consistent navigation.

These improvements enhance usability and maintainability, providing a richer user experience and preparing for future enhancements.
This commit is contained in:
Kumi 2024-06-19 09:23:45 +02:00
parent 621022dfb8
commit 894b6f8c52
Signed by: kumi
GPG key ID: ECBCC9082395383F
7 changed files with 232 additions and 8 deletions

132
README.md
View file

@ -0,0 +1,132 @@
# GitCloak
GitCloak is a simple web frontend that lets you browse GitHub repositories and view their contents. It provides an easy-to-use interface to navigate directories, view files, and also renders `README.md` files. It is still a work in progress, but the basic functionality is there.
Instead of using the GitHub API or screen scraping, GitCloak interfaces directly with the GitHub repository using the git protocol. This should make it more resilient to changes on the GitHub side, and also allows future modifications or forks to support other git hosting services like Forgejo or GitLab instances.
## Features
- Browse directories and files in GitHub repositories.
- View the content of files directly in the browser.
- Responsive design with Bootstrap for a clean and professional look.
## Getting Started
### Prerequisites
- Python 3 (tested with 3.12)
- pip
- venv (optional but recommended)
### Production
1. Set up a virtual environment and activate it:
```sh
python -m venv venv
source venv/bin/activate
```
2. Install GitCloak from PyPI:
```sh
pip install gitcloak
```
3. Run the GitCloak server:
```sh
gitcloak
```
4. Open your browser and navigate to:
```
http://localhost:8107/
```
### Development
1. Clone the repository:
```sh
git clone https://git.private.coffee/PrivateCoffee/gitcloak
cd gitcloak
```
2. Create a virtual environment and activate it:
```sh
python -m venv venv
source venv/bin/activate
```
3. Install the Python package:
```sh
pip install -Ue .
```
4. Run the development server:
```sh
gitcloak
```
5. Open your browser and navigate to:
```
http://localhost:8107/
```
### Configuration
GitCloak currently supports the following environment variables:
- `PORT`: The port number to run the server on. Default is `8107`.
- `HOST`: The host to bind the server to. Default is `127.0.0.1`.
### Usage
- **Landing Page**: The landing page provides information about the app and instructions on how to use it.
```
http://localhost:8107/
```
- **Browse Repository**: To browse a repository, use the following URL format:
```
http://localhost:8107/<owner>/<repo>/
```
- **View Subdirectory**: To view a specific directory, use the following URL format:
```
http://localhost:8107/<owner>/<repo>/tree/main/<path>
```
- **View File Content**: To view the raw content of a specific file, use the following URL format:
```
http://localhost:8107/<owner>/<repo>/raw/main/<file_path>
```
## Contributing
We welcome contributions to improve GitCloak! To contribute:
1. Fork the repository.
2. Create a new branch for your feature or bugfix.
3. Make your changes and commit them.
4. Push your changes to your fork.
5. Create a pull request to merge your changes into the main repository.
## License
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for more details.
## Acknowledgments
- [Flask](https://flask.palletsprojects.com/) - A lightweight WSGI web application framework in Python.
- [Bootstrap](https://getbootstrap.com/) - A powerful front-end framework for faster and easier web development.
- [markdown2](https://github.com/trentm/python-markdown2) - A fast and complete implementation of Markdown in Python.
- [Phosphor Icons](https://phosphoricons.com/) - Beautifully designed icons for use in web projects.

View file

@ -5,7 +5,7 @@ build-backend = "hatchling.build"
[project]
name = "gitcloak"
version = "0.0.1"
authors = [{ name = "Kumi Mitterer", email = "gitcloak@kumi.email" }]
authors = [{ name = "Private.coffee Team", email = "support@private.coffee" }]
description = "Simple Python-based private frontend for GitHub repositories"
readme = "README.md"
license = { file = "LICENSE" }
@ -17,6 +17,9 @@ classifiers = [
]
dependencies = ["requests", "flask", "markdown2[all]"]
[project.scripts]
gitcloak = "gitcloak.app:main"
[project.urls]
"Homepage" = "https://git.private.coffee/kumi/gitcloak"
"Bug Tracker" = "https://git.private.coffee/kumi/gitcloak/issues"
"Homepage" = "https://git.private.coffee/PrivateCoffee/gitcloak"
"Bug Tracker" = "https://git.private.coffee/PrivateCoffee/gitcloak/issues"

View file

@ -2,6 +2,9 @@ from flask import Flask, render_template, abort, send_from_directory
from .classes.git import Git
from .classes.markdown import RelativeURLRewriter
import logging
import os
import base64
import mimetypes
from pathlib import Path
logger = logging.getLogger(__name__)
@ -91,7 +94,16 @@ def get_raw(owner, repo, file_path):
except UnicodeDecodeError:
content_type = "application/octet-stream"
return file_content, 200, {"Content-Type": content_type}
content_type, _ = mimetypes.guess_type(file_path)
file_name = file_path.split("/")[-1]
headers = {
"Content-Type": content_type,
"Content-Disposition": f"attachment; filename={file_name}",
}
return file_content, 200, headers
except Exception as e:
logger.error(
f"Error getting file content for {file_path} in {owner}/{repo}: {e}"
@ -99,5 +111,48 @@ def get_raw(owner, repo, file_path):
abort(404, description=str(e))
@app.route("/<owner>/<repo>/blob/main/<path:file_path>", methods=["GET"])
def preview_file(owner, repo, file_path):
repo_url = f"https://github.com/{owner}/{repo}.git"
git = Git(repo_url)
try:
file_content = git.get_file_content(file_path)
content_type, _ = mimetypes.guess_type(file_path)
is_text = content_type and content_type.startswith("text")
is_image = content_type and content_type.startswith("image")
is_safe = False
if content_type == "text/markdown":
base_url = f"/{owner}/{repo}/raw/main/{"/".join(file_path.split("/")[:-1])}".rstrip("/")
file_content = RelativeURLRewriter(base_url).convert(
file_content.decode("utf-8")
)
is_safe = True
if is_image:
file_content = base64.b64encode(file_content).decode("utf-8")
return render_template(
"preview.html",
owner=owner,
repo=repo,
file_path=file_path,
file_content=file_content,
is_text=is_text,
is_image=is_image,
is_safe=is_safe
)
except Exception as e:
logger.error(f"Error previewing file {file_path} in {owner}/{repo}: {e}")
abort(404, description=str(e))
def main():
port = os.environ.get("PORT", 8107)
host = os.environ.get("HOST", "127.0.0.1")
app.run(debug=True, port=port, host=host)
if __name__ == "__main__":
app.run(debug=True, port=8107)
main()

View file

@ -10,7 +10,6 @@ class RelativeURLRewriter(markdown2.Markdown):
# Rewrite relative URLs
def replace_url(match):
url = match.group(1)
print(f"URL: {match}")
if not (":" in url or url.startswith("/") or url.startswith("#") or url.startswith("md5-")):
return f'src="{self.base_url}/{url}"'
return match.group(0)

View file

@ -12,7 +12,7 @@
<ul>
<li><code>/&lt;owner&gt;/&lt;repo&gt;/</code> - View the root directory of the repository</li>
<li><code>/&lt;owner&gt;/&lt;repo&gt;/tree/main/&lt;path&gt;</code> - View a specific directory</li>
<li><code>/&lt;owner&gt;/&lt;repo&gt;/raw/&lt;file_path&gt;</code> - View the raw content of a specific file</li>
<li><code>/&lt;owner&gt;/&lt;repo&gt;/raw/main/&lt;file_path&gt;</code> - View the raw content of a specific file</li>
</ul>
<p>For example, to see the contents of the <code>PrivateCoffee/transfer.coffee</code> repository, simply visit <a href="/PrivateCoffee/transfer.coffee/">/PrivateCoffee/transfer.coffee/</a>.</p>
<p>Other features are still in development, so stay tuned!</p>

View file

@ -23,7 +23,7 @@
>
<a
class="list-group-item list-group-item-action"
href="/{{ owner }}/{{ repo }}/{{ 'tree/main' if entry in directories else 'raw' }}/{{ path }}/{{ entry }}"
href="/{{ owner }}/{{ repo }}/{{ 'tree' if entry in directories else 'blob' }}/main/{{ path }}/{{ entry }}"
>
<img class="icon" src="{{ "/assets/dist/icons/" + ('folder.svg' if
entry in directories else 'file.svg') }}" alt="{{ 'folder' if entry in

View file

@ -0,0 +1,35 @@
{% extends 'base.html' %}
{% block title %}{{ owner }}/{{ repo }} - {{ file_path }}{% endblock %}
{% block content %}
<div class="row">
<div class="col-md-12">
<h1>{{ owner }}/{{ repo }} - <small>{{ file_path }}</small></h1>
<div class="mb-3">
<a href="/{{ owner }}/{{ repo }}/tree/main/{{ file_path.rsplit('/', 1)[0] }}">
<img class="icon" src="/assets/dist/icons/folder.svg" alt="Back to Parent Directory"> Back to Parent Directory
</a>
</div>
<div class="card">
<div class="card-body">
{% if is_text %}
{% if is_safe %}
<div>{{ file_content | safe }}</div>
{% else %}
<pre>{{ file_content }}</pre>
{% endif %}
{% elif is_image %}
<img src="data:image/png;base64,{{ file_content }}" class="img-fluid" alt="{{ file_path }}">
{% else %}
<p>This file is binary and cannot be displayed.</p>
{% endif %}
<hr>
<p class="card-text">
<a href="/{{ owner }}/{{ repo }}/raw/main/{{ file_path }}" class="btn btn-primary">Download</a>
</p>
</div>
</div>
</div>
</div>
{% endblock %}