#!/usr/bin/env python3
"""Fieldify REST API: an example script for Jira administrators.

Lists File Fields and their files, downloads files, and adds files, through
Fieldify's REST API. Copy it and adapt it to your own automation.
Python 3.9 or later, standard library only (nothing to install); runs on
Windows, macOS and Linux. Guide: https://www.teranoapps.com/file-field/docs/usage/rest-api

Settings (environment variables):
  FIELDIFY_BASE_URL        this site's base URL, copied from the Fieldify REST API
                           admin page in Jira:
                           https://api.atlassian.com/svc/jira/<cloudId>/apps/<appId>_<environmentId>
  ATLASSIAN_CLIENT_ID      your OAuth 2.0 integration's client id (Developer Console)
  ATLASSIAN_CLIENT_SECRET  the integration's secret
  ATLASSIAN_REDIRECT_URI   the integration's callback URL, as entered in the Console
  FIELDIFY_TOKEN_FILE      where the tokens are kept (default fieldify-token.json),
                           readable by your user only on macOS and Linux

Scopes the integration needs:
  read:file-field:custom   list fields and files, download files
  write:file-field:custom  upload and import files
  read:forge-app:jira      every call to an app's REST API
  offline_access           a refresh token, so the script can run unattended
  read:jira-work, write:jira-work
                           import only: add and delete the temporary attachment

Start with `exchange <code>` once. The script never prints a token, the client
secret or a download link.
"""

import argparse
import base64
import http.client
import json
import mimetypes
import os
import sys
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid

TOKEN_URL = "https://auth.atlassian.com/oauth/token"
MAX_UPLOAD_BYTES = 3_500_000  # larger files go through `import`
MAX_LINKS_PER_CALL = 50  # file ids in one POST /v1/files/links
MAX_RETRIES = 3  # for `busy` and 503 answers
DEFAULT_WAIT_SECONDS = 5  # when an answer does not say how long to wait
IMPORT_TIMEOUT_SECONDS = 10 * 60  # how long `import` waits for the copy

# Every HTTP request goes through this opener (the tests replace it with a fake).
OPENER = urllib.request.build_opener()


class FieldifyError(Exception):
    """A refusal or failure the script reports. Its message never holds a token or a link."""


# ---------- Settings ----------


def load_settings():
    """Read the settings from environment variables; stop with a message when one is missing."""
    names = ["FIELDIFY_BASE_URL", "ATLASSIAN_CLIENT_ID", "ATLASSIAN_CLIENT_SECRET", "ATLASSIAN_REDIRECT_URI"]
    missing = [name for name in names if not os.environ.get(name)]
    if missing:
        raise SystemExit("Set these environment variables first: " + ", ".join(missing))
    base_url = os.environ["FIELDIFY_BASE_URL"].strip().rstrip("/")
    return {
        "base_url": base_url,
        "cloud_id": cloud_id_from_base_url(base_url),
        "client_id": os.environ["ATLASSIAN_CLIENT_ID"],
        "client_secret": os.environ["ATLASSIAN_CLIENT_SECRET"],
        "redirect_uri": os.environ["ATLASSIAN_REDIRECT_URI"],
        "token_file": os.environ.get("FIELDIFY_TOKEN_FILE") or "fieldify-token.json",
    }


def cloud_id_from_base_url(url: str) -> str:
    """Return the site's cloud id from the base URL. Jira's own REST API needs it for `import`.

    Only the form the Fieldify REST API admin page shows is accepted:
    https://api.atlassian.com/svc/jira/<cloudId>/apps/<appId>_<environmentId>
    """
    parts = urllib.parse.urlsplit(url.strip())
    segments = parts.path.strip("/").split("/")
    if (
        parts.scheme == "https"
        and parts.netloc == "api.atlassian.com"
        and len(segments) == 5
        and segments[:2] == ["svc", "jira"]
        and segments[2]
        and segments[3] == "apps"
    ):
        return segments[2]
    raise SystemExit(
        "FIELDIFY_BASE_URL must look like "
        "https://api.atlassian.com/svc/jira/<cloudId>/apps/<appId>_<environmentId>. "
        "Copy it from the Fieldify REST API admin page in Jira (Jira settings > Apps). "
        "The https://<site>/gateway/... form has no cloud id."
    )


# ---------- Tokens ----------


def read_tokens(path):
    """Read the token file that `exchange` wrote."""
    try:
        with open(path) as token_file:
            return json.load(token_file)
    except FileNotFoundError:
        raise SystemExit(f"No token file at {path}. Run `exchange <code>` first.")


