offpunk.py 78 KB

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