Пример #1
0
 def __init__(self):
     super().__init__('192.168.1.1', *self._get_creds())
     p = Path()
     self.data_path = p.easy_joiner(p.data_dir, 'connected-ips.json')
     self.current_connections = self.get_active_connections()
     self.previous_connections = self.get_previously_active_connections()
     self._add_connection_time_to_new_clients()
Пример #2
0
class TestPath(unittest.TestCase):
    def setUp(self) -> None:
        self.path = Path()

    def test_paths(self):
        files_only = self.path.get_files_in_dir(self.path.download_dir,
                                                full_paths=False)
        self.assertTrue(all(['/' not in x for x in files_only]))
        full_file_path = self.path.get_files_in_dir(self.path.download_dir,
                                                    full_paths=True)
        self.assertTrue(all(['/' in x for x in full_file_path]))

    def test_recursive(self):
        top_level = self.path.get_files_in_dir(self.path.download_dir,
                                               recursive=False)
        all_level = self.path.get_files_in_dir(self.path.download_dir,
                                               recursive=True)
        self.assertTrue(len(top_level) <= len(all_level))
Пример #3
0
 def __init__(self, sheet_key: str):
     k = Keys()
     try:
         gsheets_creds = k.get_key('gsheet-reader')
     except Exception as e:
         local_key_path = os.path.join(Path().keys_dir, 'GSHEET_READER')
         with open(local_key_path) as f:
             gsheets_creds = json.loads(f.read())
     os.environ['GDRIVE_API_CREDENTIALS'] = json.dumps(gsheets_creds)
     self.gc = pygsheets.authorize(
         service_account_env_var='GDRIVE_API_CREDENTIALS')
     self.sheets = self.gc.open_by_key(sheet_key).worksheets()
Пример #4
0
 def setUp(self) -> None:
     self.path = Path()
Пример #5
0
"""Checks slackmojis daily for new additions"""
import json
from kavalkilu import Path, LogWithInflux
from servertools import SlackComm, XPathExtractor

logg = LogWithInflux('emoji-scraper')
scom = SlackComm(bot='viktor', parent_log=logg)

p = Path()
fpath = p.easy_joiner(p.data_dir, 'slackmojis.json')
chan = 'emoji_suggestions'
url = 'https://slackmojis.com/emojis/recent'
xpath_extractor = XPathExtractor(url)

emoji_list = xpath_extractor.xpath('//ul[@class="emojis"]', single=True)
emojis = emoji_list.getchildren()

# Read in the previous emoji id list
if not p.exists(fpath):
    prev_emojis = {}
else:
    with open(fpath) as f:
        prev_emojis = json.loads(f.read())

new_emojis = {}
for emoji in emojis:
    emo_id = emoji.getchildren()[0].get('data-emoji-id-name')
    emo_name = emoji.getchildren()[0].getchildren()[1].text.strip()
    if emo_id not in prev_emojis.keys():
        # Get link and add to the id list
        emo_link = emoji.findall('.//img')[0].get('src')
Пример #6
0
import os
import json
import signal
import requests
from random import randint
from flask import Flask, request, make_response
from slacktools import SlackEventAdapter
from kavalkilu import Path, Log
from .utils import Viktor

bot_name = 'viktor'
DEBUG = os.environ['VIKTOR_DEBUG'] == '1'
kpath = Path()
logg = Log(bot_name, arg_parse=False)

key_path = kpath.easy_joiner(kpath.keys_dir,
                             f'{bot_name.upper()}_SLACK_KEYS.json')
with open(key_path) as f:
    key_dict = json.loads(f.read())
logg.debug('Instantiating bot...')
Bot = Viktor(bot_name, creds=key_dict, debug=DEBUG)

# Register the cleanup function as a signal handler
signal.signal(signal.SIGINT, Bot.cleanup)
signal.signal(signal.SIGTERM, Bot.cleanup)
# Include a means of halting duplicate requests from being handled
#   until I can figure out a better async protocol
message_events = []
emoji_events = []
user_events = []
action_timestamps = []
Пример #7
0
"""For joining timelapse shots"""
import os
from moviepy.editor import ImageClip, concatenate_videoclips
from kavalkilu import Path, LogWithInflux
from servertools import SlackComm

