# Path: src/petmail/scripts/webwait.py
# def command(basedir, command, args, err=sys.stderr):
#     if _debug_no_http:
#         return _debug_no_http(command, args)
#     url, token = get_url_and_token(basedir, err)
#     if not url:
#         return False, {"err": "Error, node is not yet running"}
#     body = json.dumps({"token": token,
#                        "args": args,
#                        }).encode("utf-8")
#     resp = do_http("POST", url+"api/%s" % command, body)
#     # The web API can return three things:
#     #  200 (success) with a JSON body, including ["ok"] for the CLI user
#     #  400 (error) with a string body (no trailing newline)
#     #  anything else (worse error) with a string body
#     #
#     # This CLI helper always returns the same thing: (errp,json), where
#     # json["err"] is the error string (with trailing newline). Since 500s
#     # usually have messy (HTML-formatted) tracebacks, we hide the body and
#     # refer the user to the node logs instead. On 400s we present the whole
#     # thing, since it's presumably been nicely formatted by the node already.
# 
#     http_status = "HTTP status: %d %s\n" % (resp.status, resp.reason)
#     if resp.status == 200:
#         return True, json.loads(resp.read().decode("utf-8"))
#     elif resp.status == 400:
#         return False, {"err": http_status+resp.read()+"\n"}
#     else:
#         return False, {"err": http_status+"Please see node logs for details\n"}
# 
# def follow_events(basedir, topic, catchup=False, err=sys.stderr):
#     if _debug_no_http:
#         raise RuntimeError("unit-test support not implemented yet")
#     baseurl, token = get_url_and_token(basedir, err)
#     if not baseurl:
#         return False, {"err": "Error, node is not yet running"}
#     # first, create the event channel
#     resp = do_http("POST", baseurl + "api/eventchannel-create",
#                    json.dumps({"token": token}))
#     if resp.status != 200:
#         raise RuntimeError("unable to create event channel: %s %s"
#                            % (resp.status, resp.reason))
#     r = json.loads(resp.read().decode("utf-8"))
#     esid = r["esid"]
#     # we'll listen on this one
#     event_resp = do_http("GET", baseurl + "api/events/%s" % esid,
#                          event_stream=True)
#     # and then subscribe to hear about events. I'm not 100% sure this won't
#     # race (the web frontend specifically waits until a "ready" event is
#     # delivered, to make sure the browser has established the EventSource
#     # channel, before subscribing to anything. We're ok as long as do_http()
#     # doesn't return until after it's seen the HTTP headers.
#     resp = do_http("POST", baseurl + "api/eventchannel-subscribe",
#                    json.dumps({"token": token,
#                                "args": {"esid": esid,
#                                         "topic": topic,
#                                         "catchup": catchup}}))
#     if resp.status != 200:
#         raise RuntimeError("unable to subscribe to event channel: %s %s"
#                            % (resp.status, resp.reason))
# 
#     return event_resp
# 
# def get_field(r):
#     first_line = get_line(r)
#     fieldname, data = first_line.split(": ", 1)
#     lines = [data]
#     while True:
#         line = get_line(r)
#         if not line:
#             return fieldname, "\n".join(lines)
#         lines.append(line)
# 
# class EOFError(Exception):
#     pass


import json
from .webwait import command, follow_events, get_field, EOFError

def invite(so, stdout, stderr, offer_mailbox=False, accept_mailbox=False):
    args = {"petname": so.get("petname"),
            "code": so.get("code")}
    if offer_mailbox:
        args["offer_mailbox"] = True
    if accept_mailbox:
        args["accept_mailbox"] = True
    ok, result = command(so["basedir"], "invite", args, stderr)
    if not ok:
        print >>stderr, result["err"]
        return 1
    cid = result["contact-id"]
    if so.get("code") is not None:

# Path: src/petmail/scripts/webwait.py
# def command(basedir, command, args, err=sys.stderr):
#     if _debug_no_http:
#         return _debug_no_http(command, args)
#     url, token = get_url_and_token(basedir, err)
#     if not url:
#         return False, {"err": "Error, node is not yet running"}
#     body = json.dumps({"token": token,
#                        "args": args,
#                        }).encode("utf-8")
#     resp = do_http("POST", url+"api/%s" % command, body)
#     # The web API can return three things:
#     #  200 (success) with a JSON body, including ["ok"] for the CLI user
#     #  400 (error) with a string body (no trailing newline)
#     #  anything else (worse error) with a string body
#     #
#     # This CLI helper always returns the same thing: (errp,json), where
#     # json["err"] is the error string (with trailing newline). Since 500s
#     # usually have messy (HTML-formatted) tracebacks, we hide the body and
#     # refer the user to the node logs instead. On 400s we present the whole
#     # thing, since it's presumably been nicely formatted by the node already.
# 
#     http_status = "HTTP status: %d %s\n" % (resp.status, resp.reason)
#     if resp.status == 200:
#         return True, json.loads(resp.read().decode("utf-8"))
#     elif resp.status == 400:
#         return False, {"err": http_status+resp.read()+"\n"}
#     else:
#         return False, {"err": http_status+"Please see node logs for details\n"}
# 
# def follow_events(basedir, topic, catchup=False, err=sys.stderr):
#     if _debug_no_http:
#         raise RuntimeError("unit-test support not implemented yet")
#     baseurl, token = get_url_and_token(basedir, err)
#     if not baseurl:
#         return False, {"err": "Error, node is not yet running"}
#     # first, create the event channel
#     resp = do_http("POST", baseurl + "api/eventchannel-create",
#                    json.dumps({"token": token}))
#     if resp.status != 200:
#         raise RuntimeError("unable to create event channel: %s %s"
#                            % (resp.status, resp.reason))
#     r = json.loads(resp.read().decode("utf-8"))
#     esid = r["esid"]
#     # we'll listen on this one
#     event_resp = do_http("GET", baseurl + "api/events/%s" % esid,
#                          event_stream=True)
#     # and then subscribe to hear about events. I'm not 100% sure this won't
#     # race (the web frontend specifically waits until a "ready" event is
#     # delivered, to make sure the browser has established the EventSource
#     # channel, before subscribing to anything. We're ok as long as do_http()
#     # doesn't return until after it's seen the HTTP headers.
#     resp = do_http("POST", baseurl + "api/eventchannel-subscribe",
#                    json.dumps({"token": token,
#                                "args": {"esid": esid,
#                                         "topic": topic,
#                                         "catchup": catchup}}))
#     if resp.status != 200:
#         raise RuntimeError("unable to subscribe to event channel: %s %s"
#                            % (resp.status, resp.reason))
# 
#     return event_resp
# 
# def get_field(r):
#     first_line = get_line(r)
#     fieldname, data = first_line.split(": ", 1)
#     lines = [data]
#     while True:
#         line = get_line(r)
#         if not line:
#             return fieldname, "\n".join(lines)
#         lines.append(line)
# 
# class EOFError(Exception):
#     pass


# Path: src/petmail/scripts/invite.py
import json
from .webwait import command, follow_events, get_field, EOFError


def invite(so, stdout, stderr, offer_mailbox=False, accept_mailbox=False):
    args = {"petname": so.get("petname"),
            "code": so.get("code")}
    if offer_mailbox:
        args["offer_mailbox"] = True
    if accept_mailbox:
        args["accept_mailbox"] = True
    ok, result = command(so["basedir"], "invite", args, stderr)
    if not ok:
        print >>stderr, result["err"]
        return 1
    cid = result["contact-id"]
    if so.get("code") is not None:

        stdout.write("Invitation code: %s\n" % so["code"])