comments.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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, "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. reply_frame = Gtk.Frame(label=" Replied to: ")
  152. reply_frame.set_shadow_type(Gtk.ShadowType.ETCHED_OUT)
  153. reply_box = Gtk.VBox()
  154. reply_frame.add(reply_box)
  155. if "channel_url" in b:
  156. chbox = Gtk.HBox()
  157. channel_button = ui.load(win, resolve_channel, render_channel, win, b["channel_url"])
  158. chbox.pack_start(channel_button, False, False, 0)
  159. reply_box.pack_start(chbox, True, False, 4)
  160. comment_label = Gtk.Label(b["comment"].replace(BUTTON_GTK_PROMOTE, ""))
  161. comment_label.set_line_wrap_mode( Gtk.WrapMode.WORD )
  162. comment_label.set_line_wrap(True)
  163. comment_label.set_max_width_chars(20)
  164. reply_box.pack_start(comment_label, True, True, 10)
  165. box.pack_end(reply_frame, True, True, 10)
  166. break
  167. # each channel will need to be resolved on fly
  168. if "channel_url" in i:
  169. chbox = Gtk.HBox()
  170. channel_button = ui.load(win, resolve_channel, render_channel, win, i["channel_url"])
  171. chbox.pack_start(channel_button, False, False, 0)
  172. if "support_amount" in i and i["support_amount"]:
  173. chbox.pack_start(ui.icon(win, "rating"), False, False, 0)
  174. chbox.pack_start(Gtk.Label(" "+str(i["support_amount"])+" LBC"), False, False, 0)
  175. if supporter:
  176. chbox.pack_start(ui.icon(win, "rating"), False, False, 0)
  177. chbox.pack_start(Gtk.Label(" Promoter of FastLBRY "), False, False, 0)
  178. box.pack_end(chbox, False, False, 4)
  179. box.pack_end(Gtk.HSeparator(), False, False, 0)
  180. def render_comments(out, megabox=False):
  181. win, out, megabox = out
  182. if not megabox:
  183. megabox = Gtk.VBox()
  184. megabox.show_all()
  185. # renders a list of comments
  186. box = Gtk.VBox()
  187. box.set_hexpand(False)
  188. # I want to setup a little daemon to update the comments
  189. # automatically
  190. claim_id = win.resolved["claim_id"]
  191. try:
  192. the_title = win.resolved["value"]["title"]
  193. except:
  194. the_title = win.resolved["name"]
  195. if out["result"]["page"] == 1: # If it's the first page
  196. win.commenting[claim_id]["box"] = box
  197. win.commenting[claim_id]["data"] = out
  198. win.check_comment_daemon_keep_alive = True
  199. load_thread = threading.Thread(target=comment_daemon, args=[win, claim_id, the_title])
  200. load_thread.setDaemon(True)
  201. load_thread.start()
  202. def kill_daemon(w):
  203. win.check_comment_daemon_keep_alive = False
  204. box.connect("destroy", kill_daemon)
  205. try:
  206. items = out["result"]["items"]
  207. for i in items:
  208. if i not in win.commenting[claim_id]["data"]["result"]["items"]:
  209. win.commenting[claim_id]["data"]["result"]["items"].append(i)
  210. except:
  211. items = []
  212. for i in reversed(items):
  213. #print("\n\n:::::::::::::::::\n\n", i)
  214. render_single_comment(win, box, i)
  215. box.show_all()
  216. # The top level box containing about 50 comments
  217. megabox.pack_start(box, False, False, 0)
  218. lastthing(win, out, megabox)
  219. megabox.show_all()
  220. return megabox
  221. def comment_daemon(win, claim_id, the_title=""):
  222. # This function will be a daemon for the current comment system to
  223. # load all new comments that happen while the user it on the page.
  224. while win.commenting[claim_id]["keep_alive"]:
  225. time.sleep(2) # Update every two seconds ( I don't want it to crash )
  226. n = win.commenting[claim_id]["data"]
  227. claim_id = n["result"]["items"][0]["claim_id"]
  228. win, out, megabox = list_comments(win, claim_id)
  229. ##### LOGIC OF ADDING MISSING COMMENTS INTO THE BOX ####
  230. for i in reversed(out["result"]["items"]):
  231. if i not in n["result"]["items"]:
  232. ids = []
  233. for b in n["result"]["items"]:
  234. ids.append(b["comment_id"])
  235. ######## FOUND A NEW COMMENT #######
  236. if i["comment_id"] not in ids:
  237. try:
  238. channel = i["channel_name"]
  239. except:
  240. channel = "[anonymous]"
  241. text = i["comment"]
  242. print("COMMENT FROM ", channel, "IS", text)
  243. force = win.resolved["claim_id"] != claim_id
  244. ui.notify(win, channel+" Commented on "+the_title, text, force=force)
  245. win.commenting[claim_id]["data"]["result"]["items"].append(i)
  246. print(i["comment_id"])
  247. box = win.commenting[claim_id]["box"]
  248. def render(win, box, i):
  249. render_single_comment(win, box, i)
  250. box.show_all()
  251. GLib.idle_add(render, win, box, i)
  252. def br(w):
  253. if not win.commenting[claim_id]["listen"]:
  254. win.commenting[claim_id]["keep_alive"] = False
  255. win.commenting[claim_id]["box"].connect("destroy", br)
  256. def lastthing(win, out, megabox):
  257. # This will hack itself to load more comments when you reached the end.
  258. spinner_more = ui.icon(win, "loading", "gif")
  259. megabox.pack_start(spinner_more, False, False, 0)
  260. def draw_event(w, e):
  261. print("EVENT")
  262. w.destroy()
  263. try:
  264. claim_id = out["result"]["items"][0]["claim_id"]
  265. page = out["result"]["page"] + 1
  266. ui.load(win, list_comments, render_comments, win, claim_id, page, megabox, wait=False )
  267. except Exception as e:
  268. print("ERROR IS:", e)
  269. spinner_more.connect("draw", draw_event)
  270. def get_reactions(out):
  271. # Adds reactions list to the out
  272. try:
  273. claim_id = out["result"]["items"][0]["claim_id"]
  274. ids = ""
  275. for i in out["result"]["items"]:
  276. ids = ids + i["comment_id"] + ","
  277. ids = ids[:-1]
  278. except:
  279. return out
  280. rec = {
  281. "claim_id":claim_id,
  282. "comment_ids":ids}
  283. rec = comment_request("reaction.List", rec, addition="?m=reaction.List")
  284. for i in out["result"]["items"]:
  285. try:
  286. i["reactions"] = rec["result"]["others_reactions"][i["comment_id"]]
  287. except:
  288. pass
  289. return out
  290. def comment_request(method: str, params: dict, addition=""):
  291. """
  292. Sends a request to the comment API
  293. """
  294. data = {
  295. "method": method,
  296. "id": 1,
  297. "jsonrpc":"2.0",
  298. "params": params
  299. }
  300. data = json.dumps(data).encode()
  301. headers = {
  302. "Content-Type": "application/json"
  303. }
  304. try:
  305. req = urllib.request.Request(comments_api, data, headers)
  306. res = urllib.request.urlopen(req)
  307. out = res.read().decode()
  308. return json.loads(out)
  309. except Exception as e:
  310. print("COMMENT ERROR:", e)
  311. return
  312. def comment_input(win):
  313. claim_id = win.resolved["claim_id"]
  314. # This is the input for new comments.
  315. vbox = Gtk.VBox()
  316. pannel = Gtk.HBox()
  317. vbox.pack_start(pannel, False, False, False)
  318. ################## LISTEN BUTTON ###############
  319. try:
  320. give_listen = win.commenting[claim_id]["listen"]
  321. except:
  322. give_listen = False
  323. win.commenting[claim_id] = {"box": False,
  324. "data":{},
  325. "listen":give_listen,
  326. "keep_alive":True}
  327. if win.settings["notifications"]:
  328. lbox = Gtk.HBox()
  329. lbox.pack_start(Gtk.Label(" Listen "), False, False, False)
  330. listen = Gtk.Switch()
  331. def lclick(w, u):
  332. win.commenting[claim_id]["listen"] = listen.get_active()
  333. try:
  334. listen.set_active(win.commenting[claim_id]["listen"])
  335. except Exception as e:
  336. print("Switch is:", e)
  337. listen.connect("notify::active", lclick)
  338. lbox.pack_start(listen, False, False, False)
  339. pannel.pack_start(lbox, False, False, False)
  340. if win.channel:
  341. ############# BOX FOR REPLIES ##############
  342. # There will be a hidden box for replies. And when
  343. # the user presses the 'reply' button on any
  344. # of the current comments, it will fill up the box.
  345. win.commenting["reply"] = {"box":Gtk.HBox(),
  346. "to":""}
  347. vbox.pack_start( win.commenting["reply"]["box"], False, False, False)
  348. ############### SEND BUTTON ###################
  349. def send_do(w):
  350. tb = view.get_buffer()
  351. message = tb.get_text(tb.get_start_iter(), tb.get_end_iter(), True)
  352. tb.set_text("")
  353. send_comment(win, message)
  354. send = Gtk.Button()
  355. send.connect("clicked", send_do)
  356. send.set_relief(Gtk.ReliefStyle.NONE)
  357. sendbox = Gtk.HBox()
  358. sendbox.pack_start(ui.icon(win, "message-new"), False, False, 0)
  359. sendbox.pack_start(Gtk.Label(" Send "), False, False, 0)
  360. pannel.pack_end(send, False, False, False)
  361. send.add(sendbox)
  362. ############## TEXT INPUT ##############
  363. frame = Gtk.Frame()
  364. scrl = Gtk.ScrolledWindow()
  365. view = Gtk.TextView()
  366. view.set_wrap_mode(Gtk.WrapMode.WORD)
  367. scrl.set_size_request(100,100)
  368. scrl.add(view)
  369. frame.add(scrl)
  370. vbox.pack_start(frame, False, False, False)
  371. else:
  372. vbox.pack_start(Gtk.Label("To comment, Make a channel"), False, False, 30)
  373. return vbox
  374. def send_comment(win, message):
  375. # if the user wants to promote FastLBRY
  376. if win.settings["promote_fast_lbry_in_commnets"]:
  377. message = message + BUTTON_GTK_PROMOTE # See the beginning of the file
  378. claim_id = win.resolved["claim_id"]
  379. channel_name = win.channel["name"]
  380. channel_id = win.channel["claim_id"]
  381. sigs = sign(message, channel_name)
  382. if not sigs:
  383. return
  384. params = {
  385. "channel_id": channel_id,
  386. "channel_name": channel_name,
  387. "claim_id": claim_id,
  388. "comment": message,
  389. **sigs
  390. }
  391. if win.commenting["reply"]["to"]:
  392. params["parent_id"] = win.commenting["reply"]["to"]
  393. # Make sure to clean that up
  394. for ch in win.commenting["reply"]["box"].get_children():
  395. ch.destroy()
  396. win.commenting["reply"]["to"] = ""
  397. out = comment_request("comment.Create", params)
  398. i = out["result"]
  399. # RENDERING THE NEWLY DONW COMMENT INTO THE PAGE
  400. # TODO: It duplicates it when the comment is actually loaded
  401. win.commenting[claim_id]["data"]["result"]["items"].append(i)
  402. print(i["comment_id"])
  403. box = win.commenting[claim_id]["box"]
  404. def render(win, box, i):
  405. render_single_comment(win, box, i)
  406. box.show_all()
  407. GLib.idle_add(render, win, box, i)
  408. def sign(data: str = "", channel: str = "", message: str = "Channel to sign data with:", hexdata: str = ""):
  409. """
  410. Sign a string or hexdata and return the signatures
  411. Keyword arguments:
  412. data -- a string to sign
  413. channel -- channel name to sign with (e.g. "@example"). Will prompt for one if not given.
  414. message -- message to give when selecting a channel. Please pass this if not passing channel.
  415. hexdata -- direct hexadecimal data to sign
  416. """
  417. if (not data and not hexdata) or (data and hexdata):
  418. raise ValueError("Must give either data or hexdata")
  419. elif data:
  420. hexdata = data.encode().hex()
  421. if not channel:
  422. channel = select(message)
  423. if not channel.startswith("@"):
  424. channel = "@" + channel
  425. try:
  426. sigs = fetch.lbrynet("channel_sign", {"channel_name":channel, "hexdata":hexdata})
  427. # sigs = check_output([flbry_globals["lbrynet"],
  428. # "channel", "sign",
  429. # "--channel_name=" + channel,
  430. # "--hexdata=" + hexdata])
  431. # sigs = json.loads(sigs)
  432. return sigs
  433. except:
  434. print("Stupid Error")
  435. return