#!/usr/bin/env python3 import sys import time import uuid from pprint import pprint import requests import argparse import os.path try: from colors import color except ImportError: def color(text, *args, **kwargs): return text try: from fsdb import Fsdb except ImportError: Fsdb = None def err(msg): print(color(msg, fg='red', style='bold')) def is_group_subscribed(mSubscribeFlags): return bool(mSubscribeFlags & 4) def req(args, location, data=None): kwargs = {} if data is not None: kwargs["json"] = data r = requests.post( args.endpoint + location, auth=tuple(args.auth.split(":", 2)), **kwargs ) r.raise_for_status() # TODO: handle r.status_code != 200 return r def main_forum_list(args): r = req(args, "/rsGxsForums/getForumsSummaries") forums = r.json()["forums"] for item in forums: if is_group_subscribed(item["mSubscribeFlags"]): if "notsubscribed" in args.select: continue style = "bold" else: if "subscribed" in args.select: continue style = None print(color(item["mGroupName"], style=style, fg="green")) print(" " + color(item["mGroupId"], style="underline")) def main_forum_read(args): r = req(args, "/rsGxsForums/getForumMsgMetaData", {"forumId": args.forum_id}) items = r.json()["msgMetas"] if args.long: msgs = [item["mMsgId"] for item in items[: args.num_posts]] items_r = req( args, "/rsGxsForums/getForumContent", {"forumId": args.forum_id, "msgsIds": msgs}, ) items = items_r.json()["msgs"] for item in items: print(color(item["mMeta"]["mMsgName"], style="bold", fg="green")) print() print(item["mMsg"]) # TODO: html2txt print() else: for item in posts[: args.num_posts]: print(color(item["mMsgName"], style="bold", fg="green")) print(" " + color(item["mMsgId"], style="underline")) def main_channel_list(args): r = req(args, "/rsGxsChannels/getChannelsSummaries") channels = r.json()["channels"] for item in channels: if is_group_subscribed(item["mSubscribeFlags"]): if "notsubscribed" in args.select: continue style = "bold" else: if "subscribed" in args.select: continue style = None print(color(item["mGroupName"], style=style, fg="green")) print(" " + color(item["mGroupId"], style="underline")) def main_channel_read(args): r = req(args, "/rsGxsChannels/getContentSummaries", {"channelId": args.channel_id}) posts = r.json()["summaries"] if args.long: msgs = [post["mMsgId"] for post in posts[: args.num_posts]] posts_r = req( args, "/rsGxsChannels/getChannelContent", {"channelId": args.channel_id, "contentsIds": msgs}, ) posts = posts_r.json()["posts"] for post in posts: print(color(post["mMeta"]["mMsgName"], style="bold", fg="green")) print() print(post["mMsg"]) print() else: for post in posts[: args.num_posts]: print(color(post["mMsgName"], style="bold", fg="green")) print(" " + color(post["mMsgId"], style="underline")) def main_channel_show(args): r = req(args, "/rsGxsChannels/getChannelsInfo", {"chanIds": [args.channel_id]}) data = r.json() channels = data["channelsInfo"] for chan in channels: print(color(chan["mMeta"]["mGroupName"], style="bold", fg="green")) print(" " + color(chan["mMeta"]["mGroupId"], style="underline")) print(" " + chan["mDescription"]) print(color("Last Post:", style="bold") + " \t%s" % chan["mMeta"]["mLastPost"]) def main_channel_post_v1(args): chid = args.channel_id r = req( args, "/rsGxsChannels/createPost", { "post": { "mMeta": {"mGroupId": args.channel_id, "mMsgName": args.post_title}, "mMsg": args.post_body, } }, ) if r.status_code != 200: print(color("ERROR: could not create post", fg="red", style="bold")) print("Error %d" % r.status_code) sys.exit(1) ret = r.json() if ret.get("retval", True) is False: print(color("ERROR: could not create post", fg="red", style="bold")) pprint(ret) sys.exit(1) pprint(ret) def main_channel_post(args): chid = args.channel_id try: r = req( args, "/rsGxsChannels/createPostV2", { "channelId": args.channel_id, "title": args.post_title, "mBody": args.post_body, }, ) except requests.exceptions.HTTPError as exc: if exc.response.status_code != 404: raise else: ret = r.json() if ret.get("retval", True) is False: print(color("ERROR: could not create post", fg="red", style="bold")) print(ret["errorMessage"]) pprint(ret) sys.exit(1) pprint(ret) return main_channel_post_v1(args) def _file_publish(args, fnames): if Fsdb is None: raise Exception('ERROR: library Fsdb is needed for file publishing') store_dir = os.path.expanduser('~/.config/rscli/store/default') fsdb = Fsdb(store_dir, fmode='660') virtualname_path = os.path.join(store_dir, 'virtualname.txt') if os.path.exists(virtualname_path): virtualname = open(virtualname_path).read().strip() else: virtualname = 'rscli-%s' % uuid.uuid4() open(virtualname_path, 'w').write(virtualname) r = req(args, '/rsFiles/getSharedDirectories') if virtualname not in [shared['virtualname'] for shared in r.json()['dirs']]: r = req(args, '/rsFiles/addSharedDirectory', {'dir':{ 'filename': store_dir, 'virtualname': virtualname }}) if not r.json()['retval']: raise Exception("Error: could not create shared dir for default store") r = req(args, '/rsFiles/getSharedDirectories') dir_filename = [d['filename'] for d in r.json()['dirs'] if d['virtualname'] == virtualname][0] r = req(args, '/rsFiles/requestDirDetails', { 'handle': 0 }) children = [c for c in r.json()['details']['children'] if c['name'] != '[Extra List]'] for possibile_root in children: r = req(args, '/rsFiles/requestDirDetails', { 'handle': possibile_root['handle'] }) found = [c for c in r.json()['details']['children'] if c['name'] == dir_filename] if not found: raise Exception ('Error: could not find shared file in RS') handle = found[0]['handle'] for fname in fnames: digest = fsdb.add(fname) r = req(args, '/rsFiles/ForceDirectoryCheck') time.sleep(5) # mo lo ricerchiamo va looking_for = os.path.relpath(fsdb.get_file_path(digest), store_dir).split(os.path.sep) for next_component in looking_for: r = req(args, '/rsFiles/requestDirDetails', { 'handle': handle }) found = [c for c in r.json()['details']['children'] if c['name'] == next_component] if not found: raise Exception('Error: could not find shared file in RS') handle = found[0]['handle'] r = req(args, '/rsFiles/requestDirDetails', { 'handle': handle }) filehash = r.json()['details']['hash'] yield filehash def main_file_publish(args): ret = _file_publish(args, args.fnames) for filehash, fname in zip(ret, args.fnames): print(color(filehash, fg='green') + ' \t%s' % fname) def get_parser(): p = argparse.ArgumentParser() p.add_argument("--endpoint", default="http://127.0.0.1:9092") p.add_argument("-u", "--auth", dest="auth") p_sub = p.add_subparsers() ch = p_sub.add_parser("channel") ch.add_argument("--channel-id") ch_sub = ch.add_subparsers() ch_list = ch_sub.add_parser("list") ch_list.add_argument( "--select", nargs="+", choices=["all", "subscribed", "notsubscribed"], default=["all"], ) ch_list.set_defaults(mainfunc=main_channel_list) ch_show = ch_sub.add_parser("show") ch_show.set_defaults(mainfunc=main_channel_show) ch_read = ch_sub.add_parser("read") ch_read.add_argument("--long", action="store_true", default=False) ch_read.add_argument("--num-posts", type=int, default=10) ch_read.set_defaults(mainfunc=main_channel_read) ch_post = ch_sub.add_parser("post") ch_post.set_defaults(mainfunc=main_channel_post) ch_post.add_argument("--post-title") ch_post.add_argument("--post-body") forum = p_sub.add_parser("forum") forum.add_argument("--forum-id") forum_sub = forum.add_subparsers() forum_list = forum_sub.add_parser("list") forum_list.add_argument( "--select", nargs="+", choices=["all", "subscribed", "notsubscribed"], default=["all"], ) forum_list.set_defaults(mainfunc=main_forum_list) forum_read = forum_sub.add_parser("read") forum_read.add_argument("--long", action="store_true", default=False) forum_read.add_argument("--num-posts", type=int, default=10) forum_read.set_defaults(mainfunc=main_forum_read) files = p_sub.add_parser("file") files_sub = files.add_subparsers() files_list = files_sub.add_parser("publish") files_list.add_argument( "--fname", nargs="+", required=True, dest='fnames' ) files_list.set_defaults(mainfunc=main_file_publish) # TODO: channel rss -> read and convert to rss return p def main(): p = get_parser() args = p.parse_args() if getattr(args, "mainfunc", None) is None: print("Not a complete command") sys.exit(2) args.mainfunc(args) if __name__ == "__main__": main()