markdown.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  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 os
  30. from flbry.variables import *
  31. from subprocess import *
  32. from flbry import settings
  33. from flbry import plugin
  34. from flbry import url
  35. ################################################################################
  36. # Markdown. Or .md file format is an easy way to give your simple text documents
  37. # a bit of flare. Stuff like links, images and quotes are supported. Also bold
  38. # an italic characters.
  39. def Open(filename):
  40. # This function will parse a Markdown (.md) file into a readable python
  41. # dictionary object. That you can use for various things.
  42. try:
  43. md = open(filename)
  44. md = md.read()
  45. except:
  46. center("Failed to load the article!!!", "bdrd")
  47. return
  48. # After we read the file, we gonna call for all plugins
  49. # that will do something with the file data.
  50. filename, md = plugin.run([filename, md])
  51. # Spliting it for the read.
  52. md = md.split("\n")
  53. # First thing is I was to read the headings and convert it into a tree.
  54. tree = []
  55. indent = 1
  56. c = []
  57. skip = 0
  58. for n,line in enumerate(md):
  59. if skip > n:
  60. continue
  61. ty = "text"
  62. te = line
  63. # Here I want to simply get a type of each line. Later we going to parse
  64. # the links and other things. But first. Let's parse stuff based on
  65. # lines.
  66. if line.startswith("```"):
  67. # THREE ``` aka code block
  68. # This tag will block any other tags
  69. # untill it's untagged
  70. code = ""
  71. for l in md[n+1:]:
  72. if not l.startswith("```"):
  73. code = code + l + "\n"
  74. else:
  75. skip = n + code.count("\n") + 2
  76. break
  77. tree.append(["text_c", code+"\n"])
  78. te = ""
  79. elif line.startswith("#"):
  80. # The titles of the chapter. The Headers are usually written similar
  81. # to how here in python you write comments. It's a # , space, and the
  82. # text.
  83. # The amount of hashes. ## or ### gives different sized text. Officialy
  84. # it should support up to 6 hashes. ######. But why not make it more
  85. # just in case.
  86. ty = line.count("#") # This might give bugs
  87. elif line.startswith(">"):
  88. # The > sign in the Markdown language is used for quatations.
  89. ty = "text_c"
  90. tree.append([ty, te+"\n"])
  91. # Now the stage 0 is over and we parsed the basic things. Now is the hard
  92. # part to parse out all the images and stuff inside them. It's going to be
  93. # done per part. And we are going to use the same technique I used for the
  94. # conversion of the legacy projects. See : studio/story.py ( in VCStudio )
  95. # We are going to itterate over each letter. And decide what to do by that
  96. newtree = []
  97. for block in tree:
  98. if block[0] == "text_c":
  99. newtree.append(block)
  100. continue
  101. part = ""
  102. skip = 0
  103. for n, l in enumerate(block[-1]):
  104. if skip > n:
  105. continue
  106. part = part + l
  107. # Here we are going to do something if a give condition is met.
  108. # Usually I gonna do something if [part] ends with a given markdown
  109. # thing. I don't have a manual of markdown on me. So please make it
  110. # more supported. I guess. I might forget things I rarely use.
  111. # Links are made with [stuff you click on](https://example.com)
  112. # but similar to it. Images are done ![Tooltip](Image.png)
  113. # and even weirder you can put one into the other. Like
  114. # [![Tooltip](Image.png)](https://example.com)
  115. # Which going to give you a clickable image.
  116. # For this version what we are going to do is next.
  117. # If we got [![ then it's a clickable image
  118. # If we got ![ then it's just image
  119. # and if we got [ then it's a link.
  120. if part.endswith("[!["):
  121. # IMAGE LINK
  122. newtree.append([block[0], part[:-3]])
  123. tooltip = ""
  124. imageurl = ""
  125. url = ""
  126. t = False
  127. iu = False
  128. skip = n
  129. for le in block[-1][n:]: # For letters in the rest of text
  130. skip = skip + 1
  131. if le == "]":
  132. t = True
  133. elif le == ")" and t and not iu:
  134. iu = True
  135. elif le == ")" and t and iu:
  136. break
  137. elif not t:
  138. tooltip = tooltip +le
  139. elif t and not iu:
  140. imageurl = imageurl + le
  141. else:
  142. url = url+le
  143. tooltip = tooltip[tooltip.find("[")+1:]
  144. imageurl = imageurl[imageurl.find("(")+1:]
  145. url = url[url.find("(")+1:]
  146. apnd = ["image", "[IMAGE_", imageurl]
  147. newtree.append(apnd)
  148. apnd = ["link", "_LINK]", url]
  149. newtree.append(apnd)
  150. part = ""
  151. elif part.endswith("!["):
  152. # IMAGE
  153. newtree.append([block[0], part[:-2]])
  154. tooltip = ""
  155. url = ""
  156. t = False
  157. skip = n
  158. for le in block[-1][n:]: # For letters in the rest of text
  159. skip = skip + 1
  160. if le == "]":
  161. t = True
  162. elif le == ")" and t:
  163. break
  164. elif not t:
  165. tooltip = tooltip +le
  166. else:
  167. url = url+le
  168. tooltip = tooltip[tooltip.find("[")+1:]
  169. url = url[url.find("(")+1:]
  170. apnd = ["image", "[IMAGE]", url]
  171. newtree.append(apnd)
  172. part = ""
  173. elif part.endswith("[") and not block[-1][n:].startswith('[!['):
  174. # LINK
  175. newtree.append([block[0], part[:-1]])
  176. tooltip = ""
  177. url = ""
  178. t = False
  179. skip = n
  180. for le in block[-1][n:]: # For letters in the rest of text
  181. skip = skip + 1
  182. if le == "]":
  183. t = True
  184. elif le == ")" and t:
  185. break
  186. elif not t:
  187. tooltip = tooltip +le
  188. else:
  189. url = url+le
  190. tooltip = tooltip[tooltip.find("[")+1:]
  191. url = url[url.find("(")+1:]
  192. apnd = ["link", tooltip, url]
  193. newtree.append(apnd)
  194. part = ""
  195. # Now I want to deal with `, *, ** and ***. If you want to help me you
  196. # can implement other types. Such as _, __, ___ and so on. Markdown is
  197. # a very rich language. I'm going to use the cut down version I see other
  198. # people use.
  199. # BTW this is the time. Feb 28. When I switched from Gedit to GNU Emacs.
  200. # Interesting feeling using this programm. I kind a love it even tho
  201. # so many stuff in not intuitive. Like saving is not Ctrl - S but
  202. # Ctrl - X -> Ctrl - S.
  203. # Things like Alt-; to comment multiple lines at ones is HUGE. Also it
  204. # was built by programmers for programmers. So it's a very good tool.
  205. elif part.endswith("**") and not block[-1][n+2:].startswith('*'):
  206. # DOUBLE **
  207. newtree.append([block[0], part[:-2]])
  208. if block[0] == "text":
  209. block[0] = "text_b"
  210. else:
  211. block[0] = "text"
  212. part = ""
  213. elif part.endswith("*") and not block[-1][n+1:].startswith('*'):
  214. # SINGLE *
  215. newtree.append([block[0], part[:-1]])
  216. if block[0] == "text":
  217. block[0] = "text_i"
  218. else:
  219. block[0] = "text"
  220. part = ""
  221. elif part.endswith("`"):
  222. # SINGLE `
  223. newtree.append([block[0], part[:-1]])
  224. if block[0] == "text":
  225. block[0] = "text_c"
  226. else:
  227. block[0] = "text"
  228. part = ""
  229. newtree.append([block[0], part])
  230. w,h = tsize()
  231. newtree.append(["text", "\n"*h])
  232. tree = newtree
  233. return(tree)
  234. def search_convert(s):
  235. # This function convers a chapter name into a link
  236. # such links are use in notabug.org to link to chapters
  237. # for example example.com/file.md#chapter-name
  238. # With this url it will load the example.com/file.md and
  239. # then skip to the "Chapter Name" chapter.
  240. # This function transforms "Chapter Name" into "chapter-name"
  241. l = " ./\|[]{}()?!@#$%^&*`~:;'\"=,<>"
  242. s = s.lower().replace(" ","-")
  243. r = ""
  244. for i in s:
  245. if i not in l:
  246. r = r + i
  247. return r
  248. def draw(filename, title, convert=True):
  249. # Write the file to a temporary file so plugins can modify it
  250. with open(filename) as f:
  251. md = f.read()
  252. filename, md = plugin.run([filename, md])
  253. filename = "/tmp/fastlbrymarkdownreader.md"
  254. with open(filename, "w") as f:
  255. f.write(md)
  256. if settings.get("markdown_reader"):
  257. os.system(settings.get("markdown_reader") + " " + filename)
  258. else:
  259. draw_default(filename, title, convert)
  260. def draw_default(filename, title, convert=True):
  261. ###########
  262. # THE FOLLOWING CODE IS VERY DIRTY. I WAS RUNNING OUT OF TIME WHILE IMPLEMENTING
  263. # IT. PLEASE SEE WHAT CAN BE DONE ABOUT IT. I THINK SOMEBODY NEEDS TO HACK
  264. # COMMENTS TO IT. SINCE IT COULD BE CONFUSING AS HELL...
  265. ##########
  266. # Getting size of the terminal
  267. try:
  268. import os
  269. w, l = os.get_terminal_size()
  270. if not w % 2: # to solve the tearing when it's a weird amount
  271. w = w - 1
  272. l = l - 5
  273. w = w - 8
  274. except:
  275. w = 89 # The width of the frame
  276. l = 20 # Total lines amount possible.
  277. # First we want to parse the article
  278. if convert:
  279. md = Open(filename)
  280. else:
  281. mdf = open(filename)
  282. mdf = mdf.read()
  283. mdf = mdf.split("\n")
  284. md = []
  285. for i in mdf:
  286. md.append(["text", i+"\n"])
  287. md.append(["text", "\n"*l])
  288. # Now we want to print what we have
  289. # Top banner thingy. Purple with the name of the article.
  290. # Title line
  291. center(title)
  292. pline = ""
  293. lenis = 0
  294. linen = 0
  295. colors = {
  296. "text":clr["norm"]+clr["tbwh"]+clr["bdbu"],
  297. "text_b":clr["norm"]+clr["bold"]+clr["tbwh"]+clr["bdbu"],
  298. "text_i":clr["norm"]+clr["ital"]+clr["tbwh"]+clr["bdbu"],
  299. "text_c":clr["norm"]+clr["tbwh"]+clr["bdgr"],
  300. "link":clr["norm"]+clr["tbwh"]+clr["bdma"],
  301. "image":clr["norm"]+clr["tbwh"]+clr["bdcy"]
  302. }
  303. # Let's store all the links that the user might want to use
  304. links = []
  305. linkn = 0
  306. linkw = False
  307. for part in md:
  308. if part[0] in [1,2,3,4,5,6,7]:
  309. center(part[1].replace("\n", "").replace("#", ""), "bdcy")
  310. linen = linen + 1
  311. elif part[1].startswith("---") or part[1].startswith("___"):
  312. center("═"*(w-12), "bdbu")
  313. linen = linen + 1
  314. elif part[0] in ["text", "text_b", "text_c", "text_i", "link", "image"]:
  315. if linkw:
  316. pline = pline + clr["bbma"] + wdth(linkn, 4) + " "
  317. linkn = linkn + 1
  318. lenis = lenis + 5
  319. linkw = False
  320. pline = pline + colors[part[0]]
  321. for num, letter in enumerate(part[1]):
  322. br = False
  323. rest = part[1][num:] # all the rest of the part
  324. if letter not in [" ", "\n"]:
  325. pline = pline + letter
  326. lenis = lenis + 1
  327. if part[0] in ["link", "image"] and part[2] not in links:
  328. links.append(part[2])
  329. linkw = True
  330. elif letter == " ":
  331. if not lenis > w - 20 - len(rest[:rest.replace(" ","_",1).find(" ")]):
  332. pline = pline + " "
  333. lenis = lenis + 1
  334. else:
  335. br = True
  336. elif letter == "\n":
  337. br = True
  338. if br:
  339. print(" "+clr["bdbu"]+" "+pline+clr["bdbu"]+wdth("", w-lenis-6)+clr["norm"])
  340. pline = colors[part[0]]
  341. lenis = 0
  342. linen = linen + 1
  343. # If reached the line number
  344. if linen >= l:
  345. center("---type 'more' to continue reading it--- ")
  346. complete(["more"])
  347. while True:
  348. plugin.run(execute=False)
  349. c = input(typing_dots())
  350. if not c:
  351. return
  352. if c != "more":
  353. try:
  354. c = int(c)
  355. except:
  356. pass
  357. if type(c) == type(10):
  358. # Pass the link to the link parser
  359. link_open(links[c], filename)
  360. else:
  361. md, links, filename, title = plugin.run([md, links, filename, title], command=c)
  362. elif c == "more":
  363. links = []
  364. linkn = 0
  365. linkw = False
  366. linen = 0
  367. center(title)
  368. break
  369. def link_open(link, start_from=""):
  370. # This function will decide what to do with links.
  371. ####### TRY TO LOAD A LOCAL FILE FIRST #######
  372. local_link = link
  373. if not link.startswith("/"):
  374. start_from = start_from.replace(os.getcwd(), "")
  375. if not link.startswith("../"):
  376. local_link = os.getcwd()+"/"+start_from[:start_from.rfind("/")+1]+link
  377. else:
  378. local_link = os.getcwd()+"/"+start_from
  379. for i in range(link.count("../")+1):
  380. local_link = local_link[:local_link.rfind("/")-1]
  381. local_link = local_link + '/' + link.replace("../", "")
  382. if os.path.exists(local_link):
  383. try:
  384. # Testing if it's a text
  385. open(local_link)
  386. if local_link.endswith(".md"):
  387. draw(local_link, local_link)
  388. else:
  389. draw(local_link, local_link , False)
  390. except Exception as e:
  391. #print(e)
  392. Popen(['xdg-open',
  393. local_link],
  394. stdout=DEVNULL,
  395. stderr=STDOUT)
  396. return
  397. ########## TRY TO LOAD AN LBRY LINK ##############
  398. # TODO : This part confuses me. Something is wrong. Some good
  399. # links just break the url.get() function and I don't
  400. # understand what the hell is going on.
  401. try:
  402. if url.get(link, False): # If it fails, it will return the error message
  403. print(" "+link)
  404. except:
  405. print(" "+link)