from typing import Tuple import os import io import magic from config.config import DEBUG from backend.ig import IG from backend.db import dbhelper from backend.utils import ld_interface from backend.utils import ld_picturemaker from backend.utils import fileProcessor def clean(file_list:list[str]): for f in file_list: # instagram thumbnail file if f.endswith(".mp4"): try: os.remove(f+".jpg") except: pass try: os.remove(f) except: pass # return (errmsg | code, errcode) def upload(aid:int) -> Tuple[str, int]: # get article article = ld_interface.inf.get(index=aid, media=True) if article is None: return "Post not found", 1 # multimedia -> tmp file tmp_path = [] for m in article["content"]["media"]: _binary = m.read() # check mime type mime = magic.Magic(mime=True) tp = mime.from_buffer(_binary) # save file filename, err = fileProcessor.file_saver(tp, _binary) if err: clean(tmp_path) return "Error while saving file : %s"%filename, 1 tmp_path.append(filename) article["content"]["media"] = [] # 合成文字圖 proma_file:list = ld_picturemaker.picture_maker.gen(article) if len(proma_file) == 0: # no file returned clean(tmp_path) return "Error while generating proma_file", 1 tmp_path = proma_file + tmp_path # 送交 IG 上傳 if not DEBUG: media = IG.upload_media(article, tmp_path) if media is None: return "Upload failed", 1 else: media = {"code":"fake_data"} # 刪除檔案 clean(tmp_path) return media["code"], 0 # return (errmsg, code) #def remove(code:str) -> Tuple[str, int]: def remove(aid:int) -> Tuple[str, int]: # 抓取文章本體 - 叫你刪除的時候可能已經找不到本體了 # article, code = dbhelper.solo_article_fetcher(role="general", key=aid) # if code != 200: # return "Post not found", 1 article = dbhelper.solo_article_fetcher(aid=aid) # 從對表資料庫裡面抓igid if article is None: return "Post not found", 1 err = IG.delete_media(article["igid"]) if err: return "Remove failed", 1 return "OK", 0