krz/crumb
clone: git clone https://gitbay.org/krz/crumb.git
main: server.py · raw
1import os
2from datetime import datetime
3from flask import Flask, request
4
5app = Flask(__name__)
6LOG_PATH = os.path.expanduser("~/.crumb/history.org")
7
8os.makedirs(os.path.dirname(LOG_PATH), exist_ok=True)
9
10
11@app.after_request
12def add_cors_headers(response):
13 """
14 Add CORS headers to the response to allow cross-origin requests.
15
16 Args:
17 response (flask.Response): The response object to modify.
18
19 Returns:
20 flask.Response: The modified response object with CORS headers.
21 """
22 response.headers["Access-Control-Allow-Origin"] = "*"
23 response.headers["Access-Control-Allow-Headers"] = "Content-Type"
24 return response
25
26
27@app.route("/", methods=["POST", "OPTIONS"])
28def log_visit():
29 """
30 Handle POST requests to log visit information and OPTIONS requests for CORS preflight.
31
32 For POST requests, parse JSON data from the request, extract visit details,
33 and append them to the log file in org-mode format.
34
35 For OPTIONS requests, return a 204 No Content response.
36
37 Returns:
38 tuple: An empty string and the HTTP status code 204.
39 """
40 if request.method == "OPTIONS":
41 return "", 204
42
43 data = request.json
44 title = data.get("title", "No Title")
45 url = data.get("url", "No URL")
46 hostname = data.get("hostname", "")
47 path = data.get("path", "")
48 query = data.get("query", "")
49 tab_id = data.get("tabId", "")
50 window_id = data.get("windowId", "")
51 favicon = data.get("favIconUrl", "")
52 timestamp = datetime.utcnow().isoformat()
53
54 with open(LOG_PATH, "a") as f:
55 f.write(f"* {title}\n")
56 f.write(":PROPERTIES:\n")
57 f.write(f":URL: {url}\n")
58 f.write(f":TIMESTAMP: {timestamp}\n")
59 f.write(f":HOST: {hostname}\n")
60 f.write(f":PATH: {path}\n")
61 if query:
62 f.write(f":QUERY: {query}\n")
63 f.write(f":TAB: {tab_id}\n")
64 f.write(f":WINDOW: {window_id}\n")
65 if favicon:
66 f.write(f":FAVICON: {favicon}\n")
67 f.write(":END:\n\n")
68
69 return "", 204
70
71
72if __name__ == "__main__":
73 """
74 Run the Flask application on port 3555 when executed as the main program.
75 """
76 app.run(port=3555)