def save_tokens(path: str, tokens: dict) -> None:
    """Write the tokens to a temporary file next to `path`, then move it into place.

    A crash halfway leaves the old file whole. The temporary file is created
    readable by its owner only (mode 0600) on macOS and Linux, and keeps that
    mode when it is moved.
    """
    folder = os.path.dirname(os.path.abspath(path))
    handle, temp_path = tempfile.mkstemp(dir=folder, prefix=".fieldify-token-")
    try:
        with os.fdopen(handle, "w") as temp_file:
            json.dump(tokens, temp_file, indent=2)
            temp_file.flush()
            os.fsync(temp_file.fileno())
        os.replace(temp_path, path)
    finally:
        if os.path.exists(temp_path):
            os.remove(temp_path)


def token_request(fields):
    """POST to Atlassian's token endpoint and return its answer (the new tokens)."""
    request = urllib.request.Request(
        TOKEN_URL,
        data=json.dumps(fields).encode("utf-8"),
        headers={"Content-Type": "application/json", "Accept": "application/json"},
        method="POST",
    )
    status, _, data = send(request)
    answer = parse_json(data)
    if status != 200:
        # An error answer holds no token; its "error" and "error_description" are safe to show.
        reason = f"{answer.get('error', '')} {answer.get('error_description', '')}".strip()
        raise SystemExit(
            f"Atlassian's token endpoint answered {status} ({reason or 'no reason given'}). "
            "If the refresh token expired or the consent was revoked, run `exchange` with a new code."
        )
    return answer


def tokens_from(grant, refresh_token=None):
    """What the token file keeps: the access token, when it expires, and the refresh token."""
    return {
        "access_token": grant["access_token"],
        # A minute early, so a token never expires halfway through a call.
        "expires_at": time.time() + grant.get("expires_in", 3600) - 60,
        # Atlassian rotates refresh tokens: a refresh answers with a new one that replaces the old.
        "refresh_token": grant.get("refresh_token", refresh_token),
    }


def exchange_code(settings, code):
    """Trade the authorization code from the consent for tokens, and save them.

    Open the authorization URL that the Developer Console gives for Fieldify
    (with offline_access among its scopes), grant consent as the account the
    Jira administrator allowed, and copy the `code` parameter from the address
    the browser lands on (ATLASSIAN_REDIRECT_URI).
    """
    grant = token_request(
        {
            "grant_type": "authorization_code",
            "client_id": settings["client_id"],
            "client_secret": settings["client_secret"],
            "code": code,
            "redirect_uri": settings["redirect_uri"],
        }
    )
    save_tokens(settings["token_file"], tokens_from(grant))
    print(f"Saved the tokens to {settings['token_file']}.")
    print(f"Scopes granted: {grant.get('scope', 'not listed')}")
    if "refresh_token" not in grant:
        print("No refresh token: add offline_access to the scopes, or the tokens stop working in an hour.")


def access_token(settings: dict) -> str:
    """Return a valid access token, refreshing it with the saved refresh token when it has expired.

    The refresh answers with a new refresh token, and only that one will work
    next time, so it is saved before the access token is used. If it cannot be
    saved, the script stops.
    """
    tokens = read_tokens(settings["token_file"])
    if tokens.get("access_token") and tokens.get("expires_at", 0) > time.time():
        return tokens["access_token"]
    if not tokens.get("refresh_token"):
        raise SystemExit("The token file holds no refresh token. Run `exchange` again, with offline_access.")
    grant = token_request(
        {
            "grant_type": "refresh_token",
            "client_id": settings["client_id"],
            "client_secret": settings["client_secret"],
            "refresh_token": tokens["refresh_token"],
        }
    )
    new_tokens = tokens_from(grant, tokens["refresh_token"])
    try:
        save_tokens(settings["token_file"], new_tokens)
    except OSError as error:
        raise SystemExit(
            f"Could not save the new refresh token to {settings['token_file']} ({error}). "
            "Stopping here. If the next run cannot refresh, run `exchange` with a new code."
        )
    return new_tokens["access_token"]


# ---------- Calling the API ----------


def send(request):
    """Send one HTTP request; return (status, headers, body bytes). Error answers are returned, not raised."""
    try:
        with OPENER.open(request, timeout=60) as response:
            return response.status, response.headers, response.read()
    except urllib.error.HTTPError as error:
        with error:  # an error answer is a response too: read it, then close it
            return error.code, error.headers, error.read()


