offpunk.py 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940
  1. #!/usr/bin/env python3
  2. # Offpunk Offline Gemini client
  3. """
  4. Offline-First Gemini/Web/Gopher/RSS reader and browser
  5. """
  6. __version__ = "2.2"
  7. ## Initial imports and conditional imports {{{
  8. import argparse
  9. import cmd
  10. import datetime
  11. import io
  12. import os
  13. import os.path
  14. import filecmp
  15. import random
  16. import shlex
  17. import shutil
  18. import socket
  19. import sys
  20. import time
  21. import urllib.parse
  22. import subprocess
  23. import netcache
  24. import opnk
  25. import ansicat
  26. import offthemes
  27. from offutils import run,term_width,is_local,mode_url,unmode_url, looks_like_url
  28. from offutils import xdg
  29. import offblocklist
  30. try:
  31. import setproctitle
  32. setproctitle.setproctitle("offpunk")
  33. _HAS_SETPROCTITLE = True
  34. except ModuleNotFoundError:
  35. _HAS_SETPROCTITLE = False
  36. #This method copy a string to the system clipboard
  37. def clipboard_copy(to_copy):
  38. copied = False
  39. if shutil.which('xsel'):
  40. run("xsel -b -i", input=to_copy, direct_output=True)
  41. copied = True
  42. if shutil.which('xclip'):
  43. run("xclip -selection clipboard", input=to_copy, direct_output=True)
  44. copied = True
  45. if shutil.which('wl-copy'):
  46. run("wl-copy", input=to_copy, direct_output=True)
  47. copied = True
  48. if not copied:
  49. print("Install xsel/xclip (X11) or wl-clipboard (Wayland) to use copy")
  50. #This method returns an array with all the values in all system clipboards
  51. def clipboard_paste():
  52. #We use a set to avoid duplicates
  53. clipboards = set()
  54. cmds = set()
  55. pasted = False
  56. if shutil.which('xsel'):
  57. pasted = True
  58. for selec in ["-p","-s","-b"]:
  59. cmds.add("xsel "+selec)
  60. if shutil.which('xclip'):
  61. pasted = True
  62. for selec in ["clipboard","primary","secondary"]:
  63. cmds.add("xsel "+selec)
  64. if shutil.which('wl-paste'):
  65. pasted = True
  66. for selec in ["", "-p"]:
  67. cmds.add("wl-paste "+selec)
  68. for cmd in cmds:
  69. try:
  70. clipboards.add(run(cmd))
  71. except Exception as err:
  72. #print("Skippink clipboard %s because %s"%(selec,err))
  73. pass
  74. if not pasted:
  75. print("Install xsel/xclip (X11) or wl-clipboard (Wayland) to get URLs from your clipboard")
  76. return list(clipboards)
  77. ## }}} end of imports
  78. # Command abbreviations
  79. _ABBREVS = {
  80. "..": "up",
  81. "a": "add",
  82. "b": "back",
  83. "bb": "blackbox",
  84. "bm": "bookmarks",
  85. "book": "bookmarks",
  86. "cp": "copy",
  87. "f": "forward",
  88. "g": "go",
  89. "h": "history",
  90. "hist": "history",
  91. "l": "view",
  92. "less": "view",
  93. "man": "help",
  94. "mv": "move",
  95. "n": "next",
  96. "off": "offline",
  97. "on": "online",
  98. "p": "previous",
  99. "prev": "previous",
  100. "q": "quit",
  101. "r": "reload",
  102. "s": "save",
  103. "se": "search",
  104. "/": "find",
  105. "t": "tour",
  106. "u": "up",
  107. "v": "view",
  108. "w": "wikipedia",
  109. "wen": "wikipedia en",
  110. "wfr": "wikipedia fr",
  111. "wes": "wikipedia es",
  112. }
  113. _MIME_HANDLERS = {
  114. }
  115. # GeminiClient Decorators
  116. def needs_gi(inner):
  117. def outer(self, *args, **kwargs):
  118. if not self.current_url:
  119. print("You need to 'go' somewhere, first")
  120. return None
  121. else:
  122. return inner(self, *args, **kwargs)
  123. outer.__doc__ = inner.__doc__
  124. return outer
  125. class GeminiClient(cmd.Cmd):
  126. def __init__(self, completekey="tab", synconly=False):
  127. cmd.Cmd.__init__(self)
  128. # Set umask so that nothing we create can be read by anybody else.
  129. # The certificate cache and TOFU database contain "browser history"
  130. # type sensitivie information.
  131. os.umask(0o077)
  132. self.opencache = opnk.opencache()
  133. self.theme = offthemes.default
  134. self.set_prompt("ON")
  135. self.current_url = None
  136. self.hist_index = 0
  137. self.marks = {}
  138. self.page_index = 0
  139. self.permanent_redirects = {}
  140. # Sync-only mode is restriced by design
  141. self.offline_only = False
  142. self.sync_only = False
  143. self.support_http = netcache._DO_HTTP
  144. self.automatic_choice = "n"
  145. self.client_certs = {
  146. "active": None
  147. }
  148. self.active_cert_domains = []
  149. self.active_is_transient = False
  150. self.options = {
  151. "debug" : False,
  152. "beta" : False,
  153. "timeout" : 600,
  154. "short_timeout" : 5,
  155. "width" : 72,
  156. "auto_follow_redirects" : True,
  157. "tls_mode" : "tofu",
  158. "archives_size" : 200,
  159. "history_size" : 200,
  160. "max_size_download" : 10,
  161. "editor" : None,
  162. "download_images_first" : True,
  163. "images_mode" : "readable",
  164. "redirects" : True,
  165. # the wikipedia entry needs two %s, one for lang, other for search
  166. "wikipedia" : "gemini://vault.transjovian.org:1965/search/%s/%s",
  167. "search" : "gemini://kennedy.gemi.dev/search?%s",
  168. "accept_bad_ssl_certificates" : False,
  169. "default_protocol" : "gemini",
  170. }
  171. self.redirects = offblocklist.redirects
  172. for i in offblocklist.blocked:
  173. self.redirects[i] = "blocked"
  174. term_width(new_width=self.options["width"])
  175. self.log = {
  176. "start_time": time.time(),
  177. }
  178. def set_prompt(self,prompt):
  179. key = "prompt_%s"%prompt.lower()
  180. if key in self.theme:
  181. colors = self.theme[key]
  182. else:
  183. #default color is green
  184. colors = ["green"]
  185. open_color = ""
  186. close_color = ""
  187. for c in colors:
  188. if c in offthemes.colors:
  189. ansi = offthemes.colors[c]
  190. else:
  191. ansi = ["32","39"]
  192. open_color += "%s;"%ansi[0]
  193. close_color += "%s;"%ansi[1]
  194. #removing the last ";"
  195. if open_color.endswith(";"):
  196. open_color = open_color[:-1]
  197. if close_color.endswith(";"):
  198. close_color = close_color[:-1]
  199. self.prompt = "\001\x1b[%sm\002"%open_color + prompt + "\001\x1b[%sm\002"%close_color + "> "
  200. #support for 256 color mode:
  201. #self.prompt = "\001\x1b[38;5;76m\002" + "ON" + "\001\x1b[38;5;255m\002" + "> " + "\001\x1b[0m\002"
  202. return self.prompt
  203. def complete_list(self,text,line,begidx,endidx):
  204. allowed = []
  205. cmds = ["create","edit","subscribe","freeze","normal","delete","help"]
  206. lists = self.list_lists()
  207. words = len(line.split())
  208. # We need to autocomplete listname for the first or second argument
  209. # If the first one is a cmds
  210. if words <= 1:
  211. allowed = lists + cmds
  212. elif words == 2:
  213. # if text, the completing word is the second
  214. cond = bool(text)
  215. if text:
  216. allowed = lists + cmds
  217. else:
  218. current_cmd = line.split()[1]
  219. if current_cmd in ["help", "create"]:
  220. allowed = []
  221. elif current_cmd in cmds:
  222. allowed = lists
  223. elif words == 3 and text != "":
  224. current_cmd = line.split()[1]
  225. if current_cmd in ["help", "create"]:
  226. allowed = []
  227. elif current_cmd in cmds:
  228. allowed = lists
  229. return [i+" " for i in allowed if i.startswith(text)]
  230. def complete_add(self,text,line,begidx,endidx):
  231. if len(line.split()) == 2 and text != "":
  232. allowed = self.list_lists()
  233. elif len(line.split()) == 1:
  234. allowed = self.list_lists()
  235. else:
  236. allowed = []
  237. return [i+" " for i in allowed if i.startswith(text)]
  238. def complete_move(self,text,line,begidx,endidx):
  239. return self.complete_add(text,line,begidx,endidx)
  240. def complete_tour(self,text,line,begidx,endidx):
  241. return self.complete_add(text,line,begidx,endidx)
  242. def complete_theme(self,text,line,begidx,endidx):
  243. elements = offthemes.default
  244. colors = offthemes.colors
  245. words = len(line.split())
  246. if words <= 1:
  247. allowed = elements
  248. elif words == 2 and text != "":
  249. allowed = elements
  250. else:
  251. allowed = colors
  252. return [i+" " for i in allowed if i.startswith(text)]
  253. def get_renderer(self,url=None):
  254. # If launched without argument, we return the renderer for the current URL
  255. if not url: url = self.current_url
  256. return self.opencache.get_renderer(url,theme=self.theme)
  257. def _go_to_url(self, url, update_hist=True, force_refresh=False, handle=True,\
  258. grep=None,name=None, mode=None,limit_size=False):
  259. """This method might be considered "the heart of Offpunk".
  260. Everything involved in fetching a gemini resource happens here:
  261. sending the request over the network, parsing the response,
  262. storing the response in a temporary file, choosing
  263. and calling a handler program, and updating the history.
  264. Nothing is returned."""
  265. if not url:
  266. return
  267. url,newmode = unmode_url(url)
  268. if not mode: mode = newmode
  269. #we don’t handle the name anymore !
  270. if name:
  271. print("We don’t handle name of URL: %s"%name)
  272. # Obey permanent redirects
  273. if url in self.permanent_redirects:
  274. self._go_to_url(self.permanent_redirects[url],update_hist=update_hist,\
  275. force_refresh=force_refresh, handle=handle, name=name,mode=mode,\
  276. limit_size=limit_size,grep=grep)
  277. return
  278. # Code to translate URLs to better frontends (think twitter.com -> nitter)
  279. parsed = urllib.parse.urlparse(url)
  280. netloc = parsed.netloc
  281. if netloc.startswith("www."):
  282. netloc = netloc[4:]
  283. #we block/redirect even subdomains
  284. for key in self.redirects.keys():
  285. match = key == netloc
  286. if key.startswith("*"):
  287. match = netloc.endswith(key[1:])
  288. if match:
  289. if self.redirects[key] == "blocked":
  290. text = "This website has been blocked.\n"
  291. text += "Use the redirect command to unblock it."
  292. if handle and not self.sync_only:
  293. print(text)
  294. return
  295. else:
  296. parsed = parsed._replace(netloc = self.redirects[key])
  297. url = urllib.parse.urlunparse(parsed)
  298. params = {}
  299. params["timeout"] = self.options["short_timeout"]
  300. if limit_size:
  301. params["max_size"] = int(self.options["max_size_download"])*1000000
  302. params["print_error"] = not self.sync_only
  303. params["interactive"] = not self.sync_only
  304. params["offline"] = self.offline_only
  305. params["accept_bad_ssl_certificates"] = self.options["accept_bad_ssl_certificates"]
  306. if mode:
  307. params["images_mode"] = mode
  308. else:
  309. params["images_mode"] = self.options["images_mode"]
  310. if force_refresh:
  311. params["validity"] = 1
  312. elif not self.offline_only:
  313. #A cache is always valid at least 60seconds
  314. params["validity"] = 60
  315. # Use cache or mark as to_fetch if resource is not cached
  316. if handle and not self.sync_only:
  317. displayed, url = self.opencache.opnk(url,mode=mode,grep=grep,theme=self.theme,**params)
  318. modedurl = mode_url(url,mode)
  319. if not displayed:
  320. #if we can’t display, we mark to sync what is not local
  321. if not is_local(url) and not netcache.is_cache_valid(url):
  322. self.get_list("to_fetch")
  323. r = self.list_add_line("to_fetch",url=modedurl,verbose=False)
  324. if r:
  325. print("%s not available, marked for syncing"%url)
  326. else:
  327. print("%s already marked for syncing"%url)
  328. else:
  329. self.page_index = 0
  330. # Update state (external files are not added to history)
  331. self.current_url = modedurl
  332. if update_hist and not self.sync_only:
  333. self._update_history(modedurl)
  334. else:
  335. #we are asked not to handle or in sync_only mode
  336. if self.support_http or not parsed.scheme in ["http","https"] :
  337. netcache.fetch(url,**params)
  338. @needs_gi
  339. def _show_lookup(self, offset=0, end=None, show_url=False):
  340. for n, u in enumerate(self.get_renderer().get_links()[offset:end]):
  341. index = n+offset+1
  342. line = "[%s] %s" %(index,u)
  343. #TODO: implement proper listing of url (with protocol and show_url)
  344. # protocol = "" if gi.scheme == "gemini" else " %s" % gi.scheme
  345. # line = "[%d%s] %s" % (index, protocol, gi.name or gi.url)
  346. # line += " (%s)" % gi.url
  347. print(line)
  348. def _update_history(self, url):
  349. # We never update while in sync_only
  350. # We don’t add history to itself.
  351. if self.sync_only or not url or url == "list:///history":
  352. return
  353. #First, we call get_list to create history if needed
  354. self.get_list("history")
  355. links = self.list_get_links("history")
  356. length = len(links)
  357. #Don’t update history if we are back/forwarding through it
  358. if length > 0 and links[self.hist_index] == url:
  359. return
  360. if length > self.options["history_size"]:
  361. length = self.options["history_size"]
  362. self.list_add_top("history",limit=self.options["history_size"],truncate_lines=self.hist_index)
  363. self.hist_index = 0
  364. # Cmd implementation follows
  365. def default(self, line):
  366. if line.strip() == "EOF":
  367. return self.onecmd("quit")
  368. elif line.startswith("/"):
  369. return self.do_find(line[1:])
  370. # Expand abbreviated commands
  371. first_word = line.split()[0].strip()
  372. if first_word in _ABBREVS:
  373. full_cmd = _ABBREVS[first_word]
  374. expanded = line.replace(first_word, full_cmd, 1)
  375. return self.onecmd(expanded)
  376. # Try to access it like an URL
  377. if looks_like_url(line):
  378. return self.do_go(line)
  379. # Try to parse numerical index for lookup table
  380. try:
  381. n = int(line.strip())
  382. except ValueError:
  383. print("What?")
  384. return
  385. # if we have no url, there's nothing to do
  386. if self.current_url is None:
  387. print("No links to index")
  388. return
  389. else:
  390. r = self.get_renderer()
  391. if r:
  392. url = r.get_link(n)
  393. self._go_to_url(url)
  394. else:
  395. print("No page with links")
  396. return
  397. ### Settings
  398. def do_redirect(self,line):
  399. """Display and manage the list of redirected URLs. This features is mostly useful to use privacy-friendly frontends for popular websites."""
  400. if len(line.split()) == 1:
  401. if line in self.redirects:
  402. print("%s is redirected to %s" %(line,self.redirects[line]))
  403. else:
  404. print("Please add a destination to redirect %s" %line)
  405. elif len(line.split()) >= 2:
  406. orig, dest = line.split(" ",1)
  407. if dest.lower() == "none":
  408. if orig in self.redirects:
  409. self.redirects.pop(orig)
  410. print("Redirection for %s has been removed"%orig)
  411. else:
  412. print("%s was not redirected. Nothing has changed."%orig)
  413. elif dest.lower() == "block":
  414. self.redirects[orig] = "blocked"
  415. print("%s will now be blocked"%orig)
  416. else:
  417. self.redirects[orig] = dest
  418. print("%s will now be redirected to %s" %(orig,dest))
  419. else:
  420. toprint="Current redirections:\n"
  421. toprint+="--------------------\n"
  422. for r in self.redirects:
  423. toprint += ("%s\t->\t%s\n" %(r,self.redirects[r]))
  424. toprint +="\nTo add new, use \"redirect origine.com destination.org\""
  425. toprint +="\nTo remove a redirect, use \"redirect origine.com NONE\""
  426. toprint +="\nTo completely block a website, use \"redirect origine.com BLOCK\""
  427. toprint +="\nTo block also subdomains, prefix with *: \"redirect *origine.com BLOCK\""
  428. print(toprint)
  429. def do_set(self, line):
  430. """View or set various options."""
  431. if not line.strip():
  432. # Show all current settings
  433. for option in sorted(self.options.keys()):
  434. print("%s %s" % (option, self.options[option]))
  435. elif len(line.split()) == 1 :
  436. # Show current value of one specific setting
  437. option = line.strip()
  438. if option in self.options:
  439. print("%s %s" % (option, self.options[option]))
  440. else:
  441. print("Unrecognised option %s" % option)
  442. else:
  443. # Set value of one specific setting
  444. option, value = line.split(" ", 1)
  445. if option not in self.options:
  446. print("Unrecognised option %s" % option)
  447. return
  448. # Validate / convert values
  449. elif option == "tls_mode":
  450. if value.lower() not in ("ca", "tofu"):
  451. print("TLS mode must be `ca` or `tofu`!")
  452. return
  453. elif option == "accept_bad_ssl_certificates":
  454. if value.lower() == "false":
  455. print("Only high security certificates are now accepted")
  456. elif value.lower() == "true":
  457. print("Low security SSL certificates are now accepted")
  458. else:
  459. print("accept_bad_ssl_certificates should be True or False")
  460. return
  461. elif option == "width":
  462. if value.isnumeric():
  463. value = int(value)
  464. print("changing width to ",value)
  465. term_width(new_width=value)
  466. self.opencache.cleanup()
  467. else:
  468. print("%s is not a valid width (integer required)"%value)
  469. elif value.isnumeric():
  470. value = int(value)
  471. elif value.lower() == "false":
  472. value = False
  473. elif value.lower() == "true":
  474. value = True
  475. else:
  476. try:
  477. value = float(value)
  478. except ValueError:
  479. pass
  480. self.options[option] = value
  481. def do_theme(self,line):
  482. """Change the colors of your rendered text.
  483. "theme ELEMENT COLOR"
  484. ELEMENT is one of: window_title, window_subtitle, title,
  485. subtitle,subsubtitle,link,oneline_link,new_link,image_link,preformatted,blockquote.
  486. COLOR is one or many (separated by space) of: bold, faint, italic, underline, black,
  487. red, green, yellow, blue, purple, cyan, white.
  488. Each color can alternatively be prefaced with "bright_"."""
  489. words = line.split()
  490. le = len(words)
  491. if le == 0:
  492. t = self.get_renderer("list:///").get_theme()
  493. for e in t:
  494. print("%s set to %s"%(e,t[e]))
  495. else:
  496. element = words[0]
  497. if element not in offthemes.default.keys():
  498. print("%s is not a valid theme element"%element)
  499. print("Valid theme elements are: ")
  500. valid = []
  501. for k in offthemes.default:
  502. valid.append(k)
  503. print(valid)
  504. else:
  505. if le == 1:
  506. if element in self.theme.keys():
  507. value = self.theme[element]
  508. else:
  509. value = offthemes.default[element]
  510. print("%s is set to %s"%(element,str(value)))
  511. else:
  512. #Now we parse the colors
  513. for w in words[1:]:
  514. if w not in offthemes.colors.keys():
  515. print("%s is not a valid color"%w)
  516. print("Valid colors are one of: ")
  517. valid = []
  518. for k in offthemes.colors:
  519. valid.append(k)
  520. print(valid)
  521. return
  522. self.theme[element] = words[1:]
  523. self.opencache.cleanup()
  524. #now we upadte the prompt
  525. if self.offline_only:
  526. self.set_prompt("OFF")
  527. else:
  528. self.set_prompt("ON")
  529. def do_handler(self, line):
  530. """View or set handler commands for different MIME types."""
  531. if not line.strip():
  532. # Show all current handlers
  533. h = self.opencache.get_handlers()
  534. for mime in sorted(h.keys()):
  535. print("%s %s" % (mime, h[mime]))
  536. elif len(line.split()) == 1:
  537. mime = line.strip()
  538. h = self.opencache.get_handlers(mime=mime)
  539. if h:
  540. print("%s %s" % (mime, h))
  541. else:
  542. print("No handler set for MIME type %s" % mime)
  543. else:
  544. mime, handler = line.split(" ", 1)
  545. self.opencache.set_handler(mime,handler)
  546. def do_abbrevs(self, *args):
  547. """Print all Offpunk command abbreviations."""
  548. header = "Command Abbreviations:"
  549. self.stdout.write("\n{}\n".format(str(header)))
  550. if self.ruler:
  551. self.stdout.write("{}\n".format(str(self.ruler * len(header))))
  552. for k, v in _ABBREVS.items():
  553. self.stdout.write("{:<7} {}\n".format(k, v))
  554. self.stdout.write("\n")
  555. def do_offline(self, *args):
  556. """Use Offpunk offline by only accessing cached content"""
  557. if self.offline_only:
  558. print("Offline and undisturbed.")
  559. else:
  560. self.offline_only = True
  561. self.set_prompt("OFF")
  562. print("Offpunk is now offline and will only access cached content")
  563. def do_online(self, *args):
  564. """Use Offpunk online with a direct connection"""
  565. if self.offline_only:
  566. self.offline_only = False
  567. self.set_prompt("ON")
  568. print("Offpunk is online and will access the network")
  569. else:
  570. print("Already online. Try offline.")
  571. def do_copy(self, arg):
  572. """Copy the content of the last visited page as gemtext/html in the clipboard.
  573. Use with "url" as argument to only copy the adress.
  574. Use with "raw" to copy ANSI content as seen in your terminal (with colour codes).
  575. Use with "cache" to copy the path of the cached content.
  576. Use with "title" to copy the title of the page.
  577. Use with "link" to copy a link in the gemtext format to that page with the title.
  578. """
  579. if self.current_url:
  580. args = arg.split()
  581. if args and args[0] == "url":
  582. if len(args) > 1 and args[1].isdecimal():
  583. url = self.get_renderer().get_link(int(args[1])-1)
  584. else:
  585. url,mode = unmode_url(self.current_url)
  586. print(url)
  587. clipboard_copy(url)
  588. elif args and args[0] == "raw":
  589. tmp = self.opencache.get_temp_filename(self.current_url)
  590. if tmp:
  591. clipboard_copy(open(tmp,"rb"))
  592. elif args and args[0] == "cache":
  593. clipboard_copy(netcache.get_cache_path(self.current_url))
  594. elif args and args[0] == "title":
  595. title = self.get_renderer().get_page_title()
  596. clipboard_copy(title)
  597. print(title)
  598. elif args and args[0] == "link":
  599. link = "=> %s %s"%(unmode_url(self.current_url)[0],\
  600. self.get_renderer().get_page_title())
  601. print(link)
  602. clipboard_copy(link)
  603. else:
  604. clipboard_copy(open(netcache.get_cache_path(self.current_url),"rb"))
  605. else:
  606. print("No content to copy, visit a page first")
  607. ### Stuff for getting around
  608. def do_go(self, line):
  609. """Go to a gemini URL or marked item."""
  610. line = line.strip()
  611. if not line:
  612. clipboards = clipboard_paste()
  613. urls = []
  614. for u in clipboards:
  615. if "://" in u and looks_like_url(u) and u not in urls :
  616. urls.append(u)
  617. if len(urls) > 1:
  618. stri = "URLs in your clipboard\n"
  619. counter = 0
  620. for u in urls:
  621. counter += 1
  622. stri += "[%s] %s\n"%(counter,u)
  623. stri += "Where do you want to go today ?> "
  624. ans = input(stri)
  625. if ans.isdigit() and 0 < int(ans) <= len(urls):
  626. self.do_go(urls[int(ans)-1])
  627. elif len(urls) == 1:
  628. self.do_go(urls[0])
  629. else:
  630. print("Go where? (hint: simply copy an URL in your clipboard)")
  631. # First, check for possible marks
  632. elif line in self.marks:
  633. url = self.marks[line]
  634. self._go_to_url(url)
  635. # or a local file
  636. elif os.path.exists(os.path.expanduser(line)):
  637. self._go_to_url(line)
  638. # If this isn't a mark, treat it as a URL
  639. elif looks_like_url(line):
  640. self._go_to_url(line)
  641. elif "://" not in line and "default_protocol" in self.options.keys()\
  642. and looks_like_url(self.options["default_protocol"]+"://"+line):
  643. self._go_to_url(self.options["default_protocol"]+"://"+line)
  644. else:
  645. print("%s is not a valid URL to go"%line)
  646. @needs_gi
  647. def do_reload(self, *args):
  648. """Reload the current URL."""
  649. if self.offline_only and not is_local(self.current_url):
  650. self.get_list("to_fetch")
  651. r = self.list_add_line("to_fetch",url=self.current_url,verbose=False)
  652. if r:
  653. print("%s marked for syncing" %self.current_url)
  654. else:
  655. print("%s already marked for syncing" %self.current_url)
  656. else:
  657. self.opencache.cleanup()
  658. self._go_to_url(self.current_url, force_refresh=False)
  659. @needs_gi
  660. def do_up(self, *args):
  661. """Go up one directory in the path.
  662. Take an integer as argument to go up multiple times."""
  663. level = 1
  664. if args[0].isnumeric():
  665. level = int(args[0])
  666. elif args[0] != "":
  667. print("Up only take integer as arguments")
  668. #TODO : implement up, this code is copy/pasted from GeminiItem
  669. url, mode = unmode_url(self.current_url)
  670. parsed = urllib.parse.urlparse(url)
  671. path = parsed.path.rstrip('/')
  672. count = 0
  673. while count < level:
  674. pathbits = list(os.path.split(path))
  675. # Don't try to go higher than root or in config
  676. if is_local(url) or len(pathbits) == 1 :
  677. break
  678. # Get rid of bottom component
  679. if len(pathbits) > 1:
  680. pathbits.pop()
  681. path = os.path.join(*pathbits)
  682. count += 1
  683. if parsed.scheme == "gopher":
  684. path = "/1" + path
  685. newurl = urllib.parse.urlunparse((parsed.scheme,parsed.netloc,path,"","",""))
  686. self._go_to_url(newurl)
  687. def do_back(self, *args):
  688. """Go back to the previous gemini item."""
  689. histfile = self.get_list("history")
  690. links = self.list_get_links("history")
  691. if self.hist_index >= len(links) -1:
  692. return
  693. self.hist_index += 1
  694. url = links[self.hist_index]
  695. self._go_to_url(url, update_hist=False)
  696. def do_forward(self, *args):
  697. """Go forward to the next gemini item."""
  698. histfile = self.get_list("history")
  699. links = self.list_get_links("history")
  700. if self.hist_index <= 0:
  701. return
  702. self.hist_index -= 1
  703. url = links[self.hist_index]
  704. self._go_to_url(url, update_hist=False)
  705. @needs_gi
  706. def do_root(self, *args):
  707. """Go to root selector of the server hosting current item."""
  708. parse = urllib.parse.urlparse(self.current_url)
  709. self._go_to_url(urllib.parse.urlunparse((parse.scheme,parse.netloc,"/","","","")))
  710. def do_tour(self, line):
  711. """Add index items as waypoints on a tour, which is basically a FIFO
  712. queue of gemini items.
  713. `tour` or `t` alone brings you to the next item in your tour.
  714. Items can be added with `tour 1 2 3 4` or ranges like `tour 1-4`.
  715. All items in current menu can be added with `tour *`.
  716. All items in $LIST can be added with `tour $LIST`.
  717. Current item can be added back to the end of the tour with `tour .`.
  718. Current tour can be listed with `tour ls` and scrubbed with `tour clear`."""
  719. # Creating the tour list if needed
  720. self.get_list("tour")
  721. line = line.strip()
  722. if not line:
  723. # Fly to next waypoint on tour
  724. if len(self.list_get_links("tour")) < 1:
  725. print("End of tour.")
  726. else:
  727. url = self.list_go_to_line("1","tour")
  728. if url:
  729. self.list_rm_url(url,"tour")
  730. elif line == "ls":
  731. self.list_show("tour")
  732. elif line == "clear":
  733. for l in self.list_get_links("tour"):
  734. self.list_rm_url(l,"tour")
  735. elif line == "*":
  736. for l in self.get_renderer().get_links():
  737. self.list_add_line("tour",url=l,verbose=False)
  738. elif line == ".":
  739. self.list_add_line("tour",verbose=False)
  740. elif looks_like_url(line):
  741. self.list_add_line("tour",url=line)
  742. elif line in self.list_lists():
  743. list_path = self.list_path(line)
  744. if not list_path:
  745. print("List %s does not exist. Cannot add it to tour"%(list))
  746. else:
  747. url = "list:///%s"%line
  748. display = not self.sync_only
  749. for l in self.get_renderer(url).get_links():
  750. self.list_add_line("tour",url=l,verbose=False)
  751. elif self.current_url:
  752. for index in line.split():
  753. try:
  754. pair = index.split('-')
  755. if len(pair) == 1:
  756. # Just a single index
  757. n = int(index)
  758. url = self.get_renderer().get_link(n)
  759. self.list_add_line("tour",url=url,verbose=False)
  760. elif len(pair) == 2:
  761. # Two endpoints for a range of indices
  762. if int(pair[0]) < int(pair[1]):
  763. for n in range(int(pair[0]), int(pair[1]) + 1):
  764. url = self.get_renderer().get_link(n)
  765. self.list_add_line("tour",url=url,verbose=False)
  766. else:
  767. for n in range(int(pair[0]), int(pair[1]) - 1, -1):
  768. url = self.get_renderer().get_link(n)
  769. self.list_add_line("tour",url=url,verbose=False)
  770. else:
  771. # Syntax error
  772. print("Invalid use of range syntax %s, skipping" % index)
  773. except ValueError:
  774. print("Non-numeric index %s, skipping." % index)
  775. except IndexError:
  776. print("Invalid index %d, skipping." % n)
  777. @needs_gi
  778. def do_mark(self, line):
  779. """Mark the current item with a single letter. This letter can then
  780. be passed to the 'go' command to return to the current item later.
  781. Think of it like marks in vi: 'mark a'='ma' and 'go a'=''a'.
  782. Marks are temporary until shutdown (not saved to disk)."""
  783. line = line.strip()
  784. if not line:
  785. for mark, gi in self.marks.items():
  786. print("[%s] %s (%s)" % (mark, gi.name, gi.url))
  787. elif line.isalpha() and len(line) == 1:
  788. self.marks[line] = self.current_url
  789. else:
  790. print("Invalid mark, must be one letter")
  791. @needs_gi
  792. def do_info(self,line):
  793. """Display information about current page."""
  794. renderer = self.get_renderer()
  795. url,mode = unmode_url(self.current_url)
  796. out = renderer.get_page_title() + "\n\n"
  797. out += "URL : " + url + "\n"
  798. out += "Mime : " + renderer.get_mime() + "\n"
  799. out += "Cache : " + netcache.get_cache_path(url) + "\n"
  800. if self.get_renderer() :
  801. rend = str(self.get_renderer().__class__)
  802. rend = rend.lstrip("<class '__main__.").rstrip("'>")
  803. else:
  804. rend = "None"
  805. out += "Renderer : " + rend + "\n\n"
  806. lists = []
  807. for l in self.list_lists():
  808. if self.list_has_url(url,l):
  809. lists.append(l)
  810. if len(lists) > 0:
  811. out += "Page appeard in following lists :\n"
  812. for l in lists:
  813. if not self.list_is_system(l):
  814. status = "normal list"
  815. if self.list_is_subscribed(l):
  816. status = "subscription"
  817. elif self.list_is_frozen(l):
  818. status = "frozen list"
  819. out += " • %s\t(%s)\n" %(l,status)
  820. for l in lists:
  821. if self.list_is_system(l):
  822. out += " • %s\n" %l
  823. else:
  824. out += "Page is not save in any list"
  825. print(out)
  826. def do_version(self, line):
  827. """Display version and system information."""
  828. def has(value):
  829. if value:
  830. return "\t\x1b[1;32mInstalled\x1b[0m\n"
  831. else:
  832. return "\t\x1b[1;31mNot Installed\x1b[0m\n"
  833. output = "Offpunk " + __version__ + "\n"
  834. output += "===========\n"
  835. output += "Highly recommended:\n"
  836. output += " - python-cryptography : " + has(netcache._HAS_CRYPTOGRAPHY)
  837. output += " - xdg-open : " + has(opnk._HAS_XDGOPEN)
  838. output += "\nWeb browsing:\n"
  839. output += " - python-requests : " + has(netcache._DO_HTTP)
  840. output += " - python-feedparser : " + has(ansicat._DO_FEED)
  841. output += " - python-bs4 : " + has(ansicat._HAS_SOUP)
  842. output += " - python-readability : " + has(ansicat._HAS_READABILITY)
  843. output += " - timg 1.3.2+ : " + has(ansicat._NEW_TIMG)
  844. if ansicat._NEW_CHAFA:
  845. output += " - chafa 1.10+ : " + has(ansicat._HAS_CHAFA)
  846. else:
  847. output += " - chafa : " + has(ansicat._HAS_CHAFA)
  848. output += " - python-pil : " + has(ansicat._HAS_PIL)
  849. output += "\nNice to have:\n"
  850. output += " - python-setproctitle : " + has(_HAS_SETPROCTITLE)
  851. clip_support = shutil.which("xsel") or shutil.which("xclip")
  852. output += " - X11 clipboard (xsel or xclip) : " + has(clip_support)
  853. output += " - Wayland clipboard (wl-clipboard): " + has(shutil.which("wl-copy"))
  854. output += "\nFeatures :\n"
  855. if ansicat._NEW_CHAFA:
  856. output += " - Render images (chafa or timg) : " + has(ansicat._RENDER_IMAGE)
  857. else:
  858. output += " - Render images (python-pil, chafa or timg) : " + has(ansicat._RENDER_IMAGE)
  859. output += " - Render HTML (bs4, readability) : " + has(ansicat._DO_HTML)
  860. output += " - Render Atom/RSS feeds (feedparser) : " + has(ansicat._DO_FEED)
  861. output += " - Connect to http/https (requests) : " + has(netcache._DO_HTTP)
  862. output += " - Detect text encoding (python-chardet) : " + has(netcache._HAS_CHARDET)
  863. output += " - restore last position (less 572+) : " + has(opnk._LESS_RESTORE_POSITION)
  864. output += "\n"
  865. output += "Config directory : " + xdg("config") + "\n"
  866. output += "User Data directory : " + xdg("data") + "\n"
  867. output += "Cache directoy : " + xdg("cache")
  868. print(output)
  869. ### Stuff that modifies the lookup table
  870. def do_ls(self, line):
  871. """List contents of current index.
  872. Use 'ls -l' to see URLs."""
  873. self._show_lookup(show_url = "-l" in line)
  874. self.page_index = 0
  875. def do_search(self,line):
  876. """Search on Gemini using the engine configured (by default kennedy.gemi.dev)
  877. You can configure it using "set search URL".
  878. URL should contains one "%s" that will be replaced by the search term."""
  879. search = urllib.parse.quote(line)
  880. url = self.options["search"]%search
  881. self._go_to_url(url)
  882. def do_wikipedia(self,line):
  883. """Search on wikipedia using the configured Gemini interface.
  884. The first word should be the two letters code for the language.
  885. Exemple : "wikipedia en Gemini protocol"
  886. But you can also use abbreviations to go faster:
  887. "wen Gemini protocol". (your abbreviation might be missing, report the bug)
  888. The interface used can be modified with the command:
  889. "set wikipedia URL" where URL should contains two "%s", the first
  890. one used for the language, the second for the search string."""
  891. words = line.split(" ",maxsplit=1)
  892. if len(words[0]) == 2:
  893. lang = words[0]
  894. search = urllib.parse.quote(words[1])
  895. else:
  896. lang = "en"
  897. search = urllib.parse.quote(line)
  898. url = self.options["wikipedia"]%(lang,search)
  899. self._go_to_url(url)
  900. def do_gus(self, line):
  901. """Submit a search query to the geminispace.info search engine."""
  902. if not line:
  903. print("What?")
  904. return
  905. search = line.replace(" ","%20")
  906. self._go_to_url("gemini://geminispace.info/search?%s"%search)
  907. def do_history(self, *args):
  908. """Display history."""
  909. self.list_show("history")
  910. @needs_gi
  911. def do_find(self, searchterm):
  912. """Find in current page by displaying only relevant lines (grep)."""
  913. self._go_to_url(self.current_url,update_hist=False,grep=searchterm)
  914. def emptyline(self):
  915. """Page through index ten lines at a time."""
  916. i = self.page_index
  917. if not self.current_url or i > len(self.get_renderer().get_links()):
  918. return
  919. self._show_lookup(offset=i, end=i+10)
  920. self.page_index += 10
  921. ### Stuff that does something to most recently viewed item
  922. @needs_gi
  923. def do_cat(self, *args):
  924. """Run most recently visited item through "cat" command."""
  925. run("cat", input=open(self.opencache.get_temp_filename(self.current_url), "rb"),\
  926. direct_output=True)
  927. @needs_gi
  928. def do_view(self, *args):
  929. """Run most recently visited item through "less" command, restoring \
  930. previous position.
  931. Use "view normal" to see the default article view on html page.
  932. Use "view full" to see a complete html page instead of the article view.
  933. Use "view feed" to see the the linked feed of the page (in any).
  934. Use "view feeds" to see available feeds on this page.
  935. Use "view XX" where XX is a number to view information about link XX.
  936. (full, feed, feeds have no effect on non-html content)."""
  937. if self.current_url and args and args[0] != "":
  938. u, m = unmode_url(self.current_url)
  939. if args[0] in ["full","debug","source"]:
  940. self._go_to_url(self.current_url,mode=args[0])
  941. elif args[0] in ["normal","readable"]:
  942. self._go_to_url(self.current_url,mode="readable")
  943. elif args[0] == "feed":
  944. subs = self.get_renderer().get_subscribe_links()
  945. if len(subs) > 1:
  946. self.do_go(subs[1][0])
  947. elif "rss" in subs[0][1] or "atom" in subs[0][1]:
  948. print("%s is already a feed" %u)
  949. else:
  950. print("No other feed found on %s"%u)
  951. elif args[0] == "feeds":
  952. subs = self.get_renderer().get_subscribe_links()
  953. stri = "Available views :\n"
  954. counter = 0
  955. for s in subs:
  956. counter += 1
  957. stri += "[%s] %s [%s]\n"%(counter,s[0],s[1])
  958. stri += "Which view do you want to see ? >"
  959. ans = input(stri)
  960. if ans.isdigit() and 0 < int(ans) <= len(subs):
  961. self.do_go(subs[int(ans)-1][0])
  962. elif args[0].isdigit():
  963. link_url = self.get_renderer().get_link(int(args[0]))
  964. if link_url:
  965. print("Link %s is: %s"%(args[0],link_url))
  966. if netcache.is_cache_valid(link_url):
  967. last_modified = netcache.cache_last_modified(link_url)
  968. link_renderer = self.get_renderer(link_url)
  969. if link_renderer:
  970. link_title = link_renderer.get_page_title()
  971. print(link_title)
  972. else:
  973. print("Empty cached version")
  974. print("Last cached on %s"%time.ctime(last_modified))
  975. else:
  976. print("No cached version for this link")
  977. else:
  978. print("Valid argument for view are : normal, full, feed, feeds or a number")
  979. else:
  980. self._go_to_url(self.current_url)
  981. @needs_gi
  982. def do_open(self, *args):
  983. """Open current item with the configured handler or xdg-open.
  984. Uses "open url" to open current URL in a browser.
  985. see "handler" command to set your handler."""
  986. u, m = unmode_url(self.current_url)
  987. if args[0] == "url":
  988. run("xdg-open %s", parameter=u, direct_output=True)
  989. else:
  990. self.opencache.opnk(u,terminal=False)
  991. @needs_gi
  992. def do_shell(self, line):
  993. """'cat' most recently visited item through a shell pipeline.
  994. '!' is an useful shortcut."""
  995. tmp = self.opencache.get_temp_filename(self.current_url)
  996. if tmp:
  997. run(line, input=open(tmp, "rb"), direct_output=True)
  998. @needs_gi
  999. def do_save(self, line):
  1000. """Save an item to the filesystem.
  1001. 'save n filename' saves menu item n to the specified filename.
  1002. 'save filename' saves the last viewed item to the specified filename.
  1003. 'save n' saves menu item n to an automagic filename."""
  1004. args = line.strip().split()
  1005. # First things first, figure out what our arguments are
  1006. if len(args) == 0:
  1007. # No arguments given at all
  1008. # Save current item, if there is one, to a file whose name is
  1009. # inferred from the gemini path
  1010. if not netcache.is_cache_valid(self.current_url):
  1011. print("You cannot save if not cached!")
  1012. return
  1013. else:
  1014. index = None
  1015. filename = None
  1016. elif len(args) == 1:
  1017. # One argument given
  1018. # If it's numeric, treat it as an index, and infer the filename
  1019. try:
  1020. index = int(args[0])
  1021. filename = None
  1022. # If it's not numeric, treat it as a filename and
  1023. # save the current item
  1024. except ValueError:
  1025. index = None
  1026. filename = os.path.expanduser(args[0])
  1027. elif len(args) == 2:
  1028. # Two arguments given
  1029. # Treat first as an index and second as filename
  1030. index, filename = args
  1031. try:
  1032. index = int(index)
  1033. except ValueError:
  1034. print("First argument is not a valid item index!")
  1035. return
  1036. filename = os.path.expanduser(filename)
  1037. else:
  1038. print("You must provide an index, a filename, or both.")
  1039. return
  1040. # Next, fetch the item to save, if it's not the current one.
  1041. if index:
  1042. last_url = self.current_url
  1043. try:
  1044. url = self.get_renderer().get_link(index)
  1045. self._go_to_url(url, update_hist = False, handle = False)
  1046. except IndexError:
  1047. print ("Index too high!")
  1048. self.current_url = last_url
  1049. return
  1050. else:
  1051. url = self.current_url
  1052. # Derive filename from current GI's path, if one hasn't been set
  1053. if not filename:
  1054. filename = os.path.basename(netcache.get_cache_path(self.current_url))
  1055. # Check for filename collisions and actually do the save if safe
  1056. if os.path.exists(filename):
  1057. print("File %s already exists!" % filename)
  1058. else:
  1059. # Don't use _get_active_tmpfile() here, because we want to save the
  1060. # "source code" of menus, not the rendered view - this way Offpunk
  1061. # can navigate to it later.
  1062. path = netcache.get_cache_path(url)
  1063. if os.path.isdir(path):
  1064. print("Can’t save %s because it’s a folder, not a file"%path)
  1065. else:
  1066. print("Saved to %s" % filename)
  1067. shutil.copyfile(path, filename)
  1068. # Restore gi if necessary
  1069. if index != None:
  1070. self._go_to_url(last_url, handle=False)
  1071. @needs_gi
  1072. def do_url(self, *args):
  1073. """Print URL of most recently visited item."""
  1074. url,mode = unmode_url(self.current_url)
  1075. print(url)
  1076. ### Bookmarking stuff
  1077. @needs_gi
  1078. def do_add(self, line):
  1079. """Add the current URL to the list specied as argument.
  1080. If no argument given, URL is added to Bookmarks."""
  1081. args = line.split()
  1082. if len(args) < 1 :
  1083. list = "bookmarks"
  1084. if not self.list_path(list):
  1085. self.list_create(list)
  1086. self.list_add_line(list)
  1087. else:
  1088. self.list_add_line(args[0])
  1089. # Get the list file name, creating or migrating it if needed.
  1090. # Migrate bookmarks/tour/to_fetch from XDG_CONFIG to XDG_DATA
  1091. # We migrate only if the file exists in XDG_CONFIG and not XDG_DATA
  1092. def get_list(self,list):
  1093. list_path = self.list_path(list)
  1094. if not list_path:
  1095. old_file_gmi = os.path.join(xdg("config"),list + ".gmi")
  1096. old_file_nogmi = os.path.join(xdg("config"),list)
  1097. target = os.path.join(xdg("data"),"lists")
  1098. if os.path.exists(old_file_gmi):
  1099. shutil.move(old_file_gmi,target)
  1100. elif os.path.exists(old_file_nogmi):
  1101. targetgmi = os.path.join(target,list+".gmi")
  1102. shutil.move(old_file_nogmi,targetgmi)
  1103. else:
  1104. if list == "subscribed":
  1105. title = "Subscriptions #subscribed (new links in those pages will be added to tour)"
  1106. elif list == "to_fetch":
  1107. title = "Links requested and to be fetched during the next --sync"
  1108. else:
  1109. title = None
  1110. self.list_create(list, title=title,quite=True)
  1111. list_path = self.list_path(list)
  1112. return list_path
  1113. @needs_gi
  1114. def do_subscribe(self,line):
  1115. """Subscribe to current page by saving it in the "subscribed" list.
  1116. If a new link is found in the page during a --sync, the new link is automatically
  1117. fetched and added to your next tour.
  1118. To unsubscribe, remove the page from the "subscribed" list."""
  1119. subs = self.get_renderer().get_subscribe_links()
  1120. if len(subs) > 1:
  1121. stri = "Multiple feeds have been found :\n"
  1122. elif "rss" in subs[0][1] or "atom" in subs[0][1] :
  1123. stri = "This page is already a feed:\n"
  1124. else:
  1125. stri = "No feed detected. You can still watch the page :\n"
  1126. counter = 0
  1127. for l in subs:
  1128. link = l[0]
  1129. already = []
  1130. for li in self.list_lists():
  1131. if self.list_is_subscribed(li):
  1132. if self.list_has_url(link,li):
  1133. already.append(li)
  1134. stri += "[%s] %s [%s]\n"%(counter+1,link,l[1])
  1135. if len(already) > 0:
  1136. stri += "\t -> (already subscribed through lists %s)\n"%(str(already))
  1137. counter += 1
  1138. stri += "\n"
  1139. stri += "Which feed do you want to subscribe ? > "
  1140. ans = input(stri)
  1141. if ans.isdigit() and 0 < int(ans) <= len(subs):
  1142. sublink,mime,title = subs[int(ans)-1]
  1143. else:
  1144. sublink,title = None,None
  1145. if sublink:
  1146. list_path = self.get_list("subscribed")
  1147. added = self.list_add_line("subscribed",url=sublink,verbose=False)
  1148. if added :
  1149. print("Subscribed to %s" %sublink)
  1150. else:
  1151. print("You are already subscribed to %s"%sublink)
  1152. else:
  1153. print("No subscription registered")
  1154. def do_bookmarks(self, line):
  1155. """Show or access the bookmarks menu.
  1156. 'bookmarks' shows all bookmarks.
  1157. 'bookmarks n' navigates immediately to item n in the bookmark menu.
  1158. Bookmarks are stored using the 'add' command."""
  1159. list_path = self.get_list("bookmarks")
  1160. args = line.strip()
  1161. if len(args.split()) > 1 or (args and not args.isnumeric()):
  1162. print("bookmarks command takes a single integer argument!")
  1163. elif args:
  1164. self.list_go_to_line(args,"bookmarks")
  1165. else:
  1166. self.list_show("bookmarks")
  1167. @needs_gi
  1168. def do_archive(self,args):
  1169. """Archive current page by removing it from every list and adding it to
  1170. archives, which is a special historical list limited in size. It is similar to `move archives`."""
  1171. for li in self.list_lists():
  1172. if li not in ["archives", "history"]:
  1173. u,m = unmode_url(self.current_url)
  1174. deleted = self.list_rm_url(u,li)
  1175. if deleted:
  1176. print("Removed from %s"%li)
  1177. self.list_add_top("archives",limit=self.options["archives_size"])
  1178. print("Archiving: %s"%self.get_renderer().get_page_title())
  1179. print("\x1b[2;34mCurrent maximum size of archives : %s\x1b[0m" %self.options["archives_size"])
  1180. #what is the line to add to a list for this url ?
  1181. def to_map_line(self,url=None):
  1182. if not url:
  1183. url = self.current_url
  1184. r = self.get_renderer(url)
  1185. if r:
  1186. title = r.get_page_title()
  1187. else:
  1188. title = ""
  1189. toreturn = "=> {} {}\n".format(url,title)
  1190. return toreturn
  1191. def list_add_line(self,list,url=None,verbose=True):
  1192. list_path = self.list_path(list)
  1193. if not list_path and self.list_is_system(list):
  1194. self.list_create(list,quite=True)
  1195. list_path = self.list_path(list)
  1196. if not list_path:
  1197. print("List %s does not exist. Create it with ""list create %s"""%(list,list))
  1198. return False
  1199. else:
  1200. if not url:
  1201. url = self.current_url
  1202. unmoded_url,mode = unmode_url(url)
  1203. # first we check if url already exists in the file
  1204. if self.list_has_url(url,list,exact_mode=True):
  1205. if verbose:
  1206. print("%s already in %s."%(url,list))
  1207. return False
  1208. # If the URL already exists but without a mode, we update the mode
  1209. # FIXME: this doesn’t take into account the case where you want to remove the mode
  1210. elif url != unmoded_url and self.list_has_url(unmoded_url,list):
  1211. self.list_update_url_mode(unmoded_url,list,mode)
  1212. if verbose:
  1213. print("%s has updated mode in %s to %s"%(url,list,mode))
  1214. else:
  1215. with open(list_path,"a") as l_file:
  1216. l_file.write(self.to_map_line(url))
  1217. l_file.close()
  1218. if verbose:
  1219. print("%s added to %s" %(url,list))
  1220. return True
  1221. @needs_gi
  1222. def list_add_top(self,list,limit=0,truncate_lines=0):
  1223. stri = self.to_map_line().strip("\n")
  1224. if list == "archives":
  1225. stri += ", archived on "
  1226. elif list == "history":
  1227. stri += ", visited on "
  1228. else:
  1229. stri += ", added to %s on "%list
  1230. stri += time.ctime() + "\n"
  1231. list_path = self.get_list(list)
  1232. with open(list_path,"r") as l_file:
  1233. lines = l_file.readlines()
  1234. l_file.close()
  1235. with open(list_path,"w") as l_file:
  1236. l_file.write("#%s\n"%list)
  1237. l_file.write(stri)
  1238. counter = 0
  1239. # Truncating is useful in case we open a new branch
  1240. # after a few back in history
  1241. to_truncate = truncate_lines
  1242. for l in lines:
  1243. if not l.startswith("#"):
  1244. if to_truncate > 0:
  1245. to_truncate -= 1
  1246. elif limit == 0 or counter < limit:
  1247. l_file.write(l)
  1248. counter += 1
  1249. l_file.close()
  1250. # remove an url from a list.
  1251. # return True if the URL was removed
  1252. # return False if the URL was not found
  1253. def list_rm_url(self,url,list):
  1254. return self.list_has_url(url,list,deletion=True)
  1255. def list_update_url_mode(self,url,list,mode):
  1256. return self.list_has_url(url,list,update_mode = mode)
  1257. # deletion and has_url are so similar, I made them the same method
  1258. # deletion : true or false if you want to delete the URL
  1259. # exact_mode : True if you want to check only for the exact url, not the canonical one
  1260. # update_mode : a new mode to update the URL
  1261. def list_has_url(self,url,list,deletion=False, exact_mode=False, update_mode = None):
  1262. list_path = self.list_path(list)
  1263. if list_path:
  1264. to_return = False
  1265. with open(list_path,"r") as lf:
  1266. lines = lf.readlines()
  1267. lf.close()
  1268. to_write = []
  1269. # let’s remove the mode
  1270. if not exact_mode:
  1271. url=unmode_url(url)[0]
  1272. for l in lines:
  1273. # we separate components of the line
  1274. # to ensure we identify a complete URL, not a part of it
  1275. splitted = l.split()
  1276. if url not in splitted and len(splitted) > 1:
  1277. current = unmode_url(splitted[1])[0]
  1278. #sometimes, we must remove the ending "/"
  1279. if url == current or (url.endswith("/") and url[:-1] == current):
  1280. to_return = True
  1281. if update_mode:
  1282. new_line = l.replace(current,mode_url(url,update_mode))
  1283. to_write.append(new_line)
  1284. elif not deletion:
  1285. to_write.append(l)
  1286. else:
  1287. to_write.append(l)
  1288. elif url in splitted:
  1289. to_return = True
  1290. # We update the mode if asked by replacing the old url
  1291. # by a moded one in the same line
  1292. if update_mode:
  1293. new_line = l.replace(url,mode_url(url,update_mode))
  1294. to_write.append(new_line)
  1295. elif not deletion:
  1296. to_write.append(l)
  1297. else:
  1298. to_write.append(l)
  1299. if deletion or update_mode:
  1300. with open(list_path,"w") as lf:
  1301. for l in to_write:
  1302. lf.write(l)
  1303. lf.close()
  1304. return to_return
  1305. else:
  1306. return False
  1307. def list_get_links(self,list):
  1308. list_path = self.list_path(list)
  1309. if list_path and os.path.exists(list_path):
  1310. return self.get_renderer("list:///%s"%list).get_links()
  1311. else:
  1312. return []
  1313. def list_go_to_line(self,line,list):
  1314. list_path = self.list_path(list)
  1315. if not list_path:
  1316. print("List %s does not exist. Create it with ""list create %s"""%(list,list))
  1317. elif not line.isnumeric():
  1318. print("go_to_line requires a number as parameter")
  1319. else:
  1320. r = self.get_renderer("list:///%s"%list)
  1321. url = r.get_link(int(line))
  1322. display = not self.sync_only
  1323. if url:
  1324. self._go_to_url(url,handle=display)
  1325. return url
  1326. def list_show(self,list):
  1327. list_path = self.list_path(list)
  1328. if not list_path:
  1329. print("List %s does not exist. Create it with ""list create %s"""%(list,list))
  1330. else:
  1331. url = "list:///%s"%list
  1332. display = not self.sync_only
  1333. self._go_to_url(url,handle=display)
  1334. #return the path of the list file if list exists.
  1335. #return None if the list doesn’t exist.
  1336. def list_path(self,list):
  1337. listdir = os.path.join(xdg("data"),"lists")
  1338. list_path = os.path.join(listdir, "%s.gmi"%list)
  1339. if os.path.exists(list_path):
  1340. return list_path
  1341. else:
  1342. return None
  1343. def list_create(self,list,title=None,quite=False):
  1344. list_path = self.list_path(list)
  1345. if list in ["create","edit","delete","help"]:
  1346. print("%s is not allowed as a name for a list"%list)
  1347. elif not list_path:
  1348. listdir = os.path.join(xdg("data"),"lists")
  1349. os.makedirs(listdir,exist_ok=True)
  1350. list_path = os.path.join(listdir, "%s.gmi"%list)
  1351. with open(list_path,"a") as lfile:
  1352. if title:
  1353. lfile.write("# %s\n"%title)
  1354. else:
  1355. lfile.write("# %s\n"%list)
  1356. lfile.close()
  1357. if not quite:
  1358. print("list created. Display with `list %s`"%list)
  1359. else:
  1360. print("list %s already exists" %list)
  1361. def do_move(self,arg):
  1362. """move LIST will add the current page to the list LIST.
  1363. With a major twist: current page will be removed from all other lists.
  1364. If current page was not in a list, this command is similar to `add LIST`."""
  1365. if not arg:
  1366. print("LIST argument is required as the target for your move")
  1367. elif arg[0] == "archives":
  1368. self.do_archive()
  1369. else:
  1370. args = arg.split()
  1371. list_path = self.list_path(args[0])
  1372. if not list_path:
  1373. print("%s is not a list, aborting the move" %args[0])
  1374. else:
  1375. lists = self.list_lists()
  1376. for l in lists:
  1377. if l != args[0] and l not in ["archives", "history"]:
  1378. url, mode = unmode_url(self.current_url)
  1379. isremoved = self.list_rm_url(url,l)
  1380. if isremoved:
  1381. print("Removed from %s"%l)
  1382. self.list_add_line(args[0])
  1383. def list_lists(self):
  1384. listdir = os.path.join(xdg("data"),"lists")
  1385. to_return = []
  1386. if os.path.exists(listdir):
  1387. lists = os.listdir(listdir)
  1388. if len(lists) > 0:
  1389. for l in lists:
  1390. #removing the .gmi at the end of the name
  1391. to_return.append(l[:-4])
  1392. return to_return
  1393. def list_has_status(self,list,status):
  1394. path = self.list_path(list)
  1395. toreturn = False
  1396. if path:
  1397. with open(path) as f:
  1398. line = f.readline().strip()
  1399. f.close()
  1400. if line.startswith("#") and status in line:
  1401. toreturn = True
  1402. return toreturn
  1403. def list_is_subscribed(self,list):
  1404. return self.list_has_status(list,"#subscribed")
  1405. def list_is_frozen(self,list):
  1406. return self.list_has_status(list,"#frozen")
  1407. def list_is_system(self,list):
  1408. return list in ["history","to_fetch","archives","tour"]
  1409. # This modify the status of a list to one of :
  1410. # normal, frozen, subscribed
  1411. # action is either #frozen, #subscribed or None
  1412. def list_modify(self,list,action=None):
  1413. path = self.list_path(list)
  1414. with open(path) as f:
  1415. lines = f.readlines()
  1416. f.close()
  1417. if lines[0].strip().startswith("#"):
  1418. first_line = lines.pop(0).strip("\n")
  1419. else:
  1420. first_line = "# %s "%list
  1421. first_line = first_line.replace("#subscribed","").replace("#frozen","")
  1422. if action:
  1423. first_line += " " + action
  1424. print("List %s has been marked as %s"%(list,action))
  1425. else:
  1426. print("List %s is now a normal list" %list)
  1427. first_line += "\n"
  1428. lines.insert(0,first_line)
  1429. with open(path,"w") as f:
  1430. for line in lines:
  1431. f.write(line)
  1432. f.close()
  1433. def do_list(self,arg):
  1434. """Manage list of bookmarked pages.
  1435. - list : display available lists
  1436. - list $LIST : display pages in $LIST
  1437. - list create $NEWLIST : create a new list
  1438. - list edit $LIST : edit the list
  1439. - list subscribe $LIST : during sync, add new links found in listed pages to tour
  1440. - list freeze $LIST : don’t update pages in list during sync if a cache already exists
  1441. - list normal $LIST : update pages in list during sync but don’t add anything to tour
  1442. - list delete $LIST : delete a list permanently (a confirmation is required)
  1443. - list help : print this help
  1444. See also :
  1445. - add $LIST (to add current page to $LIST or, by default, to bookmarks)
  1446. - move $LIST (to add current page to list while removing from all others)
  1447. - archive (to remove current page from all lists while adding to archives)
  1448. There’s no "delete" on purpose. The use of "archive" is recommended.
  1449. The following lists cannot be removed or frozen but can be edited with "list edit"
  1450. - list archives : contains last 200 archived URLs
  1451. - history : contains last 200 visisted URLs
  1452. - to_fetch : contains URLs that will be fetch during the next sync
  1453. - tour : contains the next URLs to visit during a tour (see "help tour")
  1454. """
  1455. listdir = os.path.join(xdg("data"),"lists")
  1456. os.makedirs(listdir,exist_ok=True)
  1457. if not arg:
  1458. lists = self.list_lists()
  1459. if len(lists) > 0:
  1460. lurl = "list:///"
  1461. self._go_to_url(lurl)
  1462. else:
  1463. print("No lists yet. Use `list create`")
  1464. else:
  1465. args = arg.split()
  1466. if args[0] == "create":
  1467. if len(args) > 2:
  1468. name = " ".join(args[2:])
  1469. self.list_create(args[1].lower(),title=name)
  1470. elif len(args) == 2:
  1471. self.list_create(args[1].lower())
  1472. else:
  1473. print("A name is required to create a new list. Use `list create NAME`")
  1474. elif args[0] == "edit":
  1475. editor = None
  1476. if "editor" in self.options and self.options["editor"]:
  1477. editor = self.options["editor"]
  1478. elif os.environ.get("VISUAL"):
  1479. editor = os.environ.get("VISUAL")
  1480. elif os.environ.get("EDITOR"):
  1481. editor = os.environ.get("EDITOR")
  1482. if editor:
  1483. if len(args) > 1 and args[1] in self.list_lists():
  1484. path = os.path.join(listdir,args[1]+".gmi")
  1485. try:
  1486. # Note that we intentionally don't quote the editor.
  1487. # In the unlikely case `editor` includes a percent
  1488. # sign, we also escape it for the %-formatting.
  1489. cmd = editor.replace("%", "%%") + " %s"
  1490. run(cmd, parameter=path, direct_output=True)
  1491. except Exception as err:
  1492. print(err)
  1493. print("Please set a valid editor with \"set editor\"")
  1494. else:
  1495. print("A valid list name is required to edit a list")
  1496. else:
  1497. print("No valid editor has been found.")
  1498. print("You can use the following command to set your favourite editor:")
  1499. print("set editor EDITOR")
  1500. print("or use the $VISUAL or $EDITOR environment variables.")
  1501. elif args[0] == "delete":
  1502. if len(args) > 1:
  1503. if self.list_is_system(args[1]):
  1504. print("%s is a system list which cannot be deleted"%args[1])
  1505. elif args[1] in self.list_lists():
  1506. size = len(self.list_get_links(args[1]))
  1507. stri = "Are you sure you want to delete %s ?\n"%args[1]
  1508. confirm = "YES"
  1509. if size > 0:
  1510. stri += "! %s items in the list will be lost !\n"%size
  1511. confirm = "YES DELETE %s" %size
  1512. else :
  1513. stri += "The list is empty, it should be safe to delete it.\n"
  1514. stri += "Type \"%s\" (in capital, without quotes) to confirm :"%confirm
  1515. answer = input(stri)
  1516. if answer == confirm:
  1517. path = os.path.join(listdir,args[1]+".gmi")
  1518. os.remove(path)
  1519. print("* * * %s has been deleted" %args[1])
  1520. else:
  1521. print("A valid list name is required to be deleted")
  1522. else:
  1523. print("A valid list name is required to be deleted")
  1524. elif args[0] in ["subscribe","freeze","normal"]:
  1525. if len(args) > 1:
  1526. if self.list_is_system(args[1]):
  1527. print("You cannot modify %s which is a system list"%args[1])
  1528. elif args[1] in self.list_lists():
  1529. if args[0] == "subscribe":
  1530. action = "#subscribed"
  1531. elif args[0] == "freeze":
  1532. action = "#frozen"
  1533. else:
  1534. action = None
  1535. self.list_modify(args[1],action=action)
  1536. else:
  1537. print("A valid list name is required after %s" %args[0])
  1538. elif args[0] == "help":
  1539. self.onecmd("help list")
  1540. elif len(args) == 1:
  1541. self.list_show(args[0].lower())
  1542. else:
  1543. self.list_go_to_line(args[1],args[0].lower())
  1544. def do_help(self, arg):
  1545. """ALARM! Recursion detected! ALARM! Prepare to eject!"""
  1546. if arg == "!":
  1547. print("! is an alias for 'shell'")
  1548. elif arg == "?":
  1549. print("? is an alias for 'help'")
  1550. elif arg in _ABBREVS:
  1551. full_cmd = _ABBREVS[arg]
  1552. print("%s is an alias for '%s'" %(arg,full_cmd))
  1553. print("See the list of aliases with 'abbrevs'")
  1554. print("'help %s':"%full_cmd)
  1555. cmd.Cmd.do_help(self, full_cmd)
  1556. else:
  1557. cmd.Cmd.do_help(self, arg)
  1558. def do_sync(self, line):
  1559. """Synchronize all bookmarks lists and URLs from the to_fetch list.
  1560. - New elements in pages in subscribed lists will be added to tour
  1561. - Elements in list to_fetch will be retrieved and added to tour
  1562. - Normal lists will be synchronized and updated
  1563. - Frozen lists will be fetched only if not present.
  1564. Before a sync, you can edit the list of URLs that will be fetched with the
  1565. following command: "list edit to_fetch"
  1566. Argument : duration of cache validity (in seconds)."""
  1567. if self.offline_only:
  1568. print("Sync can only be achieved online. Change status with `online`.")
  1569. return
  1570. args = line.split()
  1571. if len(args) > 0:
  1572. if not args[0].isdigit():
  1573. print("sync argument should be the cache validity expressed in seconds")
  1574. return
  1575. else:
  1576. validity = int(args[0])
  1577. else:
  1578. validity = 0
  1579. self.call_sync(refresh_time=validity)
  1580. def call_sync(self,refresh_time=0,depth=1,lists=None):
  1581. # fetch_url is the core of the sync algorithm.
  1582. # It takes as input :
  1583. # - an URL to be fetched
  1584. # - depth : the degree of recursion to build the cache (0 means no recursion)
  1585. # - validity : the age, in seconds, existing caches need to have before
  1586. # being refreshed (0 = never refreshed if it already exists)
  1587. # - savetotour : if True, newly cached items are added to tour
  1588. def add_to_tour(url):
  1589. if url and netcache.is_cache_valid(url):
  1590. toprint = " -> adding to tour: %s" %url
  1591. width = term_width() - 1
  1592. toprint = toprint[:width]
  1593. toprint += " "*(width-len(toprint))
  1594. print(toprint)
  1595. self.list_add_line("tour",url=url,verbose=False)
  1596. return True
  1597. else:
  1598. return False
  1599. def fetch_url(url,depth=0,validity=0,savetotour=False,count=[0,0],strin=""):
  1600. #savetotour = True will save to tour newly cached content
  1601. # else, do not save to tour
  1602. #regardless of valitidy
  1603. if not url: return
  1604. if not netcache.is_cache_valid(url,validity=validity):
  1605. if strin != "":
  1606. endline = '\r'
  1607. else:
  1608. endline = None
  1609. #Did we already had a cache (even an old one) ?
  1610. isnew = not netcache.is_cache_valid(url)
  1611. toprint = "%s [%s/%s] Fetch "%(strin,count[0],count[1]) + url
  1612. width = term_width() - 1
  1613. toprint = toprint[:width]
  1614. toprint += " "*(width-len(toprint))
  1615. print(toprint,end=endline)
  1616. #If not saving to tour, then we should limit download size
  1617. limit = not savetotour
  1618. self._go_to_url(url,update_hist=False,limit_size=limit)
  1619. if savetotour and isnew and netcache.is_cache_valid(url):
  1620. #we add to the next tour only if we managed to cache
  1621. #the ressource
  1622. add_to_tour(url)
  1623. #Now, recursive call, even if we didn’t refresh the cache
  1624. # This recursive call is impacting performances a lot but is needed
  1625. # For the case when you add a address to a list to read later
  1626. # You then expect the links to be loaded during next refresh, even
  1627. # if the link itself is fresh enough
  1628. # see fetch_list()
  1629. if depth > 0:
  1630. #we should only savetotour at the first level of recursion
  1631. # The code for this was removed so, currently, we savetotour
  1632. # at every level of recursion.
  1633. r = self.get_renderer(url)
  1634. url,oldmode = unmode_url(url)
  1635. if oldmode == "full":
  1636. mode = "full_links_only"
  1637. else:
  1638. mode = "links_only"
  1639. if r:
  1640. links = r.get_links(mode=mode)
  1641. subcount = [0,len(links)]
  1642. d = depth - 1
  1643. for k in links:
  1644. #recursive call (validity is always 0 in recursion)
  1645. substri = strin + " -->"
  1646. subcount[0] += 1
  1647. fetch_url(k,depth=d,validity=0,savetotour=savetotour,\
  1648. count=subcount,strin=substri)
  1649. def fetch_list(list,validity=0,depth=1,tourandremove=False,tourchildren=False):
  1650. links = self.list_get_links(list)
  1651. end = len(links)
  1652. counter = 0
  1653. print(" * * * %s to fetch in %s * * *" %(end,list))
  1654. for l in links:
  1655. counter += 1
  1656. # If cache for a link is newer than the list
  1657. fetch_url(l,depth=depth,validity=validity,savetotour=tourchildren,count=[counter,end])
  1658. if tourandremove:
  1659. if add_to_tour(l):
  1660. self.list_rm_url(l,list)
  1661. self.sync_only = True
  1662. if not lists:
  1663. lists = self.list_lists()
  1664. # We will fetch all the lists except "archives" and "history"
  1665. # We keep tour for the last round
  1666. subscriptions = []
  1667. normal_lists = []
  1668. fridge = []
  1669. for l in lists:
  1670. #only try existing lists
  1671. if l in self.list_lists():
  1672. if not self.list_is_system(l):
  1673. if self.list_is_frozen(l):
  1674. fridge.append(l)
  1675. elif self.list_is_subscribed(l):
  1676. subscriptions.append(l)
  1677. else:
  1678. normal_lists.append(l)
  1679. # We start with the "subscribed" as we need to find new items
  1680. starttime = int(time.time())
  1681. for l in subscriptions:
  1682. fetch_list(l,validity=refresh_time,depth=depth,tourchildren=True)
  1683. #Then the fetch list (item are removed from the list after fetch)
  1684. # We fetch regarless of the refresh_time
  1685. if "to_fetch" in lists:
  1686. nowtime = int(time.time())
  1687. short_valid = nowtime - starttime
  1688. fetch_list("to_fetch",validity=short_valid,depth=depth,tourandremove=True)
  1689. #then we fetch all the rest (including bookmarks and tour)
  1690. for l in normal_lists:
  1691. fetch_list(l,validity=refresh_time,depth=depth)
  1692. for l in fridge:
  1693. fetch_list(l,validity=0,depth=depth)
  1694. #tour should be the last one as item my be added to it by others
  1695. fetch_list("tour",validity=refresh_time,depth=depth)
  1696. print("End of sync")
  1697. self.sync_only = False
  1698. ### The end!
  1699. def do_quit(self, *args):
  1700. """Exit Offpunk."""
  1701. self.opencache.cleanup()
  1702. print("You can close your screen!")
  1703. sys.exit()
  1704. do_exit = do_quit
  1705. # Main function
  1706. def main():
  1707. # Parse args
  1708. parser = argparse.ArgumentParser(description=__doc__)
  1709. parser.add_argument('--bookmarks', action='store_true',
  1710. help='start with your list of bookmarks')
  1711. parser.add_argument('--config-file',metavar='FILE',
  1712. help='use this particular config file instead of default')
  1713. parser.add_argument('--sync', action='store_true',
  1714. help='run non-interactively to build cache by exploring lists passed \
  1715. as argument. Without argument, all lists are fetched.')
  1716. parser.add_argument('--assume-yes', action='store_true',
  1717. help='assume-yes when asked questions about certificates/redirections during sync (lower security)')
  1718. parser.add_argument('--disable-http',action='store_true',
  1719. help='do not try to get http(s) links (but already cached will be displayed)')
  1720. parser.add_argument('--fetch-later', action='store_true',
  1721. help='run non-interactively with an URL as argument to fetch it later')
  1722. parser.add_argument('--depth',
  1723. help='depth of the cache to build. Default is 1. More is crazy. Use at your own risks!')
  1724. parser.add_argument('--images-mode',
  1725. help='the mode to use to choose which images to download in a HTML page.\
  1726. one of (None, readable, full). Warning: full will slowdown your sync.')
  1727. parser.add_argument('--cache-validity',
  1728. help='duration for which a cache is valid before sync (seconds)')
  1729. parser.add_argument('--version', action='store_true',
  1730. help='display version information and quit')
  1731. parser.add_argument('--features', action='store_true',
  1732. help='display available features and dependancies then quit')
  1733. parser.add_argument('url', metavar='URL', nargs='*',
  1734. help='Arguments should be URL to be fetched or, if --sync is used, lists')
  1735. args = parser.parse_args()
  1736. # Handle --version
  1737. if args.version:
  1738. print("Offpunk " + __version__)
  1739. sys.exit()
  1740. elif args.features:
  1741. GeminiClient.do_version(None,None)
  1742. sys.exit()
  1743. else:
  1744. for f in [xdg("config"), xdg("data")]:
  1745. if not os.path.exists(f):
  1746. print("Creating config directory {}".format(f))
  1747. os.makedirs(f)
  1748. # Instantiate client
  1749. gc = GeminiClient(synconly=args.sync)
  1750. torun_queue = []
  1751. # Interactive if offpunk started normally
  1752. # False if started with --sync
  1753. # Queue is a list of command (potentially empty)
  1754. def read_config(queue,rcfile=None,interactive=True):
  1755. if not rcfile:
  1756. rcfile = os.path.join(xdg("config"), "offpunkrc")
  1757. if os.path.exists(rcfile):
  1758. print("Using config %s" % rcfile)
  1759. with open(rcfile, "r") as fp:
  1760. for line in fp:
  1761. line = line.strip()
  1762. if ((args.bookmarks or args.url) and
  1763. any((line.startswith(x) for x in ("go", "g", "tour", "t")))
  1764. ):
  1765. if args.bookmarks:
  1766. print("Skipping rc command \"%s\" due to --bookmarks option." % line)
  1767. else:
  1768. print("Skipping rc command \"%s\" due to provided URLs." % line)
  1769. continue
  1770. # We always consider redirect
  1771. # for the rest, we need to be interactive
  1772. if line.startswith("redirect") or interactive:
  1773. queue.append(line)
  1774. return queue
  1775. # Act on args
  1776. if args.bookmarks:
  1777. torun_queue.append("bookmarks")
  1778. elif args.url and not args.sync:
  1779. if len(args.url) == 1:
  1780. torun_queue.append("go %s" % args.url[0])
  1781. else:
  1782. for url in args.url:
  1783. torun_queue.append("tour %s" % url)
  1784. torun_queue.append("tour")
  1785. if args.disable_http:
  1786. gc.support_http = False
  1787. # Endless interpret loop (except while --sync or --fetch-later)
  1788. if args.fetch_later:
  1789. if args.url:
  1790. gc.sync_only = True
  1791. for u in args.url:
  1792. if looks_like_url(u):
  1793. if netcache.is_cache_valid(u):
  1794. gc.list_add_line("tour",u)
  1795. else:
  1796. gc.list_add_line("to_fetch",u)
  1797. else:
  1798. print("%s is not a valid URL to fetch"%u)
  1799. else:
  1800. print("--fetch-later requires an URL (or a list of URLS) as argument")
  1801. elif args.sync:
  1802. if args.assume_yes:
  1803. gc.automatic_choice = "y"
  1804. gc.onecmd("set accept_bad_ssl_certificates True")
  1805. if args.cache_validity:
  1806. refresh_time = int(args.cache_validity)
  1807. else:
  1808. # if no refresh time, a default of 0 is used (which means "infinite")
  1809. refresh_time = 0
  1810. if args.images_mode and args.images_mode in ["none","readable","normal","full"]:
  1811. gc.options["images_mode"] = args.images_mode
  1812. if args.depth:
  1813. depth = int(args.depth)
  1814. else:
  1815. depth = 1
  1816. read_config(torun_queue,rcfile=args.config_file,interactive=False)
  1817. for line in torun_queue:
  1818. gc.onecmd(line)
  1819. lists = None
  1820. gc.call_sync(refresh_time=refresh_time,depth=depth,lists=args.url)
  1821. else:
  1822. # We are in the normal mode. First process config file
  1823. torun_queue = read_config(torun_queue,rcfile=args.config_file,interactive=True)
  1824. print("Welcome to Offpunk!")
  1825. print("Type `help` to get the list of available command.")
  1826. for line in torun_queue:
  1827. gc.onecmd(line)
  1828. while True:
  1829. try:
  1830. gc.cmdloop()
  1831. except KeyboardInterrupt:
  1832. print("")
  1833. if __name__ == '__main__':
  1834. main()