From d29285d468e95cd4865cdc62b399e0a637301c53 Mon Sep 17 00:00:00 2001
From: Edward Betts <edward@4angle.com>
Date: Fri, 8 Sep 2023 11:01:50 +0100
Subject: [PATCH] Add link to send flickr message

---
 main.py                     | 33 ++++++++++++++++++++++++++++++++-
 templates/show_message.html |  2 ++
 2 files changed, 34 insertions(+), 1 deletion(-)

diff --git a/main.py b/main.py
index 345c63c..36e910a 100755
--- a/main.py
+++ b/main.py
@@ -1,9 +1,13 @@
 #!/usr/bin/python3
 
+import collections
+import json
 import sys
+import typing
 from urllib.parse import unquote
 
 import flask
+import requests
 
 app = flask.Flask(__name__)
 app.debug = True
@@ -28,6 +32,20 @@ def flickr_search() -> str:
     )
 
 
+def get_params(line_iter: collections.abc.Iterable[str]) -> str:
+    """Find and return params from flickr profile page."""
+    look_for = 'params: {"isEditingTestimonial":false,'
+    return next(line[line.find("{") :] for line in line_iter if look_for in line)
+
+
+def flickr_usrename_to_nsid(username: str) -> str:
+    """Get NSID from flickr username."""
+    url = f"https://www.flickr.com/people/{username}/"
+    r = requests.get(url)
+    params = json.loads(get_params(r.text.splitlines()))
+    return typing.cast(str, params["nsid"])
+
+
 @app.route("/message")
 def show_message() -> str:
     """Show message."""
@@ -50,6 +68,17 @@ def show_message() -> str:
     if "/in/" in flickr_url:
         flickr_url = flickr_url[: flickr_url.find("/in/")]
 
+    flickr_start = "https://flickr.com/photos/"
+
+    assert flickr_url.startswith(flickr_start)
+    flickr_username = flickr_url[
+        len(flickr_start) : flickr_url.find("/", len(flickr_start))
+    ]
+
+    nsid = flickr_usrename_to_nsid(flickr_username)
+    assert nsid
+    print(nsid)
+
     msg = flask.render_template(
         "message.jinja",
         flickr_url=flickr_url,
@@ -63,7 +92,9 @@ def show_message() -> str:
 
     lines = msg.split("\n\n")
 
-    return flask.render_template("show_message.html", subject=subject, lines=lines)
+    return flask.render_template(
+        "show_message.html", subject=subject, lines=lines, nsid=nsid
+    )
 
 
 if __name__ == "__main__":
diff --git a/templates/show_message.html b/templates/show_message.html
index 503950a..908b99f 100644
--- a/templates/show_message.html
+++ b/templates/show_message.html
@@ -10,6 +10,8 @@
 
 <body>
   <div class="container my-3">
+    <h1>Flickr Mail</h1>
+    <p><a href="https://www.flickr.com/mail/write/?to={{nsid}}">send message</a>
     <div><strong>Subject:</strong> {{ subject }}
       <div>
         <h3>message</h3>