def parse_json(data):
    """The answer body as a dict; {} when it is empty or not a JSON object."""
    try:
        answer = json.loads(data)
    except ValueError:
        return {}
    return answer if isinstance(answer, dict) else {}


def with_token(request, settings):
    """Add the access token to a request for Fieldify or Jira.

    An "unredirected" header is not passed on if the answer redirects to
    another address, so the token only goes where the script sent it.
    """
    request.add_unredirected_header("Authorization", "Bearer " + access_token(settings))
    return request


def call(settings: dict, method: str, path: str, body: dict = None) -> tuple[int, dict]:
    """Call one Fieldify endpoint; return (status, answer). JSON in and out.

    `busy` (another write into the same field) and 503 (Fieldify unavailable
    for a moment) are tried again up to 3 times, after the wait the Retry-After
    header asks for, or 5 seconds. Any other error raises FieldifyError with
    the API's error code and message.
    """
    data = None if body is None else json.dumps(body).encode("utf-8")
    for attempt in range(1 + MAX_RETRIES):
        request = urllib.request.Request(settings["base_url"] + path, data=data, method=method)
        request.add_header("Accept", "application/json")
        if data is not None:
            request.add_header("Content-Type", "application/json")
        status, headers, raw = send(with_token(request, settings))
        answer = parse_json(raw)
        if status < 400:
            return status, answer
        error = answer.get("error")
        code = error.get("code") if isinstance(error, dict) else None
        if (code == "busy" or status == 503) and attempt < MAX_RETRIES:
            wait = retry_after(headers)
            print(f"{code or status}: trying again in {wait} s")
            time.sleep(wait)
            continue
        raise FieldifyError(describe_error(status, answer))


def retry_after(headers):
    """Seconds to wait, from the Retry-After header; 5 when it is missing."""
    value = headers.get("Retry-After", "")
    return int(value) if value.isdigit() else DEFAULT_WAIT_SECONDS


def describe_error(status, answer):
    """One line about an error answer, from Fieldify's error body when there is one."""
    error = answer.get("error")
    if isinstance(error, dict) and error.get("code"):
        text = f"{status} {error['code']}: {error.get('message', '')}"
        if error.get("details"):
            text += " (" + "; ".join(error["details"]) + ")"
        return text
    if status in (401, 403):
        return (
            f"Atlassian answered {status} without Fieldify's error body. Usually the consent expired "
            "(run `exchange` with a new code), App REST APIs are off for Fieldify in Connected apps, "
            "the account is not allowed, or the integration lacks a scope."
        )
    return f"{status} without an error body. The call may have run out of time; try again."


# ---------- Tasks ----------


def list_fields(settings):
    """Print the File Fields on the site: the id other commands take, and the name."""
    _, answer = call(settings, "GET", "/v1/fields")
    for field in answer["fields"]:
        print(f"{field['id']}  {field['name']}")
    if not answer["fields"]:
        print("No File Fields on this site.")


def list_files(settings, issue, field):
    """Return the field's current files on the work item (key such as SUP-12, or id)."""
    query = urllib.parse.urlencode({"issue": issue, "field": field})
    _, answer = call(settings, "GET", "/v1/files?" + query)
    return answer["files"]


def show_files(settings, issue, field):
    """Print one line per file: name, size, when it was added, number of versions."""
    files = list_files(settings, issue, field)
    for file in files:
        name = file.get("filename") or "(no name)"
        added = file.get("uploadedAt") or "unknown"
        print(f"{name}  {file.get('size')} bytes  added {added}  versions {file.get('versions')}")
    if not files:
        print("No files in this field.")


def download_files(settings, issue, field, folder):
    """Download every file of the field into `folder`.

    POST /v1/files/links gives a one-hour link per file. Anyone holding a link
    can download the file, so the script never prints or logs it. The link
    points to another host: it is fetched without the access token. A file
    already in the folder is never overwritten.
    """
    file_ids = [file["fileId"] for file in list_files(settings, issue, field)]
    if not file_ids:
        print("No files in this field.")
        return
    os.makedirs(folder, exist_ok=True)
    number = 0
    failed = 0
    while file_ids:
        batch, file_ids = file_ids[:MAX_LINKS_PER_CALL], file_ids[MAX_LINKS_PER_CALL:]
        _, answer = call(settings, "POST", "/v1/files/links", {"issue": issue, "field": field, "fileIds": batch})
        for link in answer.get("links", []):
            number += 1
            if not save_link(link, folder, number):
                failed += 1
        for error in answer.get("errors", []):
            failed += 1
            print(f"Not downloaded: {error.get('code')}: {error.get('message')}")
        # Ids the call had no time for come back in notProcessed: ask for them again.
        not_processed = answer.get("notProcessed", [])
        if not_processed and len(not_processed) == len(batch):
            raise FieldifyError("The links call made no progress. Try again later.")
        file_ids = not_processed + file_ids
    if failed:
        raise FieldifyError(
            f"{failed} file(s) not downloaded. Run the command again, into an empty folder if files were already there."
        )


