123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314 |
- #!/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()
|