Skip to content

Commit

Permalink
Add new types. Closes #9
Browse files Browse the repository at this point in the history
  • Loading branch information
deanishe committed Feb 21, 2019
1 parent b653a4c commit 7f75b76
Show file tree
Hide file tree
Showing 317 changed files with 33,762 additions and 8,765 deletions.
Binary file removed Fakeum-2.0.1.alfredworkflow
Binary file not shown.
Binary file added Fakeum-2.2.0.alfredworkflow
Binary file not shown.
41 changes: 4 additions & 37 deletions src/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@
from collections import OrderedDict
import logging
import os
import subprocess

from workflow import Variables
from workflow.util import run_applescript


log = logging.getLogger('workflow')
Expand Down Expand Up @@ -105,7 +105,7 @@
('th_TH', 'Thai'),
('tr_TR', 'Turkish'),
('uk_UA', 'Ukranian'),
))
))


# Workflow's bundle IDs
Expand All @@ -114,19 +114,10 @@
# Script Filter keyword
KEYWORD = os.getenv('keyword')

# AppleScript to call an External Trigger
TRIGGER_AS = (u'tell application "Alfred 3" to run trigger "{trigger}" '
u'in workflow "{bundleid}"')

# AppleScript to run an Alfred search
SEARCH_AS = u'tell application "Alfred 3" to search "{query}"'


def escape_as(s):
"""Escape string for inserting into AppleScript."""
return s.replace('"', '" & quote & "')


def boolvar(name, default=False):
"""Return `True` or `False` for a workflow variable."""
v = os.getenv(name)
Expand Down Expand Up @@ -156,42 +147,18 @@ def intvar(name, default=0):
return default


def savevar(name, value):
"""Save a workflow variable by adding it to ``info.plist``."""
from plistlib import readPlist, writePlist
if not isinstance(value, basestring):
value = str(value)

data = readPlist('info.plist')
data['variables'][name] = value
writePlist(data, 'info.plist')
log.debug(u'set workflow variable "%s" to "%s"', name, value)


def run_trigger(name, arg=None):
"""Run an external trigger."""
script = TRIGGER_AS.format(trigger=name, bundleid=BUNDLE_ID)
if arg:
script += u' with argument "{}"'.format(escape_as(arg))

msg = u'calling external trigger "{}"'.format(name)
if arg:
msg += u' with arg "{}"'.format(arg)
log.debug(msg + ' ...')
subprocess.call(['osascript', '-e', script.encode('utf-8')])


def run_workflow(query=None):
"""Run workflow with query."""
query = KEYWORD + u' ' + (query or '')
script = SEARCH_AS.format(query=query)
log.debug(u'calling Alfred with query "%s" ...', query)
subprocess.call(['osascript', '-e', script.encode('utf-8')])
run_applescript(script)


def notify(title, text=''):
"""Show a notification."""
if not boolvar('SHOW_NOTIFICATIONS'):
return

v = Variables(title=title, text=text)
print(v)
18 changes: 5 additions & 13 deletions src/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import sys

from workflow import Workflow3, ICON_WARNING
from workflow.util import run_trigger, set_config

from common import (
ALL_LOCALES,
Expand All @@ -47,9 +48,6 @@
ICON_UPDATE_CHECK,
UPDATE_SETTINGS,
boolvar,
notify,
run_trigger,
savevar,
)


Expand Down Expand Up @@ -152,17 +150,14 @@ def toggle_locale(loc):
is_active = loc in active

if is_active:
msg = u'Deactivated locale {}'.format(ALL_LOCALES.get(loc))
log.info(u'Deactivated locale %s', ALL_LOCALES.get(loc))
active.remove(loc)
wf.settings['locales'] = active
else:
msg = u'Activated locale {}'.format(ALL_LOCALES.get(loc))
log.info(u'Activated locale %s', ALL_LOCALES.get(loc))
active.append(loc)
wf.settings['locales'] = active

log.info(msg)
notify(msg)

run_trigger('locales')


Expand All @@ -177,11 +172,8 @@ def toggle_notifications():
what = 'off'
value = '0'

msg = 'Turned notifications ' + what
savevar(name, value)

log.info(msg)
notify(msg)
set_config(name, value)
log.info('turned notifications ' + what)

run_trigger('config')

Expand Down
114 changes: 89 additions & 25 deletions src/fakeum.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@

from collections import OrderedDict
import datetime
import os
import random
import sys

from workflow import Workflow3, ICON_WARNING, MATCH_ALL, MATCH_ALLCHARS
from workflow.util import run_trigger, set_config