log = LogWithInflux('timelapse_combi')
p = Path()
tl_dir = p.easy_joiner(p.data_dir, 'timelapse')
fnames = {}
for dirpath, _, filenames in os.walk(tl_dir):
    dirname = os.path.basename(dirpath)
    if dirname != 'timelapse':
        fnames[os.path.basename(dirpath)] = filenames

files = []
# Begin combining shots
for k, v in fnames.items():
    if not any([k.startswith(x) for x in ['ac-', 're-']]):
        continue
    log.debug(f'Working on {k}. {len(v)} files.')
    full_paths = sorted([os.path.join(tl_dir, *[k, x]) for x in v])
    clips = []
    for fpath in full_paths:
        try:
            clips.append(ImageClip(fpath).set_duration(1))
        except ValueError:
            log.debug(f'Error with this path: {fpath}')
            continue
    clip = concatenate_videoclips(clips)
    clip = clip.set_fps(30).speedx(30)
Пример #8
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Read temperature and humidity from living room"""
import json
from pitools import Sensor
from kavalkilu import LogWithInflux, Path, NetTools

logg = LogWithInflux('elutuba_temp', log_dir='weather')
p = Path('pi')
peripherals_path = p.easy_joiner(p.extras_dir,
                                 ['pitools', 'scripts', 'peripherals.json'])

# Read in the peripherals file
with open(peripherals_path) as f:
    pers = json.loads(f.read())

# machine_name = 'pi-elutuba'
machine_name = NetTools().hostname

for k, v in pers.items():
    sensor = None
    name_split = k.split('-')
    if len(name_split) > 1:
        name = '-'.join(name_split[1:])
    else:
        name = machine_name

    if k.startswith('dht'):
        # DHT22 sensor
        sensor = Sensor('DHT22', data_pin=v, loc_override=name)
    elif k.startswith('dallas'):
Пример #9
0
import os
from typing import Dict
from pykeepass import PyKeePass
from pykeepass.entry import Entry
from kavalkilu import Path

p = Path()
ROOT_DIR = os.path.dirname(os.path.dirname(__file__))


def get_secret_file(fname: str) -> str:
    """Grabs a file containing a 'metasecret' (secret for obtaining secrets)"""
    secret_path = p.easy_joiner(p.keys_dir, fname)
    if not p.exists(secret_path):
        raise FileNotFoundError(f'File at \'{secret_path}\' does not exist.')
    with open(secret_path) as f:
        return f.read().strip()


def read_props() -> Dict[str, str]:
    props = {}
    with open(os.path.join(p.keys_dir, 'SECRETPROP'), 'r') as f:
        contents = f.read().split('\n')
        for item in contents:
            if item != '':
                key, value = item.split('=', 1)
                props[key] = value.strip()
    return props


class Secrets:
Пример #10
0
import os
import json
import requests
import signal
from typing import Dict
from flask import Flask, request, make_response
from slacktools import SlackEventAdapter, SecretStore
from easylogger import Log
from kavalkilu import Path
from .utils import CAHBot

bot_name = 'wizzy'
DEBUG = os.environ['CAH_DEBUG'] == '1'
kpath = Path()
logg = Log(bot_name)


def read_props() -> Dict[str, str]:
    props = {}
    with open(os.path.abspath('./secretprops.properties'), 'r') as f:
        contents = f.read().split('\n')
        for item in contents:
            if item != '':
                key, value = item.split('=', 1)
                props[key] = value.strip()
    return props


secretprops = read_props()
credstore = SecretStore('secretprops-bobdev.kdbx',
                        secretprops['slacktools_secret'])
Пример #11
0
 def __init__(self, target_zones: List[str]):
     self.zones = target_zones
     # This is where we store past alerts
     p = Path()
     self.data_path = p.easy_joiner(p.data_dir, 'severe_weather.csv')
     self.old_alerts = self.get_old_alerts()