New fortune system

This commit is contained in:
Kujiu 2018-10-12 16:17:17 +02:00
parent d11d8fdc2b
commit e4e70aef67
No known key found for this signature in database
GPG key ID: F6A8243BF7C8404D
6 changed files with 899 additions and 1 deletions

61
common/.local/bin/json-fortune Executable file
View file

@ -0,0 +1,61 @@
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
"""
Get a fortune from a JSON file.
File is under EUPL1.2
Author: kujiu
"""
import json
import argparse
import logging
import sys
import os.path
import random
logger = logging.getLogger(__name__)
ch = logging.StreamHandler(sys.stderr)
ch.setLevel(logging.WARNING)
logger.addHandler(ch)
def get_quote(srcfile):
"""
Get a quote
"""
with open(srcfile) as fin:
quotes = json.load(fin)
quote = ""
count = 0
while not quote and count < 50:
count += 1
lang = random.choice([lang for lang in quotes.keys()])
category = random.choice([cat for cat in quotes[lang].keys()])
if not quotes[lang][category]:
continue
author = random.choice(
[author for author in quotes[lang][category].keys()])
if not quotes[lang][category][author]:
continue
quote = random.choice(quotes[lang][category][author])
if quote:
quote += "\n-- %s" % author
return quote
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Get a quote from JSON file.")
parser.add_argument(
'--source', default='~/.fortunes.json',
help='JSON file with quotes')
options = parser.parse_args()
source = os.path.expanduser(
os.path.expandvars(options.source)
)
print(get_quote(source))

101
common/.local/bin/update-quotes Executable file
View file

