comments.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. #####################################################################
  2. # #
  3. # THIS IS A SOURCE CODE FILE FROM A PROGRAM TO INTERACT WITH THE #
  4. # LBRY PROTOCOL ( lbry.com ). IT WILL USE THE LBRY SDK ( lbrynet ) #
  5. # FROM THEIR REPOSITORY ( https://github.com/lbryio/lbry-sdk ) #
  6. # WHICH I GONNA PRESENT TO YOU AS A BINARY. SINCE I DID NOT DEVELOP #
  7. # IT AND I'M LAZY TO INTEGRATE IN A MORE SMART WAY. THE SOURCE CODE #
  8. # OF THE SDK IS AVAILABLE IN THE REPOSITORY MENTIONED ABOVE. #
  9. # #
  10. # ALL THE CODE IN THIS REPOSITORY INCLUDING THIS FILE IS #
  11. # (C) J.Y.Amihud and Other Contributors 2021. EXCEPT THE LBRY SDK. #
  12. # YOU CAN USE THIS FILE AND ANY OTHER FILE IN THIS REPOSITORY UNDER #
  13. # THE TERMS OF GNU GENERAL PUBLIC LICENSE VERSION 3 OR ANY LATER #
  14. # VERSION. TO FIND THE FULL TEXT OF THE LICENSE GO TO THE GNU.ORG #
  15. # WEBSITE AT ( https://www.gnu.org/licenses/gpl-3.0.html ). #
  16. # #
  17. # THE LBRY SDK IS UNFORTUNATELY UNDER THE MIT LICENSE. IF YOU ARE #
  18. # NOT INTENDING TO USE MY CODE AND JUST THE SDK. YOU CAN FIND IT ON #
  19. # THEIR OFFICIAL REPOSITORY ABOVE. THEIR LICENSE CHOICE DOES NOT #
  20. # SPREAD ONTO THIS PROJECT. DON'T GET A FALSE ASSUMPTION THAT SINCE #
  21. # THEY USE A PUSH-OVER LICENSE, I GONNA DO THE SAME. I'M NOT. #
  22. # #
  23. # THE LICENSE CHOSEN FOR THIS PROJECT WILL PROTECT THE 4 ESSENTIAL #
  24. # FREEDOMS OF THE USER FURTHER, BY NOT ALLOWING ANY WHO TO CHANGE #
  25. # THE LICENSE AT WILL. SO NO PROPRIETARY SOFTWARE DEVELOPER COULD #
  26. # TAKE THIS CODE AND MAKE THEIR USER-SUBJUGATING SOFTWARE FROM IT. #
  27. # #
  28. #####################################################################
  29. import time
  30. import json
  31. import threading
  32. import urllib.request
  33. from gi.repository import Gtk
  34. from gi.repository import Gdk
  35. from gi.repository import GLib
  36. from gi.repository import Pango
  37. from gi.repository import GdkPixbuf
  38. from flbry import markdown
  39. from flbry import ui
  40. from flbry import fetch
  41. # TODO: Get rid of this string and use win.settings["comment_api"] instead
  42. comments_api = "https://comments.odysee.com/api/v2"
  43. # This is going into the end of comments to promote FastLBRY GTK
  44. BUTTON_GTK_PROMOTE = "\n\n[![](https://player.odycdn.com/api/v4/streams/free/button_GTK/d025c8ec2cdb5122a85b374b7bc453ba11d9409d/6526ef)](https://notabug.org/jyamihud/FastLBRY-GTK)"
  45. def list_comments( win, claim_id, page=1, megabox=False):
  46. # gets list of comment
  47. params = {
  48. "claim_id": claim_id,
  49. "page": page,
  50. # "page_size": page_size,
  51. "sort_by": 0,
  52. "top_level": False,
  53. }
  54. time.sleep(1) # too fast
  55. out = comment_request("comment.List", params)
  56. out = get_reactions(out)
  57. return [win, out, megabox]
  58. def render_single_comment(win, box, i):
  59. items = win.commenting[i["claim_id"]]["data"]["result"]["items"]
  60. # Like / Dislike ratio
  61. reactionbox = Gtk.HBox()
  62. like_dislike_ratio_box = Gtk.VBox()
  63. like_dislike_box = Gtk.HBox()
  64. likes = i.get("reactions", {}).get("like", 0)
  65. like = Gtk.ToggleButton(" 👍 "+str(likes)+" ")
  66. like.set_relief(Gtk.ReliefStyle.NONE)
  67. like_dislike_box.pack_start(like, False, False, 0)
  68. dislikes = i.get("reactions", {}).get("dislike", 0)
  69. dislike = Gtk.ToggleButton(" 👎 "+str(dislikes)+" ")
  70. dislike.set_relief(Gtk.ReliefStyle.NONE)
  71. like_dislike_box.pack_start(dislike, False, False, 0)
  72. like_dislike_ratio_box.pack_start(like_dislike_box, False, False, False)
  73. try:
  74. frac = likes / (likes + dislikes)
  75. except:
  76. frac = 0
  77. ratio_bar = Gtk.ProgressBar()
  78. ratio_bar.set_fraction(frac)
  79. like_dislike_ratio_box.pack_start(ratio_bar, True, True,0)
  80. reactionbox.pack_start(like_dislike_ratio_box, False, False, False)
  81. ########### REPLY ############
  82. def reply_set(w):
  83. for ch in win.commenting["reply"]["box"].get_children():
  84. ch.destroy()
  85. win.commenting["reply"]["to"] = i["comment_id"]
  86. reply_frame = Gtk.Frame(label=" Replying to: ")
  87. reply_frame.set_shadow_type(Gtk.ShadowType.ETCHED_OUT)
  88. reply_box = Gtk.HBox()
  89. reply_frame.add(reply_box)
  90. chbox = Gtk.HBox()
  91. channel_button = ui.load(win, resolve_channel, render_channel, win, i["channel_url"])
  92. chbox.pack_start(channel_button, False, False, 0)
  93. reply_box.pack_start(chbox, False, False, 4)
  94. comment_label = Gtk.Label(i["comment"].split("\n")[0][:100]+" ...")
  95. comment_label.set_line_wrap_mode( Gtk.WrapMode.WORD )
  96. comment_label.set_line_wrap(True)
  97. reply_box.pack_start(comment_label, False, False, 10)
  98. win.commenting["reply"]["box"].pack_start(reply_frame, True, True, 5)
  99. ##### DELETE REPLY ####
  100. def delete_set(w):
  101. for ch in win.commenting["reply"]["box"].get_children():
  102. ch.destroy()
  103. win.commenting["reply"]["to"] = ""
  104. delete = Gtk.Button()
  105. delete.connect("clicked", delete_set)
  106. delete.set_relief(Gtk.ReliefStyle.NONE)
  107. delete.add(ui.icon(win, "edit-delete"))
  108. win.commenting["reply"]["box"].pack_end(delete, False, False, 0)
  109. win.commenting["reply"]["box"].show_all()
  110. reply = Gtk.Button(" Reply ")
  111. reply.set_relief(Gtk.ReliefStyle.NONE)
  112. reply.connect("clicked", reply_set)
  113. reactionbox.pack_end(reply, False, False, False)
  114. box.pack_end(reactionbox, False, False, 0)
  115. # TODO: Figure out how to keep textview from expanding sideways
  116. # and use the commented out code to make markdown comments work
  117. #commentbox = Gtk.ScrolledWindow()
  118. # commentbox = Gtk.Frame(label="Frame")
  119. # #commentbox.set_size_request(0,200)
  120. # comment_field = Gtk.TextView()
  121. # comment_field.set_wrap_mode(Gtk.WrapMode.WORD )
  122. # comment_field.set_editable(False)
  123. # comment_field.set_hexpand(False)
  124. # comment_buffer = comment_field.get_buffer()
  125. # comment_buffer.set_text(i["comment"])
  126. # markdown.convert(win, comment_field)
  127. # commentbox.add(comment_field)
  128. # box.pack_end(commentbox, True, True, 0)
  129. comment_text = i["comment"]
  130. supporter = False
  131. if BUTTON_GTK_PROMOTE in comment_text:
  132. supporter = True
  133. comment_text = comment_text.replace(BUTTON_GTK_PROMOTE, "")
  134. comment_label = Gtk.Label(comment_text)
  135. comment_label.set_selectable(True)
  136. comment_label.set_line_wrap_mode( Gtk.WrapMode.WORD )
  137. comment_label.set_line_wrap(True)
  138. comment_label.set_max_width_chars(20)
  139. box.pack_end(comment_label, True, True, 10)
  140. def resolve_channel(win, url):
  141. out = fetch.lbrynet("resolve", {"urls":url})
  142. out = out[url]
  143. return [win, out]
  144. def render_channel(out):
  145. win, out = out
  146. return ui.go_to_channel(win, out)
  147. # Sometimes it's a reply
  148. if "parent_id" in i:
  149. for b in items:
  150. if b["comment_id"] == i["parent_id"]:
  151. expand = Gtk.Expander(label=" In Reply to: ")
  152. reply_frame = Gtk.Frame()
  153. expand.add(reply_frame)
  154. reply_frame.set_shadow_type(Gtk.ShadowType.ETCHED_OUT)
  155. reply_box = Gtk.VBox()
  156. reply_frame.add(reply_box)
  157. if "channel_url" in b:
  158. chbox = Gtk.HBox()
  159. channel_button = ui.load(win, resolve_channel, render_channel, win, b["channel_url"])
  160. chbox.pack_start(channel_button, False, False, 0)
  161. reply_box.pack_start(chbox, True, False, 4)
  162. comment_label = Gtk.Label(b["comment"].replace(BUTTON_GTK_PROMOTE, ""))
  163. comment_label.set_line_wrap_mode( Gtk.WrapMode.WORD )
  164. comment_label.set_line_wrap(True)
  165. comment_label.set_max_width_chars(20)
  166. reply_box.pack_start(comment_label, True, True, 10)
  167. box.pack_end(expand, True, True, 10)
  168. break
  169. # each channel will need to be resolved on fly
  170. if "channel_url" in i:
  171. chbox = Gtk.HBox()
  172. channel_button = ui.load(win, resolve_channel, render_channel, win, i["channel_url"])
  173. chbox.pack_start(channel_button, False, False, 0)
  174. if "support_amount" in i and i["support_amount"]:
  175. chbox.pack_start(ui.icon(win, "starred"), False, False, 0)
  176. chbox.pack_start(Gtk.Label(" "+str(i["support_amount"])+" LBC"), False, False, 0)
  177. if supporter:
  178. chbox.pack_start(ui.icon(win, "starred"), False, False, 0)
  179. chbox.pack_start(Gtk.Label(" Promoter of FastLBRY "), False, False, 0)
  180. box.pack_end(chbox, False, False, 4)
  181. box.pack_end(Gtk.HSeparator(), False, False, 0)
  182. def render_comments(out, megabox=False):
  183. win, out, megabox = out
  184. if not megabox:
  185. megabox = Gtk.VBox()
  186. megabox.show_all()
  187. # renders a list of comments
  188. box = Gtk.VBox()
  189. box.set_hexpand(False)
  190. # I want to setup a little daemon to update the comments
  191. # automatically
  192. claim_id = win.resolved["claim_id"]
  193. try:
  194. the_title = win.resolved["value"]["title"]
  195. except:
  196. the_title = win.resolved["name"]
  197. if out["result"]["page"] == 1: # If it's the first page
  198. win.commenting[claim_id]["box"] = box
  199. win.commenting[claim_id]["data"] = out
  200. win.check_comment_daemon_keep_alive = True
  201. load_thread = threading.Thread(target=comment_daemon, args=[win, claim_id, the_title])
  202. load_thread.setDaemon(True)
  203. load_thread.start()
  204. def kill_daemon(w):
  205. win.check_comment_daemon_keep_alive = False
  206. box.connect("destroy", kill_daemon)
  207. try:
  208. items = out["result"]["items"]
  209. for i in items:
  210. if i not in win.commenting[claim_id]["data"]["result"]["items"]:
  211. win.commenting[claim_id]["data"]["result"]["items"].append(i)
  212. except:
  213. items = []
  214. for i in reversed(items):
  215. #print("\n\n:::::::::::::::::\n\n", i)
  216. render_single_comment(win, box, i)
  217. box.show_all()
  218. # The top level box containing about 50 comments
  219. megabox.pack_start(box, False, False, 0)
  220. lastthing(win, out, megabox)
  221. megabox.show_all()
  222. return megabox
  223. def comment_daemon(win, claim_id, the_title=""):
  224. # This function will be a daemon for the current comment system to
  225. # load all new comments that happen while the user it on the page.
  226. while win.commenting[claim_id]["keep_alive"]:
  227. time.sleep(2) # Update every two seconds ( I don't want it to crash )
  228. n = win.commenting[claim_id]["data"]
  229. try:
  230. claim_id = n["result"]["items"][0]["claim_id"]
  231. except:
  232. n["result"]["items"] = []
  233. continue
  234. win, out, megabox = list_comments(win, claim_id)
  235. ##### LOGIC OF ADDING MISSING COMMENTS INTO THE BOX ####
  236. for i in reversed(out["result"]["items"]):
  237. if i not in n["result"]["items"]:
  238. ids = []
  239. for b in n["result"]["items"]:
  240. ids.append(b["comment_id"])
  241. ######## FOUND A NEW COMMENT #######
  242. if i["comment_id"] not in ids:
  243. try:
  244. channel = i["channel_name"]
  245. except:
  246. channel = "[anonymous]"
  247. text = i["comment"]
  248. print("COMMENT FROM ", channel, "IS", text)
  249. force = win.resolved["claim_id"] != claim_id
  250. ui.notify(win, channel+" Commented on "+the_title, text, force=force)
  251. win.commenting[claim_id]["data"]["result"]["items"].append(i)
  252. print(i["comment_id"])
  253. box = win.commenting[claim_id]["box"]
  254. def render(win, box, i):
  255. render_single_comment(win, box, i)
  256. box.show_all()
  257. GLib.idle_add(render, win, box, i)
  258. def br(w):
  259. if not win.commenting[claim_id]["listen"]:
  260. win.commenting[claim_id]["keep_alive"] = False
  261. win.commenting[claim_id]["box"].connect("destroy", br)
  262. def lastthing(win, out, megabox):
  263. # This will hack itself to load more comments when you reached the end.
  264. spinner_more = ui.icon(win, "loading", "gif")
  265. megabox.pack_start(spinner_more, False, False, 0)
  266. def draw_event(w, e):
  267. print("EVENT")
  268. w.destroy()
  269. try:
  270. claim_id = out["result"]["items"][0]["claim_id"]
  271. page = out["result"]["page"] + 1
  272. ui.load(win, list_comments, render_comments, win, claim_id, page, megabox, wait=False )
  273. except Exception as e:
  274. print("ERROR IS:", e)
  275. spinner_more.connect("draw", draw_event)
  276. def get_reactions(out):
  277. # Adds reactions list to the out
  278. try:
  279. claim_id = out["result"]["items"][0]["claim_id"]
  280. ids = ""
  281. for i in out["result"]["items"]:
  282. ids = ids + i["comment_id"] + ","
  283. ids = ids[:-1]
  284. except:
  285. return out
  286. rec = {
  287. "claim_id":claim_id,
  288. "comment_ids":ids}
  289. rec = comment_request("reaction.List", rec, addition="?m=reaction.List")
  290. for i in out["result"]["items"]:
  291. try:
  292. i["reactions"] = rec["result"]["others_reactions"][i["comment_id"]]
  293. except:
  294. pass
  295. return out
  296. def comment_request(method: str, params: dict, addition=""):
  297. """
  298. Sends a request to the comment API
  299. """
  300. data = {
  301. "method": method,
  302. "id": 1,
  303. "jsonrpc":"2.0",
  304. "params": params
  305. }
  306. data = json.dumps(data).encode()
  307. headers = {
  308. "Content-Type": "application/json"
  309. }
  310. try:
  311. req = urllib.request.Request(comments_api, data, headers)
  312. res = urllib.request.urlopen(req)
  313. out = res.read().decode()
  314. return json.loads(out)
  315. except Exception as e:
  316. print("COMMENT ERROR:", e)
  317. return
  318. def comment_input(win):
  319. claim_id = win.resolved["claim_id"]
  320. # This is the input for new comments.
  321. vbox = Gtk.VBox()
  322. pannel = Gtk.HBox()
  323. vbox.pack_start(pannel, False, False, False)
  324. ################## LISTEN BUTTON ###############
  325. try:
  326. give_listen = win.commenting[claim_id]["listen"]
  327. except:
  328. give_listen = False
  329. win.commenting[claim_id] = {"box": False,
  330. "data":{},
  331. "listen":give_listen,
  332. "keep_alive":True}
  333. if win.settings["notifications"]:
  334. lbox = Gtk.HBox()
  335. lbox.pack_start(Gtk.Label(" Listen "), False, False, False)
  336. listen = Gtk.Switch()
  337. def lclick(w, u):
  338. win.commenting[claim_id]["listen"] = listen.get_active()
  339. try:
  340. listen.set_active(win.commenting[claim_id]["listen"])
  341. except Exception as e:
  342. print("Switch is:", e)
  343. listen.connect("notify::active", lclick)
  344. lbox.pack_start(listen, False, False, False)
  345. pannel.pack_start(lbox, False, False, False)
  346. if win.channel:
  347. ############# BOX FOR REPLIES ##############
  348. # There will be a hidden box for replies. And when
  349. # the user presses the 'reply' button on any
  350. # of the current comments, it will fill up the box.
  351. win.commenting["reply"] = {"box":Gtk.HBox(),
  352. "to":""}
  353. vbox.pack_start( win.commenting["reply"]["box"], False, False, False)
  354. ############### SEND BUTTON ###################
  355. def send_do(w):
  356. tb = view.get_buffer()
  357. message = tb.get_text(tb.get_start_iter(), tb.get_end_iter(), True)
  358. tb.set_text("")
  359. send_comment(win, message)
  360. send = Gtk.Button()
  361. send.connect("clicked", send_do)
  362. send.set_relief(Gtk.ReliefStyle.NONE)
  363. sendbox = Gtk.HBox()
  364. sendbox.pack_start(ui.icon(win, "user-available"), False, False, 0)
  365. sendbox.pack_start(Gtk.Label(" Send "), False, False, 0)
  366. pannel.pack_end(send, False, False, False)
  367. send.add(sendbox)
  368. ############## TEXT INPUT ##############
  369. frame = Gtk.Frame()
  370. scrl = Gtk.ScrolledWindow()
  371. view = Gtk.TextView()
  372. view.set_wrap_mode(Gtk.WrapMode.WORD)
  373. scrl.set_size_request(100,100)
  374. scrl.add(view)
  375. frame.add(scrl)
  376. vbox.pack_start(frame, False, False, False)
  377. else:
  378. vbox.pack_start(Gtk.Label("To comment, Make a channel"), False, False, 30)
  379. return vbox
  380. def send_comment(win, message):
  381. # if the user wants to promote FastLBRY
  382. if win.settings["promote_fast_lbry_in_commnets"]:
  383. message = message + BUTTON_GTK_PROMOTE # See the beginning of the file
  384. claim_id = win.resolved["claim_id"]
  385. channel_name = win.channel["name"]
  386. channel_id = win.channel["claim_id"]
  387. sigs = sign(message, channel_name)
  388. if not sigs:
  389. return
  390. params = {
  391. "channel_id": channel_id,
  392. "channel_name": channel_name,
  393. "claim_id": claim_id,
  394. "comment": message,
  395. **sigs
  396. }
  397. if win.commenting["reply"]["to"]:
  398. params["parent_id"] = win.commenting["reply"]["to"]
  399. # Make sure to clean that up
  400. for ch in win.commenting["reply"]["box"].get_children():
  401. ch.destroy()
  402. win.commenting["reply"]["to"] = ""
  403. out = comment_request("comment.Create", params)
  404. i = out["result"]
  405. # RENDERING THE NEWLY DONW COMMENT INTO THE PAGE
  406. # TODO: It duplicates it when the comment is actually loaded
  407. win.commenting[claim_id]["data"]["result"]["items"].append(i)
  408. print(i["comment_id"])
  409. box = win.commenting[claim_id]["box"]
  410. def render(win, box, i):
  411. render_single_comment(win, box, i)
  412. box.show_all()
  413. GLib.idle_add(render, win, box, i)
  414. def sign(data: str = "", channel: str = "", message: str = "Channel to sign data with:", hexdata: str = ""):
  415. """
  416. Sign a string or hexdata and return the signatures
  417. Keyword arguments:
  418. data -- a string to sign
  419. channel -- channel name to sign with (e.g. "@example"). Will prompt for one if not given.
  420. message -- message to give when selecting a channel. Please pass this if not passing channel.
  421. hexdata -- direct hexadecimal data to sign
  422. """
  423. if (not data and not hexdata) or (data and hexdata):
  424. raise ValueError("Must give either data or hexdata")
  425. elif data:
  426. hexdata = data.encode().hex()
  427. if not channel:
  428. channel = select(message)
  429. if not channel.startswith("@"):
  430. channel = "@" + channel
  431. try:
  432. sigs = fetch.lbrynet("channel_sign", {"channel_name":channel, "hexdata":hexdata})
  433. # sigs = check_output([flbry_globals["lbrynet"],
  434. # "channel", "sign",
  435. # "--channel_name=" + channel,
  436. # "--hexdata=" + hexdata])
  437. # sigs = json.loads(sigs)
  438. return sigs
  439. except:
  440. print("Stupid Error")
  441. return