url.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. # This file will fetch an LBRY URL directly and print out various
  30. # options that the user may do with the publication.
  31. from subprocess import *
  32. import json
  33. import os
  34. from flbry.variables import *
  35. from flbry import markdown
  36. from flbry import channel
  37. from flbry import search
  38. from flbry import comments
  39. import urllib.request
  40. from flbry import following
  41. from flbry import settings
  42. from flbry import wallet
  43. from flbry import plugin
  44. from flbry import channel
  45. import urllib.parse
  46. def print_url_info(url, out):
  47. """Prints some information about the URL"""
  48. ##### NAME URL INFORMATION #####
  49. center("Publication Information")
  50. d = {"categories":["lbry url", "title"],
  51. "size":[1,1],
  52. "data":[[url]]}
  53. try:
  54. # This prints out the title
  55. d["data"][0].append(out["value"]["title"])
  56. except:
  57. d["data"][0] = [url]
  58. d["data"][0].append("[no title]")
  59. table(d, False)
  60. #### LICENSE ####
  61. try:
  62. d = {"categories":["License"],
  63. "size":[1],
  64. "data":[[out["value"]["license"]]]}
  65. except:
  66. d = {"categories":["License"],
  67. "size":[1],
  68. "data":[["[failed to load license]"]]}
  69. table(d, False)
  70. #### TAGS #####
  71. d = {"categories":[],
  72. "size":[],
  73. "data":[[]]}
  74. try:
  75. for tag in out["value"]["tags"]:
  76. d["categories"].append(" ")
  77. d["size"].append(1)
  78. d["data"][0].append(tag)
  79. except:
  80. d = {"categories":[" "],
  81. "size":[1],
  82. "data":[["[no tags found]"]]}
  83. table(d, False)
  84. #### FILE INFO #####
  85. d = {"categories":["Value Type", "File Type", "File Size", "Duration"],
  86. "size":[1,1,1, 1],
  87. "data":[[]]}
  88. try:
  89. d["data"][0].append(what[out["value_type"]])
  90. except:
  91. d["data"][0].append("[no value type]")
  92. try:
  93. d["data"][0].append(out["value"]["source"]["media_type"])
  94. except:
  95. d["data"][0].append("[no file type]")
  96. try:
  97. d["data"][0].append(csize(out["value"]["source"]["size"]))
  98. except:
  99. d["data"][0].append("[no file size]")
  100. try:
  101. d["data"][0].append(timestring(float(out["value"]["video"]["duration"])))
  102. except:
  103. d["data"][0].append("[no duration]")
  104. table(d, False)
  105. ##### CHANNEL INFORMATION ####
  106. center("Channel Information")
  107. d = {"categories":["lbry url", "title"],
  108. "size":[1,1],
  109. "data":[[]]}
  110. try:
  111. # This prints out the title
  112. d["data"][0].append(out["signing_channel"]["name"])
  113. title = "[no title]"
  114. try:
  115. title = out["signing_channel"]["value"]["title"]
  116. except:
  117. pass
  118. d["data"][0].append(title)
  119. except:
  120. d["data"][0] = []
  121. d["data"][0].append("[no url]")
  122. d["data"][0].append("[anonymous publisher]")
  123. table(d, False)
  124. #### LBC INFORMATION ####
  125. center("LBRY Coin ( LBC ) Information")
  126. d = {"categories":["combined", "at upload", "support"],
  127. "size":[1,1,1],
  128. "data":[[]]}
  129. try:
  130. fullamount = float(out["amount"]) + float(out["meta"]["support_amount"])
  131. # This prints out the title
  132. d["data"][0].append(fullamount)
  133. d["data"][0].append(out["amount"])
  134. d["data"][0].append(out["meta"]["support_amount"])
  135. except:
  136. d["data"][0] = []
  137. d["data"][0].append("[no data]")
  138. d["data"][0].append("[no data]")
  139. d["data"][0].append("[no data]")
  140. table(d, False)
  141. #### PRICE ####
  142. try:
  143. # Print the prince of this publication in LBC
  144. center("PRICE: "+out["value"]["fee"]["amount"]+" "+out["value"]["fee"]["currency"], "bdrd", blink=True)
  145. except:
  146. pass
  147. # Some things are too big to output like this in the terminal
  148. # so for them I want the user to type a command.
  149. center("--- for publication commands list type 'help' --- ")
  150. def get(url="", do_search=True):
  151. """Allows user to interact with the given URL"""
  152. # The user might type the word url and nothing else.
  153. if not url:
  154. url = input(typing_dots("LBRY url", give_space=True, to_add_dots=True))
  155. # Decode the URL to turn percent encoding into normal characters
  156. # Example: "%C3%A9" turns into "é"
  157. url = urllib.parse.unquote(url)
  158. ##### Converting an HTTPS domain ( of any website ) into lbry url ###
  159. # Any variation of this:
  160. # https://odysee.com/@blenderdumbass:f/hacking-fastlbry-live-with-you:6
  161. # customlbry.com/@blenderdumbass:f/hacking-fastlbry-live-with-you:6
  162. # Should become this:
  163. # lbry://@blenderdumbass:f/hacking-fastlbry-live-with-you:6
  164. if "/" in url and not url.startswith("@") and not url.startswith("lbry://"):
  165. if "@" in url:
  166. url = url[url.find("@"):]
  167. else:
  168. url = url[text.rfind("/")-1:]
  169. # Some web interfaces pass data through URLs using a '?'.
  170. # This is not valid for a LBRY URL, so we remove everything
  171. # after it to avoid errors.
  172. url = url.split("?")[0]
  173. url = "lbry://"+url
  174. # If a url looks like it might be a claim id, try to get the claim from it
  175. if len(url) == 40 and not url.startswith("lbry://"):
  176. x = check_output([lbrynet_binary["b"], "claim", "search", "--claim_id="+url])
  177. try:
  178. x = json.loads(x)
  179. except:
  180. center("Connect to LBRY first.", "bdrd")
  181. return
  182. if len(x["items"]) == 1:
  183. # If "items" has something in it we know it was a claim id
  184. out = x["items"][0]
  185. url = out["canonical_url"]
  186. else:
  187. # Let's fetch the url from our beloved SDK.
  188. out = check_output([lbrynet_binary["b"],
  189. "resolve", url])
  190. # Now we want to parse the json
  191. try:
  192. out = json.loads(out)
  193. except:
  194. center("Connect to LBRY first.", "bdrd")
  195. return
  196. out = out[url]
  197. # In case there are plugins that want to modify resolved data.
  198. out = plugin.run(out)
  199. ### REPOST ####
  200. # Sometimes a user wants to select a repost. This will not
  201. # load anything of a value. A repost is an empty blob that
  202. # links to another blob. So I want to automatically load
  203. # the actuall publication it self here.
  204. if "value_type" in out and out["value_type"] == "repost":
  205. get(out["reposted_claim"]["canonical_url"])
  206. return
  207. #### FORCE SEARCH ###
  208. # Sometimes user might type something that is not a url
  209. # in this case ["value_type"] will not be loaded. And in
  210. # this case we can load search instead.
  211. if "value_type" not in out and do_search:
  212. search.simple(url)
  213. return out
  214. elif "value_type" not in out:
  215. return out
  216. # Now that we know that don't search for it. We can make
  217. # one thing less broken. Sometimes a user might type a
  218. # urls that's going to be resolved but that doesn't have
  219. # the lbry:// in the beginning of it. Like typing
  220. # @blenderdumbass instead of lbry://@blenderdumbass
  221. # I want to add the lbry:// to it anyway. So none of the
  222. # stuff later will break.
  223. if not url.startswith("lbry://"):
  224. url = "lbry://" + url
  225. print_url_info(url, out)
  226. # So we are going to start a new while loop here. IK crazy.
  227. # this one will handle all the commands associated with the
  228. # currently selected publication.
  229. # Completer thingy
  230. url_commands = [
  231. "help",
  232. "link",
  233. "id",
  234. "web",
  235. "description",
  236. "read",
  237. "channel",
  238. "comments",
  239. "reply",
  240. "open",
  241. "play",
  242. "music",
  243. "save",
  244. "rss",
  245. "thumbnail",
  246. "follow",
  247. "unfollow",
  248. "boost",
  249. "tip",
  250. "repost"
  251. ]
  252. complete(url_commands)
  253. settings_cache = settings.get_all_settings()
  254. while True:
  255. plugin.run(execute=False)
  256. c = input(typing_dots())
  257. # Some strings are only one line, so it's a waste to reprint the info.
  258. reprint = True
  259. # Some commands were changing url, which we don't want, so now
  260. # it uses a temporary variable instead.
  261. tmpurl = ""
  262. if not c:
  263. break
  264. elif c == "help":
  265. markdown.draw("help/url.md", "Publication Help")
  266. elif c == "web":
  267. print_web_instance(url)
  268. elif c == "link":
  269. center(url)
  270. reprint = False
  271. elif c == "id":
  272. center(out["claim_id"])
  273. reprint = False
  274. elif c.startswith("open"):
  275. # If open has an argument (like `open mpv`) it opens it in that
  276. # Next it trys to open it with the default opener
  277. # If neither of those find an opener, it prompts the user.
  278. if len(c) > 5:
  279. p = c[5:]
  280. elif settings_cache["default_opener"]:
  281. p = settings_cache["default_opener"]
  282. else:
  283. p = input(typing_dots("Open in"))
  284. p = p.split()
  285. Popen([*p,
  286. url.replace("lbry://", "https://spee.ch/").replace("#", ":").replace("(", "%28").replace(")", "%29")],
  287. stdout=DEVNULL,
  288. stderr=STDOUT)
  289. elif c == "description":
  290. # Here I want to print out the description of the publication.
  291. # but since, they are most likely in the markdown format I
  292. # need to implement a simple markdown parser. Oh wait.... I
  293. # have one. For the article read function. How about using it
  294. # here?
  295. # First we need to save the description into a file. Let's use
  296. # /tmp/ since there files are automatically cleaned up by the
  297. # system.
  298. try:
  299. savedes = open("/tmp/fastlbrylastdescription.md", "w")
  300. savedes.write(out["value"]["description"])
  301. savedes.close()
  302. except:
  303. savedes = open("/tmp/fastlbrylastdescription.md", "w")
  304. savedes.write("This file has no description.")
  305. savedes.close()
  306. # Now let's just simply load the markdown on this file.
  307. markdown.draw("/tmp/fastlbrylastdescription.md", "Description")
  308. elif c.startswith("play"):
  309. # Then we want to tell the SDK to start downloading.
  310. playout = check_output([lbrynet_binary["b"],
  311. "get", url])
  312. # Parsing the JSON
  313. playout = json.loads(playout)
  314. # Same thing as in open
  315. if len(c) > 5:
  316. p = c[5:]
  317. elif settings_cache["player"]:
  318. p = settings_cache["player"]
  319. else:
  320. p = input(typing_dots("Play in"))
  321. p = p.split()
  322. # Then we want to launch the player
  323. Popen([*p,
  324. playout['download_path']],
  325. stdout=DEVNULL,
  326. stderr=STDOUT)
  327. elif c.startswith("music"):
  328. # Then we want to tell the SDK to start downloading.
  329. playout = check_output([lbrynet_binary["b"],
  330. "get", url])
  331. # Parsing the Json
  332. playout = json.loads(playout)
  333. # And again for music player
  334. if len(c) > 6:
  335. p = c[6:]
  336. elif settings_cache["music_player"]:
  337. p = settings_cache["music_player"]
  338. else:
  339. p = input(typing_dots("Play in"))
  340. p = p.split()
  341. # Then we want to launch the player
  342. Popen([*p,
  343. playout['download_path']],
  344. stdout=DEVNULL,
  345. stderr=STDOUT)
  346. elif c == "save":
  347. # Then we want to tell the SDK to start downloading.
  348. playout = check_output([lbrynet_binary["b"],
  349. "get", url])
  350. # Parsing the Json
  351. playout = json.loads(playout)
  352. center("Saved to "+playout['download_path'])
  353. reprint = False
  354. elif c == "read":
  355. # Then we want to tell the SDK to start downloading.
  356. playout = check_output([lbrynet_binary["b"],
  357. "get", url])
  358. # Parsing the Json
  359. playout = json.loads(playout)
  360. # Present the article to the user.
  361. markdown.draw(playout['download_path'], out["value"]["title"])
  362. elif c == "channel":
  363. # This a weird one. If the publication is a channel we
  364. # want it to list the publications by that channel.
  365. # If a publication is a publication. We want it to list
  366. # publications by the channel that made the publication.
  367. if out["value_type"] == "channel":
  368. channel.simple(url)
  369. else:
  370. try:
  371. channel.simple(out["signing_channel"]["canonical_url"].replace("lbry://",""))
  372. except:
  373. center("Publication is anonymous", "bdrd")
  374. elif c == "comments":
  375. comments.list(out["claim_id"], url)
  376. elif c.startswith("reply"):
  377. c = c + ' '
  378. comments.post(out["claim_id"], c[c.find(" "):])
  379. elif c == "rss":
  380. if out["value_type"] == "channel":
  381. tmpurl = out["short_url"].replace("#", ":")
  382. if tmpurl.startswith("lbry://"):
  383. tmpurl = url.split("lbry://", 1)[1]
  384. center("https://odysee.com/$/rss/"+tmpurl)
  385. else:
  386. try:
  387. tmpurl = out["signing_channel"]["short_url"].replace("#", ":")
  388. tmpurl = tmpurl.split("lbry://", 1)[1]
  389. center("https://odysee.com/$/rss/"+tmpurl)
  390. except:
  391. center("Publication is anonymous!", "bdrd")
  392. reprint = False
  393. elif c == "thumbnail":
  394. try:
  395. thumb_url = out["value"]["thumbnail"]["url"]
  396. urllib.request.urlretrieve(thumb_url, "/tmp/fastlbrythumbnail")
  397. Popen(["xdg-open",
  398. "/tmp/fastlbrythumbnail"],
  399. stdout=DEVNULL,
  400. stderr=STDOUT)
  401. except:
  402. center("Publication does not have a thumbnail", "bdrd")
  403. elif c == "follow":
  404. if out["value_type"] == "channel":
  405. try:
  406. name = out["value"]["title"]
  407. except:
  408. name = out["normalized_name"]
  409. tmpurl = out["permanent_url"]
  410. following.follow_channel(tmpurl, name)
  411. else:
  412. try:
  413. try:
  414. name = out["signing_channel"]["value"]["title"]
  415. except:
  416. name = out["signing_channel"]["normalized_name"]
  417. tmpurl = out["signing_channel"]["permanent_url"]
  418. following.follow_channel(tmpurl, name)
  419. except:
  420. center("Publication is anonymous.", "bdrd")
  421. elif c == "unfollow":
  422. if out["value_type"] == "channel":
  423. try:
  424. name = out["value"]["title"]
  425. except:
  426. name = out["normalized_name"]
  427. tmpurl = out["permanent_url"]
  428. following.unfollow_channel(tmpurl, name)
  429. else:
  430. try:
  431. try:
  432. name = out["signing_channel"]["value"]["title"]
  433. except:
  434. name = out["signing_channel"]["normalized_name"]
  435. tmpurl = out["signing_channel"]["permanent_url"]
  436. following.unfollow_channel(tmpurl, name)
  437. except:
  438. center("Publication is anonymous.", "bdrd")
  439. elif c.startswith("boost"):
  440. if " " in c:
  441. wallet.support(out["claim_id"], amount=c[c.find(" ")+1:])
  442. else:
  443. wallet.support(out["claim_id"])
  444. elif c.startswith("tip"):
  445. if " " in c:
  446. wallet.support(out["claim_id"], amount=c[c.find(" ")+1:], tip=True)
  447. else:
  448. wallet.support(out["claim_id"], tip=True)
  449. elif c.startswith("repost"):
  450. name = input(typing_dots("Name (enter for name of publication)", give_space=True))
  451. if not name:
  452. name = out["normalized_name"]
  453. a = c.split()
  454. try:
  455. bid = a[1]
  456. except:
  457. bid = input(typing_dots("Bid"))
  458. claim_id = out["claim_id"]
  459. ch, chid = channel.select("Channel to repost to:", True)
  460. repost_out = check_output([lbrynet_binary["b"], "stream", "repost", "--name="+name, "--bid="+bid, "--claim_id="+claim_id, "--channel_id="+chid])
  461. repost_out = json.loads(repost_out)
  462. if "message" in repost_out:
  463. center("Error reposting: "+repost_out["message"], "bdrd")
  464. else:
  465. center("Successfully reposted to "+ch, "bdgr")
  466. elif c:
  467. out = plugin.run(out, command=c)
  468. complete(url_commands)
  469. # Print the publication information again
  470. if reprint:
  471. print()
  472. print_url_info(url, out)