@ -0,0 +1,101 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Create a JSON file containing quotes.
File is under EUPL1.2
Author: kujiu
"""
import json
import argparse
import logging
import sys
import os.path
import wikiquote
logger = logging.getLogger(__name__)
ch = logging.StreamHandler(sys.stderr)
ch.setLevel(logging.WARNING)
logger.addHandler(ch)
def generate_quotes(srcfile):
"""
Generate a dict with all quotes
"""
quotes = {}
with open(srcfile) as fin:
sources_dict = json.load(fin)
for lang in sources_dict:
quotes.setdefault(lang, {})
for category in sources_dict[lang]:
quotes[lang].setdefault(category, {})
for author in sources_dict[lang][category]:
try:
quotes[lang][category][author] = wikiquote.quotes(
author, lang=lang
)
except Exception:
logger.exception(
"Error when retrieving %s from %s/%s",
author, lang, category)
continue
if not quotes[lang][category][author]:
logger.warning(
"Source %s from %s/%s has no quote.",
author, lang, category
)
else:
logger.debug(
"Source %s from %s/%s: %d quotes.",
author, lang, category,
len(quotes[lang][category][author])
)
return quotes
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="""
Generate a JSON file containing quotes from wikiquote.\n
\n
Source file must be a JSON in this format:\n
{\n
'en': {'fantasy': ['Discworld', 'Terry Pratchett']},\n
'fr': {'fantasy': ['Kaamelott/Arthur'], 'category2': ['Name']}\n
}\n
""")
parser.add_argument(
'--source', default='~/.wikiquote-sources.json',
help='JSON file with sources')
parser.add_argument(
'--dest', default='~/.fortunes.json',
help='Destination file')
parser.add_argument(
'-d', '--debug', action='store_true', help="Debug mode")
parser.add_argument(
'-v', '--verbose', help="Verbose mode", action='store_true')
options = parser.parse_args()
if hasattr(options, 'debug') and options.debug:
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.DEBUG)
logger.addHandler(ch)
if hasattr(options, 'verbose') and options.verbose:
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.INFO)
logger.addHandler(ch)
source = os.path.expanduser(
os.path.expandvars(options.source)
)
dest = os.path.expanduser(
os.path.expandvars(options.dest)
)
with open(dest, 'w') as fout:
json.dump(generate_quotes(source), fout, indent=4)

View file

@ -0,0 +1,566 @@
{
"fr": {
"harry potter": [
"J. K. Rowling",
"Harry Potter",
"Harry Potter (films)",
"Harry Potter et le Prince de sang-mêlé"
],
"star_trek": [
"Star Trek",
"Star Trek (série télévisée)",
"Star Trek, le film",
"Star Trek 2 : La Colère de Khan",
"Star Trek 3 : À la recherche de Spock",
"Star Trek 4 : Retour sur Terre",
"Star Trek 5 : L'Ultime Frontière",
"Star Trek 6 : Terre inconnue",
"Star Trek : Générations",
"Star Trek : Premier Contact",
"Star Trek (film, 2009)",
"Star Trek : Deep Space Nine",
"Star Trek : La Nouvelle Génération",
"Star Trek : Voyager"
],
"starwars": [
"Star Wars",
"Star Wars : The Clone Wars (série, 2008)",
"Star Wars, épisode I : La Menace fantôme (film)",
"Star Wars, épisode II : L'Attaque des clones (film)",
"Star Wars, épisode III : La Revanche des Sith (film)",
"Star Wars, épisode IV : Un nouvel espoir (film)",
"Star Wars, épisode V : L'Empire contre-attaque (film)",
"Star Wars, épisode VI : Le Retour du Jedi (film)",
"Star Wars, épisode VI : Le Retour du Jedi (livre)"
],
"kaamelott": [
"Kaamelott",
"Kaamelott/Bandes dessinées",
"Kaamelott/Dialogues",
"Kaamelott/Dialogues/Absurdités de la vie quotidienne",
"Kaamelott/Arthur",
"Kaamelott/Père Blaise",
"Kaamelott/Bohort",
"Kaamelott/Le roi burgonde",
"Kaamelott/Caius Camillus",
"Kaamelott/Demetra",
"Kaamelott/Élias de Kelliwich",
"Kaamelott/Gauvain",
"Kaamelott/Guenièvre",
"Kaamelott/Guethenoc",
"Kaamelott/Le Seigneur Jacca",
"Kaamelott/Kadoc",
"Kaamelott/Karadoc",
"Kaamelott/Lancelot",
"Kaamelott/Léodagan",
"Kaamelott/Loth",
"Kaamelott/Le maître darmes",
"Kaamelott/Méléagant",
"Kaamelott/Merlin",
"Kaamelott/Perceval",
"Kaamelott/Le Répurgateur",
"Kaamelott/Roparzh",
"Kaamelott/Séli",
"Kaamelott/Le tavernier",
"Kaamelott/Urgan",
"Kaamelott/Venec",
"Kaamelott/Yvain"
],
"fantasy": [
"Dan Simmons",
"La Roue du Temps",
"Stardust",
"Neil Gaiman",
"Pirates des Caraïbes",
"Robin Cook",
"Adolfo Bioy Casares",
"Terry Goodkind",
"Hero Corp",
"Reflets d'Acide",
"Terry Pratchett",
"H. P. Lovecraft"
],
"science-fiction": [
"Short Circuit",
"George Orwell",
"Philip K. Dick",
"Jurassic Park (film)",
"L'Échiquier du mal",
"Robert Silverberg",
"Starship Troopers (film)",
"Ghost in the Shell",
"Hypérion",
"La Chute d'Hypérion",
"Jules Verne",
"1984",
"Retour vers le futur",
"Douglas Adams"
],
"dune": [
"Frank Herbert",
"Dune (film)",
"Dune",
"Le Messie de Dune",
"Les Enfants de Dune",
"L'Empereur-Dieu de Dune",
"Les Hérétiques de Dune",
"La Maison des mères"
],
"disney": [
"Rox et Rouky",
"Mulan",
"La Belle et le Clochard",
"Blanche-Neige et les Sept Nains",
"Kuzco, l'empereur mégalo",
"Robin des Bois (film, 1973)",
"Hercule (film, 1997)",
"Atlantide, l'empire perdu"
],
"lord_of_the_rings": [
"John Ronald Reuel Tolkien",
"Le Hobbit",
"Le Seigneur des anneaux",
"Le Seigneur des anneaux : Le Retour du roi",
"Le Seigneur des anneaux : Les Deux Tours",
"Le Seigneur des anneaux : La Communauté de l'anneau"
],
"isaac_asimov": [
"Isaac Asimov",
"Les Robots",
"Les Cavernes d'acier",
"Face aux feux du soleil",
"Les Robots de l'aube",
"Les Robots et l'Empire",
"Tyrann",
"Poussière d'étoiles",
"Les Courants de l'espace",
"Cailloux dans le ciel",
"Fondation (livre)",
"Fondation et Empire",
"Seconde Fondation",
"Fondation foudroyée",
"Terre et Fondation",
"Trantor"
],
"stephen_king": [
"Stephen King",
"Sac d'os",
"Histoire de Lisey",
"Écriture : Mémoires d'un métier",
"Le Fléau",
"Cœurs perdus en Atlantide",
"Différentes Saisons",
"La Tour sombre"
],
"detective": [
"Détective Conan",
"La Cité de la peur",
"Le Pacte des loups",
"Gaston Leroux",
"Le Mystère de la chambre jaune (film)",
"Qui veut la peau de Roger Rabbit",
"Le téléphone sonne toujours deux fois !!",
"Le Nom de la rose (film)",
"Fred Vargas",
"Agatha Christie"
],
"ghibli": [
"Le Voyage de Chihiro",
"Princesse Mononoké",
"Porco Rosso"
],
"adventure": [
"Saiyuki - Chronique de l'Extrême Voyage",
"Prince of Persia : Les Sables du temps",
"Astérix",
"Les Aventures de Tintin",
"Indiana Jones et la Dernière Croisade",
"Corto Maltese",
"Gladiator",
"Jack London"
],
"science": [
"Isaac Newton",
"Albert Einstein"
],
"theater": [
"Molière"
],
"other": [
"Grand Corps Malade",
"Émile Zola",
"Amélie Nothomb",
"Coluche"
]
},
"en": {
"harry_potter": [
"Harry Potter and the Chamber of Secrets",
"Harry Potter and the Sorcerer's Stone",
"Harry Potter and the Prisoner of Azkaban",
"Harry Potter and the Goblet of Fire",
"Harry Potter and the Order of the Phoenix",
"Harry Potter and the Half-Blood Prince",
"Harry Potter and the Deathly Hallows",
"Harry Potter and the Philosopher's Stone (film)",
"Harry Potter and the Prisoner of Azkaban (film)",
"Harry Potter and the Half-Blood Prince (film)",
"Harry Potter and the Philosopher's Stone (film)",
"Harry Potter and the Chamber of Secrets (film)",
"Harry Potter and the Goblet of Fire (film)",
"Harry Potter and the Deathly Hallows Part 1",
"Harry Potter and the Deathly Hallows Part 2",
"Albus Dumbledore",
"J. K. Rowling"
],
"starwars": [
"Star Wars",
"The Empire Strikes Back",
"Return of the Jedi",
"Rogue One",
"Star Wars (film)",
"Star Wars: Battlefront",
"Star Wars: Episode I The Phantom Menace",
"Star Wars: Episode II Attack of the Clones",
"Star Wars: Episode III Revenge of the Sith",
"Star Wars: The Clone Wars (film)",
"Star Wars: The Force Awakens",
"Star Wars: The Last Jedi",
"Star Wars Rebels"
],
"star_trek": [
"Star Trek",
"Star Trek: Discovery",
"Jean-Luc Picard",
"Klingon proverbs",
"Star Trek (film)",
"Star Trek Beyond",
"Star Trek Into Darkness",
"Star Trek: The Motion Picture",
"Star Trek II: The Wrath of Khan",
"Star Trek IV: The Voyage Home",
"Star Trek V: The Final Frontier",
"Star Trek VI: The Undiscovered Country",
"Star Trek Generations",
"Star Trek: First Contact",
"Star Trek: Insurrection",
"Star Trek: Nemesis",
"Star Trek III: The Search for Spock",
"Star Trek: Borg",
"Star Trek: Deep Space Nine",
"Star Trek: Enterprise",
"Star Trek: Klingon Academy",
"Star Trek: Phase II (fan series)",
"Star Trek: The Animated Series",
"Star Trek: The Next Generation",
"Star Trek: The Original Series",
"Star Trek: Voyager",
"Vulcan proverbs"
],
"fantasy": [
"The Chronicles of Narnia",
"The Chronicles of Narnia: The Lion, the Witch and the Wardrobe",
"The Chronicles of Narnia: Prince Caspian",
"The Chronicles of Narnia: The Voyage of the Dawn Treader",
"The Chronicles of Narnia: Prince Caspian",
"Ursula K. Le Guin",
"Alice's Adventures in Wonderland",
"Hook (film)",
"Alice in Wonderland (2010 film)",
"How to Train Your Dragon (film)",
"How to Train Your Dragon 2",
"Neil Gaiman",
"Lewis Carroll",
"Charles Dickens",
"A Christmas Carol",
"C. S. Lewis",
"H. P. Lovecraft",
"Terry Pratchett",
"Discworld",
"Good Omens",
"Terry Pratchett's Hogfather"
],
"science-fiction":[
"Back to the Future",
"Back to the Future Part II",
"Back to the Future Part III",
"Ray Bradbury",
"Idiocracy",
"WarGames",
"Starship Troopers",
"Starship Troopers (film)",
"Blade Runner",
"Frank Herbert",
"Dune",
"Dune (film)",
"Guardians of the Galaxy Vol. 2",
"Guardians of the Galaxy (film)",
"Jules Verne",
"George Orwell",
"Battlestar Galactica (2003)",
"Nineteen Eighty-Four",
"Fahrenheit 451",
"Douglas Adams",
"The Hitchhiker's Guide to the Galaxy (film)",
"The Hitchhiker's Guide to the Galaxy",
"Isaac Asimov",
"The IT Crowd",
"Philip K. Dick",
"The Dark Tower (series)",
"Stephen King"
],
"disney": [
"The Lion King",
"The Fox and the Hound",
"Fantasia (1940 film)",
"Daffy Duck",
"Sleeping Beauty (1959 film)",
"Walt Disney cartoon characters",
"Snow White and the Seven Dwarfs (1937 film)",
"Robin Hood (1973 film)",
"Wreck-It Ralph",
"One Hundred and One Dalmatians",
"The Black Cauldron (film)",
"The Land Before Time",
"Dumbo",
"Cinderella (1950 film)",
"Aladdin (1992 Disney film)",
"The Nightmare Before Christmas",
"Hercules (1997 film)",
"The Secret of NIMH",
"Up (2009 film)",
"Brave (2012 film)",
"Peter Pan",
"Lady and the Tramp",
"Mary Poppins (film)",
"Beauty and the Beast (1991 film)",
"Alice in Wonderland (1951 film)",
"The Jungle Book (1967 film)",
"Coco (2017 film)",
"Pinocchio (1940 film)",
"Frozen (2013 film)",
"Atlantis: The Lost Empire",
"The Hunchback of Notre Dame (1996 film)",
"Big Hero 6 (film)",
"Treasure Planet"
],
"manga": [
"Neon Genesis Evangelion",
"Gurren Lagann",
"Ghost in the Shell (film)",
"Ghost in the Shell 2: Innocence",
"Ghost in the Shell: Stand Alone Complex",
"Fairy Tail",
"Reborn!",
"Trigun",
"Azumanga Daioh",
"Sonic the Hedgehog (TV series)",
"Hikaru no Go",
"Death Note",
"Death Note (manga)",
"Fullmetal Alchemist (manga)",
"Fullmetal Alchemist: Brotherhood (anime)",
"Fullmetal Alchemist (anime)",
"InuYasha",
"Cowboy Bebop",
"Cowboy Bebop: The Movie",
"Great Teacher Onizuka",
"×××HOLiC",
"Vampire Knight",
"Tsubasa: Reservoir Chronicle",
"Pandora Hearts",
"One Piece",
"Noir",
"Excel Saga",
"Elfen Lied",
"Durarara!!",
"Devil May Cry: The Animated Series",
"Devil May Cry",
"Detective Conan",
"Black Butler",
"Buso Renkin",
"Berserk (anime)",
"Akira (film)",
"Wolf's Rain",
"Megatokyo",
"InuYasha",
"Ergo Proxy",
"Naruto the Movie: Ninja Clash in the Land of Snow",
"Naruto",
"Naruto: Shippūden",
"Ranma ½",
"Air Gear",
"Paranoia Agent",
"Avatar: The Last Airbender (season 2)",
"Avatar: The Last Airbender (season 1)",
"Avatar: The Last Airbender (season 3)"
],
"gundam": [
"Mobile Suit Gundam 00",
"Mobile Suit Gundam",
"Mobile Suit Gundam 0083: Stardust Memory",
"Mobile Suit Zeta Gundam",
"Mobile Suit Gundam: Char's Counterattack",
"Gundam Wing",
"Mobile Fighter G Gundam",
"Gundam Seed",
"Gundam 00"
],
"final_fantasy": [
"Auron",
"Final Fantasy VII: Crisis Core",
"Dissidia: Final Fantasy",
"Final Fantasy (video game)",
"Final Fantasy",
"Final Fantasy II",
"Final Fantasy III",
"Final Fantasy IV",
"Final Fantasy V",
"Final Fantasy VI",
"Final Fantasy VII",
"Final Fantasy VII: Advent Children",
"Final Fantasy VII Dirge of Cerberus",
"Final Fantasy VIII",
"Final Fantasy IX",
"Final Fantasy X",
"Final Fantasy X-2",
"Final Fantasy XI",
"Final Fantasy XII",
"Final Fantasy XIII",
"Final Fantasy XIV",
"Final Fantasy Crystal Chronicles",
"Final Fantasy Tactics",
"Final Fantasy Tactics Advance",
"Final Fantasy Tactics: The War of the Lions",
"Final Fantasy Unlimited",
"Final Fantasy: The Spirits Within",
"Last words in Final Fantasy"
],
"kingdom_hearts": [
"Kingdom Hearts",
"Kingdom Hearts (series)",
"Kingdom Hearts 3D: Dream Drop Distance",
"Kingdom Hearts Birth by Sleep",
"Kingdom Hearts coded",
"Kingdom Hearts II",
"Kingdom Hearts: 358/2 Days",
"Kingdom Hearts: Chain of Memories"
],
"ghibli": [
"Your Name",
"Porco Rosso",
"Spirited Away",
"Howl's Moving Castle",
"Nausicaä of the Valley of the Wind",
"Kiki's Delivery Service",
"Princess Mononoke"
],
"detective": [
"Who Framed Roger Rabbit",
"Arthur Conan Doyle",
"The Da Vinci Code",
"The Da Vinci Code (film)",
"Sherlock Holmes",
"Agatha Christie",
"Agatha Christie's Poirot"
],
"adventure": [
"E.T. the Extra-Terrestrial",
"Indiana Jones and the Temple of Doom",
"Indiana Jones and the Last Crusade",
"Raiders of the Lost Ark",
"Indiana Jones and the Kingdom of the Crystal Skull",
"The Young Indiana Jones Chronicles",
"Pirates of the Caribbean: The Curse of the Black Pearl",
"Pirates of the Caribbean: Dead Man's Chest",
"Pirates of the Caribbean: At World's End",
"Pirates of the Caribbean: On Stranger Tides",
"Pirates of the Caribbean: Dead Men Tell No Tales",
"Willow (film)",
"Stardust (novel)",
"Stardust (2007 film)",
"Prince of Persia",
"Reservoir Dogs",
"The Adventures of Tintin (film)",
"Prince of Persia: Warrior Within",
"The Rock (film)",
"Twister",
"Gladiator (2000 film)",
"Jack London",
"Jurassic Park (film)",
"Oliver Twist"
],
"games_of_throne": [
"George R. R. Martin",
"A Song of Ice and Fire",
"Game of Thrones/Season 7",
"Game of Thrones/Season 6",
"Game of Thrones/Season 5",
"Game of Thrones/Season 4",
"Game of Thrones/Season 3",
"Game of Thrones/Season 2",
"Game of Thrones/Season 1"
],
"games": [
"Go (game)",
"Grim Fandango",
"The Dig",
"Day of the Tentacle",
"Indiana Jones and the Fate of Atlantis",
"Return to Zork",
"Zork",
"Zork Grand Inquisitor",
"The Legend of Spyro: A New Beginning",
"The Elder Scrolls V: Skyrim",
"Rayman",
"Ōkami",
"NetHack",
"Ecco the Dolphin",
"Earthworm Jim",
"Chrono Trigger",
"Chrono Cross",
"Bubsy",
"The Legend of Zelda (TV series)",
"The Legend of Zelda: A Link to the Past",
"The Legend of Zelda: Majora's Mask",
"The Legend of Zelda: Ocarina of Time",
"The Legend of Zelda: Oracle of Ages and Oracle of Seasons",
"The Legend of Zelda: The Wind Waker",
"The Legend of Zelda: Twilight Princess",
"Link: The Faces of Evil",
"Zelda: The Wand of Gamelon",
"Dragon Quest IX",
"Fate/Stay Night",
"Spyro: Year of the Dragon",
"Spyro the Dragon",
"Elder Scrolls IV: Oblivion",
"Monkey Island",
"Xenoblade Chronicles",
"Heavy Rain",
"Tales of Symphonia",
"Adventures of Sonic the Hedgehog",
"Sonic the Hedgehog",
"Sonic Adventure",
"Fictional last words in video games",
"Eternal Sonata"
],
"lord_of_the_rings": [
"J. R. R. Tolkien",
"The Hobbit",
"The Hobbit: An Unexpected Journey",
"The Hobbit: The Desolation of Smaug",
"The Hobbit: The Battle of the Five Armies",
"The Lord of the Rings",
"The Two Towers",
"The Fellowship of the Ring",
"The Return of the King",
"Appendices to The Lord of the Rings",
"The Lord of the Rings: The Return of the King",
"The Lord of the Rings: The Fellowship of the Ring"
],
"science": [
"Isaac Newton",
"Albert Einstein"
]
}
}

View file

@ -153,4 +153,4 @@ alias pa-create-loopback='pactl load-module module-loopback sink=$1'
alias meteo=wego
alias f='fortune 30% discworld 30% hitchhiker 10% vimtips 30% fr/kaamelott'
f
json-fortune

View file

@ -0,0 +1,94 @@
#!/usr/bin/python
from variety.plugins.IQuoteSource import IQuoteSource
import subprocess, re
import random
from locale import gettext as _
SOURCES = [
*(('hitchhiker',)*3),
*(('vimtips',)*1),
*(('fr/kaamelott',)*3),
*(('discworld',)*4),
]
class FortuneSource(IQuoteSource):
@classmethod
def get_info(cls):
return {
"name": "Fortunes",
"description": _("Displays quotes using the UNIX fortune program"),
"author": "Dan Jones",
"version": "0.1"
}
def supports_search(self):
return False
def get_random(self):
source = random.choice(SOURCES)
fortune = subprocess.check_output(['fortune', source])
fortune = fortune.decode().split('\n')
if not fortune[-1]:
del fortune[-1]
if source == 'discworld':
author = 'Terry Pratchett'
sourceName = 'Disc World'
elif source == 'hitchhiker':
sourceName = 'Hitch Hicker\'s Guide to the Galaxy'
author = 'Douglas Adams'
elif source == 'fr/kaamelott':
author = 'Alexandre Astier'
sourceName = 'Kaamelott'
else:
sourceName = 'Vim Tips'
author = None
r = {
"quote": '\n'.join(fortune),
"author": author,
"sourceName": sourceName,
"link": None
}
return [r]
def get_for_author(self, author):
return []
def get_for_keyword(self, keyword):
return []
### Read Me
#
# First be sure that fortune is installed and in your PATH
# Copy this file to ~/.config/variety/plugins/quotes
# Restart variety
#
###
#
# Gist: https://gist.github.com/goodevilgenius/3878ce0f3e232e3daf5c
#
### BEGIN LICENSE
# Copyright (c) 2014 Dan Jones
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
### END LICENSE

View file

@ -0,0 +1,76 @@
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
"""
Get a fortune from a JSON file.
File is under EUPL1.2
Author: kujiu
"""
import os
import json
import random
from locale import gettext as _
from variety.plugins.IQuoteSource import IQuoteSource
SRCFILE = "~/.fortunes.json"
class JsonFortuneSource(IQuoteSource):
""" Get quote from JSON fortune file """
quotes = {}
@classmethod
def get_info(cls):
return {
"name": "JSON Fortunes",
"description": _("Displays quotes using a JSON file"),
"author": "kujiu",
"version": "0.1"
}
def supports_search(self):
return False
def load_srcfile(self):
"""
Load quote from file
"""
if self.quotes:
return
srcfile = os.path.expanduser(
os.path.expandvars(SRCFILE)
)
with open(srcfile) as fin:
self.quotes = json.load(fin)
def get_random(self):
self.load_srcfile()
quote = ""
count = 0
while not quote and count < 50:
count += 1
lang = random.choice([lang for lang in self.quotes.keys()])
category = random.choice([cat for cat in self.quotes[lang].keys()])
if not self.quotes[lang][category]:
continue
author = random.choice(
[author for author in self.quotes[lang][category].keys()])
if not self.quotes[lang][category][author]:
continue
quote = random.choice(self.quotes[lang][category][author])
return [{
"quote": quote,
"author": author,
"sourceName": "WikiQuote",
"link": "https://%s.wikiquote.org/wiki/%s" % (lang, author)
}]
def get_for_author(self, author):
return []
def get_for_keyword(self, keyword):
return []