from common import (
DEFAULT_SETTINGS,
Expand All @@ -32,6 +34,7 @@

# Number of sentences per paragraph of Lipsum text
LIPSUMS = intvar('LIPSUM_SENTENCES', 3)
SNIPPET_MODE = os.getenv('SNIPPET_MODE') is not None

# ALFRED_AS = 'tell application "Alfred 2" to search "fake "'

Expand All @@ -45,11 +48,15 @@
('Email (free)', 'free_email'),
('Email (safe)', 'safe_email'),
('Email domain (free)', 'free_email_domain'),
('Social Security No.', 'ssn'),
('Phone No.', 'phone_number'),
('MSISDN', 'msisdn'),
# Addresses
('Address', 'address'),
('Street', 'street_address'),
('Street Name', 'street_name'),
('City', 'city'),
('Postcode', 'postcode'),
('State', 'state'),
('State abbr.', 'state_abbr'),
('Country', 'country'),
Expand All @@ -62,60 +69,101 @@
('URI', 'uri'),
('URI path', 'uri_path'),
('URL', 'url'),
('User-Agent', 'user_agent'),
# Corporate bullshit
('Corporate BS', 'bs'),
('Corporate catchphrase', 'catch_phrase'),
('Company', 'company'),
('Company suffix', 'company_suffix'),
# Lorem
('Paragraph', 'paragraph'),
# 'Paragraphs', 'paragraphs',
('Sentence', 'sentence'),
# 'Sentences', 'sentences',
# 'Text', 'text',
('Word', 'word'),
# 'Words', 'words',
# Dates and times
('Date', 'date'),
('Datetime', 'date_time'),
('ISO 8601 Datetime', 'iso8601'),
('Time', 'time'),
('Timezone', 'timezone'),
('UNIX timestamp', 'unix_time'),
('UNIX Timestamp', 'unix_time'),
# Banking
('Credit Card Provider', 'credit_card_provider'),
('Credit Card No.', 'credit_card_number'),
('Credit Card Expiry Date', 'credit_card_expire'),
('Credit Card Full', 'credit_card_full'),
('Credit Card Security No.', 'credit_card_security_code'),
('IBAN', 'iban'),
('BBAN', 'bban'),
('Bank Country Code', 'bank_country'),
('Currency', 'currency_name'),
('Currency Code', 'currency_code'),
('Cryptocurrency', 'cryptocurrency_name'),
('Cryptocurrency Code', 'cryptocurrency_code'),
# Barcodes
('EAN', 'ean'),
('EAN 8', 'ean8'),
('EAN 13', 'ean13'),
('ISBN 10', 'isbn10'),
('ISBN 13', 'isbn13'),
# Colours
('Colour Name', 'color_name'),
('Colour Name (Safe)', 'safe_color_name'),
('Hex Colour', 'hex_color'),
('Hex Colour (Safe)', 'safe_hex_color'),
('RGB Colour', 'rgb_color'),
('RGB CSS Colour', 'rgb_css_color'),
# Miscellaneous
('Profession', 'job'),
('Licence Plate', 'license_plate'),
('MD5 Hash', 'md5'),
('SHA1 Hash', 'sha1'),
('SHA256 Hash', 'sha256'),
('Locale', 'locale'),
('Language Code', 'language_code'),
('UUID4', 'uuid4'),
('Password (not secure!!)', 'password'),
])

log = None
fakers = []


def get_faker():
"""Return random faker instance."""
def all_fakers():
"""Return all fakers."""
from faker import Factory
global fakers
if not fakers:
for loc in wf.settings.get('locales', DEFAULT_SETTINGS['locales']):
fakers.append(Factory.create(loc))

return random.choice(fakers)
return fakers


def get_faker(name=None):
"""Return random faker instance."""
fakers = all_fakers()

if name is None:
return random.choice(fakers)

# def run_workflow():
# """Run workflow in Alfred"""
# subprocess.call(['osascript', '-e', ALFRED_AS])
random.shuffle(fakers)
methname = FAKERS[name]
for faker in fakers:
if hasattr(faker, methname):
return faker


def get_fake_datum(name):
"""Return one fake datum for name."""
faker = get_faker(name)
if not faker:
return None

methname = FAKERS[name]
# Get a faker instance that has the required method
while True:
faker = get_faker()
if hasattr(faker, methname):
if name == 'Paragraph': # Pass no. of sentences to generator
datum = getattr(faker, methname)(LIPSUMS, False)
else:
datum = getattr(faker, methname)()
break
if name == 'Paragraph': # Pass no. of sentences to generator
datum = getattr(faker, methname)(LIPSUMS, False)
else:
datum = getattr(faker, methname)()

if isinstance(datum, int):
datum = str(datum)
Expand All @@ -129,13 +177,26 @@ def get_fake_datum(name):
return datum


def supported_type(name):
"""Return ``True`` if at least one Faker supports this type."""
methname = FAKERS[name]
for faker in all_fakers():
if hasattr(faker, methname):
return True

log.debug('data type "%s" is not supported by active locales', name)
return False


def get_fake_data(names=None, count=1):
"""Return list of fake data."""
fake_data = []

if not names:
names = sorted(FAKERS.keys())

names = [n for n in names if supported_type(n)]

for name in names:

data = []
Expand Down Expand Up @@ -171,8 +232,8 @@ def main(wf):

if DELIMITER in query:
if query.endswith(DELIMITER):
# Run workflow with previous query
# run_workflow(wf.cached_data('last_query', session=True))
# Back up to empty query
# run_trigger('fake')
run_workflow()
return

Expand Down Expand Up @@ -230,9 +291,12 @@ def main(wf):
it.setvar('title', 'Copied to Clipboard')
it.setvar('text', data)

mod = it.add_modifier('cmd', 'Paste to frontmost application')
mod.setvar('paste', 1)
mod.setvar('SHOW_NOTIFICATIONS', 0)
if SNIPPET_MODE:
it.setvar('paste', 1)
else:
mod = it.add_modifier('cmd', 'Paste to frontmost application')
mod.setvar('paste', 1)
mod.setvar('SHOW_NOTIFICATIONS', 0)

wf.send_feedback()

Expand Down
Loading

0 comments on commit 7f75b76

Please sign in to comment.