From 4190057b3cbcc8e2a5e12b0c886614c160a53ff4 Mon Sep 17 00:00:00 2001
From: Tulir Asokan <tulir@maunium.net>
Date: Sat, 5 Sep 2020 14:43:07 +0300
Subject: [PATCH] Ask for Matrix access token on first run

---
 README.md           |  9 ++++-----
 example-config.json |  4 ----
 import.py           | 35 ++++++++++++++++++++++++++++++-----
 3 files changed, 34 insertions(+), 14 deletions(-)
 delete mode 100644 example-config.json

diff --git a/README.md b/README.md
index a5a08de..0020da3 100644
--- a/README.md
+++ b/README.md
@@ -6,11 +6,10 @@ A fast and simple Matrix sticker picker widget. Tested on Element Web & Android.
    1. Create with `virtualenv -p python3 .`
    2. Activate with `source ./bin/activate`
 2. Install dependencies with `pip install -r requirements.txt`
-3. Copy `example-config.json` to `config.json` and set your homeserver URL and access token
-   (used for uploading stickers to Matrix).
-4. Run `python3 import.py <pack urls...>`
-   * On the first run, it'll prompt you to log in with a bot token or a telegram account.
-     The session data is stored in `sticker-import.session` by default.
+3. Run `python3 import.py <pack urls...>`
+   * On the first run, it'll prompt you to log in to Matrix and Telegram.
+     * The Matrix URL and access token are stored in `config.json` by default.
+     * The Telethon session data is stored in `sticker-import.session` by default.
    * By default, the pack data will be written to `web/packs/`.
    * You can pass as many pack URLs as you want.
    * You can re-run the command with the same URLs to update packs.
diff --git a/example-config.json b/example-config.json
deleted file mode 100644
index af53451..0000000
--- a/example-config.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
-  "homeserver": "https://example.com",
-  "access_token": "foo"
-}
diff --git a/import.py b/import.py
index 36eaf5f..5114db4 100644
--- a/import.py
+++ b/import.py
@@ -31,11 +31,36 @@ parser.add_argument("--output-dir", help="Directory to write packs to", default=
 parser.add_argument("pack", help="Sticker pack URLs to import", action="append", nargs="*")
 args = parser.parse_args()
 
-with open(args.config) as config_file:
-    config = json.load(config_file)
-    homeserver_url = config["homeserver"]
-    upload_url = URL(homeserver_url) / "_matrix" / "media" / "r0" / "upload"
-    access_token = config["access_token"]
+
+async def whoami(url: URL, access_token: str) -> str:
+    headers = {"Authorization": f"Bearer {access_token}"}
+    async with ClientSession() as sess, sess.get(url, headers=headers) as resp:
+        resp.raise_for_status()
+        user_id = (await resp.json())["user_id"]
+        print(f"Access token validated (user ID: {user_id})")
+        return user_id
+
+
+try:
+    with open(args.config) as config_file:
+        config = json.load(config_file)
+        homeserver_url = config["homeserver"]
+        access_token = config["access_token"]
+except FileNotFoundError:
+    print("Matrix config file not found. Please enter your homeserver and access token.")
+    homeserver_url = input("Homeserver URL: ")
+    access_token = input("Access token: ")
+    whoami_url = URL(homeserver_url) / "_matrix" / "client" / "r0" / "account" / "whoami"
+    user_id = asyncio.run(whoami(whoami_url, access_token))
+    with open(args.config, "w") as config_file:
+        json.dump({
+            "homeserver": homeserver_url,
+            "user_id": user_id,
+            "access_token": access_token
+        }, config_file)
+    print(f"Wrote config to {args.config}")
+
+upload_url = URL(homeserver_url) / "_matrix" / "media" / "r0" / "upload"
 
 
 async def upload(data: bytes, mimetype: str, filename: str) -> str:
-- 
GitLab