def save_link(link, folder, number):
    """Fetch one download link and write the file into `folder`; never overwrites a file.

    Return False if the download failed or the name is already taken in the folder.
    """
    try:
        name = safe_name(link.get("filename") or "")
    except ValueError:
        name = f"file-{number}"
    try:
        # A plain request: no Authorization header goes to the download host.
        status, _, data = send(urllib.request.Request(link["url"]))
        if status != 200:
            print(f"{name}: download failed ({status})")
            return False
        with open(os.path.join(folder, name), "xb") as target:  # "x": fails if the file exists
            target.write(data)
    except FileExistsError:
        print(f"{name}: a file with this name is already in the folder; not overwritten")
        return False
    except (ValueError, OSError, http.client.HTTPException) as error:
        # The type only: the error's text can hold the link.
        print(f"{name}: download failed ({type(error).__name__})")
        return False
    print(f"{name}: {len(data)} bytes")
    return True


def safe_name(name: str) -> str:
    """The file name without any folder part, so a download never writes outside its folder.

    Both / and \\ count as separators on every system, and a colon (a drive
    letter on Windows) and control characters become "_". Trailing dots and
    spaces are dropped, as Windows drops them. Raises ValueError when nothing
    usable is left ("", "." or "..").
    """
    base = name.replace("\\", "/").split("/")[-1].replace(":", "_")
    base = "".join("_" if ord(char) < 0x20 or char == "\x7f" else char for char in base)
    base = base.strip().rstrip(". ")
    if base in ("", ".", ".."):
        raise ValueError("no usable file name")
    return base


def upload_file(settings, issue, field, path):
    """Add a file of up to 3,500,000 bytes, sent in the request as base64.

    In a one-file field it replaces the current file; in other fields it is
    added next to the others. Sending the same name and bytes again changes
    nothing (mode "unchanged"), so a retry is safe.
    """
    size = os.path.getsize(path)
    if size > MAX_UPLOAD_BYTES:
        raise FieldifyError(
            f"The file has {size:,} bytes; upload takes at most {MAX_UPLOAD_BYTES:,}. Use the import command."
        )
    with open(path, "rb") as source:
        content = source.read()
    body = {
        "issue": issue,
        "field": field,
        "filename": os.path.basename(path),
        "contentBase64": base64.b64encode(content).decode("ascii"),
    }
    mime_type = mimetypes.guess_type(path)[0]
    if mime_type:
        body["mimeType"] = mime_type
    _, answer = call(settings, "POST", "/v1/files/upload", body)
    print(describe_write(answer))


def import_file(settings, issue, field, path):
    """Add a file larger than the upload takes, up to the field's own size limit.

    Three steps: attach the file to the work item with Jira's REST API, let
    Fieldify copy the attachment into the field, delete the attachment. The
    attachment is deleted even when the import fails or takes too long.
    """
    attachment_id = add_attachment(settings, issue, path)
    try:
        body = {"issue": issue, "field": field, "attachmentId": attachment_id}
        _, job = call(settings, "POST", "/v1/files/import", body)
        job = wait_for_import(settings, job)
    finally:
        delete_attachment(settings, attachment_id)
    if job["status"] == "failed":
        error = job.get("error") or {}
        raise FieldifyError(f"The import failed: {error.get('code')}: {error.get('message')}")
    print(describe_write(job["result"]))


def jira_url(settings, path):
    """An address in Jira's REST API for this site, through api.atlassian.com."""
    return f"https://api.atlassian.com/ex/jira/{settings['cloud_id']}/rest/api/3{path}"


