import os, json, time, re, io, tempfile, uuid, threading from flask import Flask, request, jsonify, send_from_directory, send_file import openpyxl import requests as req app = Flask(__name__) BASE_DIR = os.path.dirname(os.path.abspath(__file__)) jobs = {} # =================================================================== # HTML Assembly - builds WP Gutenberg blocks from headings + body # =================================================================== def build_html(sections, cta=True): html_parts = [] for heading, body in sections: if not heading or not body: continue h = heading.strip() b = body.strip() html_parts.append(f'\n
{p}
\n') if cta: html_parts.append('\n地域の課題解決に挑戦してみませんか?FLASPOでは、全国の地方創生コンテストに参加できます。あなたのアイデアが地域を変えるきっかけになるかもしれません。
\n') return "\n\n".join(html_parts) # =================================================================== # WordPress helpers # =================================================================== def wp_call(method, url, user, pw, ep, data=None, files=None): full = f"{url}/wp-json/wp/v2/{ep}" auth = (user, pw) try: if files: r = req.post(full, auth=auth, files=files, data=data, timeout=60) elif method == "GET": r = req.get(full, auth=auth, timeout=30) else: r = req.post(full, auth=auth, json=data, timeout=30) return r.json() if r.status_code in [200, 201] else None except: return None def get_or_create(url, user, pw, t, name): items = wp_call("GET", url, user, pw, f"{t}?search={req.utils.quote(name)}&per_page=100") or [] for i in items: if i.get("name") == name: return i["id"] r = wp_call("POST", url, user, pw, t, {"name": name, "slug": name.replace("・", "-").replace(" ", "-")}) return r["id"] if r else None def make_eyecatch(pk, pt, title): if not pk or not pt: return None try: r = req.post("https://api.placid.app/api/rest/images", headers={"Authorization": f"Bearer {pk}", "Content-Type": "application/json"}, json={"template_uuid": pt, "layers": {"title": {"text": title}, "feature-1": {"text": "FLASPO MAGAZINE"}, "feature-2": {"text": ""}, "feature-3": {"text": ""}}}, timeout=60) if r.status_code in [200, 201]: d = r.json() u = d.get("image_url") or d.get("url") if not u and d.get("status") in ("queued", "processing"): for _ in range(15): time.sleep(3) pr = req.get(f"https://api.placid.app/api/rest/images/{d.get('id', '')}", headers={"Authorization": f"Bearer {pk}"}, timeout=30) if pr.status_code == 200 and pr.json().get("status") == "finished": u = pr.json().get("image_url") or pr.json().get("url") break if u: return req.get(u, timeout=30).content except: pass return None def post_one(wp_url, wp_user, wp_pass, pk, pt, title, content, category, tags_str, meta, slug, kw): mid = None img = make_eyecatch(pk, pt, title) if img: r = wp_call("POST", wp_url, wp_user, wp_pass, "media", data={"title": slug or title[:30], "alt_text": title}, files={"file": (f"eyecatch-{slug or 'img'}.jpg", img, "image/jpeg")}) if r: mid = r["id"] cat_id = get_or_create(wp_url, wp_user, wp_pass, "categories", category) if category else None tag_ids = [] if tags_str: for t in [x.strip() for x in tags_str.split(",") if x.strip()][:10]: tid = get_or_create(wp_url, wp_user, wp_pass, "tags", t) if tid: tag_ids.append(tid) pd = {"title": title, "slug": slug or "", "content": content, "excerpt": meta or "", "status": "draft", "categories": [cat_id] if cat_id else [], "tags": tag_ids} if mid: pd["featured_media"] = mid r = wp_call("POST", wp_url, wp_user, wp_pass, "posts", pd) if r: try: wp_call("POST", wp_url, wp_user, wp_pass, f"posts/{r['id']}", { "meta": {"_yoast_wpseo_metadesc": meta or "", "_yoast_wpseo_focuskw": kw or ""}}) except: pass return {"status": "ok", "id": r["id"], "url": f"{wp_url}/wp-admin/post.php?post={r['id']}&action=edit", "title": title} return {"status": "fail", "title": title, "error": "WordPress投稿失敗"} # =================================================================== # Excel reading # =================================================================== def read_batch(data): wb = openpyxl.load_workbook(io.BytesIO(data)) ws = wb.active articles = [] for row in range(2, ws.max_row + 1): title = ws.cell(row=row, column=1).value if not title or not str(title).strip(): continue sections = [] for i in range(5): h = ws.cell(row=row, column=7 + i * 2).value b = ws.cell(row=row, column=8 + i * 2).value if h and str(h).strip(): sections.append((str(h).strip(), str(b).strip() if b else "")) content = build_html(sections) articles.append({ "title": str(title).strip(), "content": content, "category": str(ws.cell(row=row, column=2).value or "").strip(), "tags": str(ws.cell(row=row, column=3).value or "").strip(), "meta": str(ws.cell(row=row, column=4).value or "").strip(), "slug": str(ws.cell(row=row, column=5).value or "").strip(), "keyword": str(ws.cell(row=row, column=6).value or "").strip(), "section_count": len(sections), }) return articles # =================================================================== # Async job # =================================================================== def start_job(fn, *args): job_id = str(uuid.uuid4())[:8] jobs[job_id] = {"status": "running", "result": None, "progress": 0, "total": 0, "current": ""} def wrapper(): try: result = fn(job_id, *args) jobs[job_id]["status"] = "done" jobs[job_id]["result"] = result except Exception as e: jobs[job_id]["status"] = "error" jobs[job_id]["result"] = str(e) threading.Thread(target=wrapper, daemon=True).start() return job_id # =================================================================== # Routes # =================================================================== @app.route("/") def index(): return send_from_directory(BASE_DIR, "index.html") @app.route("/api/testwp", methods=["POST"]) def test_wp(): d = request.json u = wp_call("GET", d["wp_url"], d["wp_user"], d["wp_pass"], "users/me") if u and u.get("id"): return jsonify({"ok": True, "name": u.get("name", "")}) return jsonify({"ok": False}) @app.route("/api/post-single", methods=["POST"]) def post_single(): d = request.json job_id = start_job(do_post_single, d) return jsonify({"job_id": job_id}) def do_post_single(job_id, d): jobs[job_id]["total"] = 1 jobs[job_id]["current"] = d.get("title", "") sections = [] for i in range(1, 6): h = d.get(f"h{i}", "") b = d.get(f"b{i}", "") if h: sections.append((h, b)) content = build_html(sections) result = post_one(d["wp_url"], d["wp_user"], d["wp_pass"], d.get("pk", ""), d.get("pt", ""), d["title"], content, d.get("category", ""), d.get("tags", ""), d.get("meta", ""), d.get("slug", ""), d.get("keyword", "")) jobs[job_id]["progress"] = 1 return result @app.route("/api/upload-batch", methods=["POST"]) def upload_batch(): f = request.files.get("file") if not f: return jsonify({"ok": False}) path = os.path.join(tempfile.gettempdir(), "batch.xlsx") f.save(path) articles = read_batch(open(path, "rb").read()) return jsonify({"ok": True, "path": path, "count": len(articles), "articles": [{"title": a["title"], "category": a["category"], "sections": a["section_count"]} for a in articles]}) @app.route("/api/post-batch", methods=["POST"]) def post_batch(): d = request.json job_id = start_job(do_post_batch, d) return jsonify({"job_id": job_id}) def do_post_batch(job_id, d): path = d.get("excel_path", "") if not path or not os.path.exists(path): return {"ok": False, "error": "ファイルなし"} articles = read_batch(open(path, "rb").read()) if not articles: return {"ok": False, "error": "記事なし。Excelのフォーマットを確認してください。"} jobs[job_id]["total"] = len(articles) results = [] for i, art in enumerate(articles): jobs[job_id]["progress"] = i jobs[job_id]["current"] = art["title"][:30] r = post_one(d["wp_url"], d["wp_user"], d["wp_pass"], d.get("pk", ""), d.get("pt", ""), art["title"], art["content"], art["category"], art["tags"], art["meta"], art["slug"], art["keyword"]) results.append(r) time.sleep(2) jobs[job_id]["progress"] = len(articles) return {"ok": True, "results": results} @app.route("/api/status/