95 lines
3.5 KiB
Python
95 lines
3.5 KiB
Python
from libs.api.apiBlueprint import ApiBlueprint
|
|
from libs.fspn.utils.sha256_util import hash_bytes
|
|
from libs.app.common.paths import FILES_DIR
|
|
|
|
from flask import jsonify, request, send_from_directory
|
|
|
|
import os
|
|
import copy
|
|
import random
|
|
|
|
MEDIAS_FOLDER = os.path.join(FILES_DIR, "p2post", "medias")
|
|
|
|
class Blueprint(ApiBlueprint):
|
|
def routes(self):
|
|
from .p2post import P2post
|
|
self.module:P2post = self.module
|
|
|
|
@self.blueprint.route('/')
|
|
def show():
|
|
return self.module.name
|
|
|
|
@self.blueprint.route('/myusers', methods=["GET", "POST"])
|
|
def my_users():
|
|
if request.method == "GET":
|
|
users = []
|
|
for user_id in self.module.nosys_core.users.users:
|
|
user = self.module.data.get_user(user_id)
|
|
if user:
|
|
user["data"] = self.module.nosys_core.data.get_user(user_id)
|
|
users.append(user)
|
|
return jsonify(users)
|
|
|
|
elif request.method == "POST":
|
|
content:dict = request.json
|
|
self.module.data.add_user(content["pubkey"], content["nickname"], content["avatar"], content["bio"])
|
|
return jsonify({"pubkey":content["pubkey"]})
|
|
|
|
|
|
@self.blueprint.route('/users', methods=["GET", "POST"])
|
|
def users():
|
|
if request.method == "GET":
|
|
users = self.module.data.list_users()
|
|
return jsonify({"users":users})
|
|
|
|
elif request.method == "POST":
|
|
content:dict = request.json
|
|
self.module.data.add_user(content["pubkey"], content["nickname"], content["avatar"], content["bio"])
|
|
return jsonify({"pubkey":content["pubkey"]})
|
|
|
|
@self.blueprint.route('/posts', methods=["GET", "POST"])
|
|
def posts():
|
|
if request.method == "GET":
|
|
raw_posts = self.module.data.list_posts()
|
|
posts = copy.deepcopy(raw_posts)
|
|
for post in posts:
|
|
for media in post.get("medias"):
|
|
if media.get("type") == "local":
|
|
media_info = self.module.data.get_media(media.get("hash"))
|
|
media["file_path"] = media_info.get("file_path")
|
|
return jsonify(posts)
|
|
|
|
elif request.method == "POST":
|
|
content:dict = request.json
|
|
hash = self.module.create_post(content["user"], content["content"], content["medias"], content["networks"])
|
|
return jsonify(hash)
|
|
|
|
@self.blueprint.route('/medias', methods=['POST'])
|
|
def medias():
|
|
file = request.files.get("file")
|
|
if not file:
|
|
return jsonify({"error": "Empty file"}), 400
|
|
|
|
file_bytes = file.read()
|
|
file_hash = hash_bytes(file_bytes)
|
|
file_ext = os.path.splitext(file.filename)[1]
|
|
file_path = os.path.join(MEDIAS_FOLDER, f"{file_hash}{file_ext}")
|
|
|
|
if not os.path.exists(file_path):
|
|
with open(file_path, "wb") as f:
|
|
f.write(file_bytes)
|
|
|
|
return jsonify({
|
|
"status": "ok",
|
|
"hash": file_hash,
|
|
"path": f"{file_hash}{file_ext}"
|
|
})
|
|
|
|
@self.blueprint.route('/medias/<filename>')
|
|
def media_file(filename):
|
|
return send_from_directory(MEDIAS_FOLDER, filename)
|
|
|
|
|
|
|
|
|