def add_attachment(settings, issue, path):
    """Attach the file to the work item with Jira's REST API; return the attachment id.

    Jira takes a multipart form with one part named "file", and the
    X-Atlassian-Token: no-check header.
    """
    with open(path, "rb") as source:
        content = source.read()
    filename = os.path.basename(path).replace('"', "%22")
    mime_type = mimetypes.guess_type(path)[0] or "application/octet-stream"
    boundary = uuid.uuid4().hex
    body = (
        (
            f"--{boundary}\r\n"
            f'Content-Disposition: form-data; name="file"; filename="{filename}"\r\n'
            f"Content-Type: {mime_type}\r\n"
            "\r\n"
        ).encode("utf-8")
        + content
        + f"\r\n--{boundary}--\r\n".encode("ascii")
    )
    request = urllib.request.Request(
        jira_url(settings, f"/issue/{urllib.parse.quote(issue, safe='')}/attachments"),
        data=body,
        method="POST",
        headers={
            "Content-Type": f"multipart/form-data; boundary={boundary}",
            "X-Atlassian-Token": "no-check",
            "Accept": "application/json",
        },
    )
    status, _, data = send(with_token(request, settings))
    if status != 200:
        raise FieldifyError(
            f"Jira did not add the attachment ({status}). The import needs the read:jira-work and "
            f"write:jira-work scopes, and an account that may add attachments to {issue}."
        )
    return json.loads(data)[0]["id"]


def wait_for_import(settings, job):
    """Ask for the import's status at its statusPath until it has succeeded or failed.

    Each 202 answer says how long to wait before asking again: the Retry-After
    header, which the body repeats as retryAfterSeconds. Gives up after 10 minutes.
    """
    status_path = job["statusPath"]
    give_up_at = time.monotonic() + IMPORT_TIMEOUT_SECONDS
    while job["status"] in ("queued", "running"):
        if time.monotonic() > give_up_at:
            raise FieldifyError(
                "The import did not finish within 10 minutes. Run the command again: "
                "if the first copy finished meanwhile, the second changes nothing."
            )
        print(f"Import {job['status']}...")
        time.sleep(job.get("retryAfterSeconds", DEFAULT_WAIT_SECONDS))
        _, job = call(settings, "GET", status_path)
    return job


def delete_attachment(settings, attachment_id):
    """Delete the temporary attachment with Jira's REST API. Reports a failure, never raises one."""
    request = urllib.request.Request(jira_url(settings, f"/attachment/{attachment_id}"), method="DELETE")
    try:
        status, _, _ = send(with_token(request, settings))
    except OSError:
        status = "no answer"
    except SystemExit as error:
        status = f"no access token: {error}"
    if status in (200, 204):
        print("Deleted the temporary attachment.")
    else:
        print(f"Could not delete the temporary attachment {attachment_id} ({status}). Delete it on the work item.")


def describe_write(result):
    """One line about a write: replaced, appended or unchanged, and the file."""
    file = result["file"]
    text = f"{result['mode']}: {file.get('filename')} ({file.get('size')} bytes)"
    if result.get("replacedFileIds"):
        text += f", replacing {len(result['replacedFileIds'])} file(s)"
    return text


# ---------- Command line ----------


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    commands = parser.add_subparsers(dest="command", required=True, metavar="command")

    def work_item_and_field(command):
        command.add_argument("issue", help="work item key or id, for example SUP-12")
        command.add_argument("field", help="File Field id, for example customfield_10123 (see fields)")
        return command

    exchange = commands.add_parser("exchange", help="once: trade the code from the consent for tokens")
    exchange.add_argument("code", help="the code parameter of the address the consent sends you to")
    commands.add_parser("fields", help="list the File Fields on the site")
    work_item_and_field(commands.add_parser("files", help="list the files in a field on a work item"))
    download = work_item_and_field(commands.add_parser("download", help="download those files into a folder"))
    download.add_argument("folder", help="where to write the files (created if missing)")
    upload = work_item_and_field(commands.add_parser("upload", help="add a file of up to 3,500,000 bytes"))
    upload.add_argument("path", help="the file to add")
    import_ = work_item_and_field(commands.add_parser("import", help="add a larger file through a Jira attachment"))
    import_.add_argument("path", help="the file to add")

    args = parser.parse_args()
    settings = load_settings()
    try:
        if args.command == "exchange":
            exchange_code(settings, args.code)
        elif args.command == "fields":
            list_fields(settings)
        elif args.command == "files":
            show_files(settings, args.issue, args.field)
        elif args.command == "download":
            download_files(settings, args.issue, args.field, args.folder)
        elif args.command == "upload":
            upload_file(settings, args.issue, args.field, args.path)
        elif args.command == "import":
            import_file(settings, args.issue, args.field, args.path)
    except (FieldifyError, OSError) as error:
        sys.exit(f"Error: {error}")


if __name__ == "__main__":
    main()
