aboutsummaryrefslogtreecommitdiffstats
path: root/alfred/feed.py
blob: 4839181c6877ed5d8aaad4de7189547367943574 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
"""
Sopel plugin: feed.gumx.cc aggregator management

Commands (owner only):
  !feed                        - show usage
  !feed refresh                - regenerate feed.gumx.cc now
  !feed add <url> [nick]       - add a feed and refresh
  !feed list                   - list followed feeds
  !feed rm <nick>              - remove a feed by nick and refresh
"""

import subprocess
import os
import sys
from datetime import date as _date

from sopel import plugin

import os as _os, sys as _sys
_alfred_dir = _os.path.dirname(_os.path.abspath(__file__))
if _alfred_dir not in _sys.path:
    _sys.path.insert(0, _alfred_dir)
import helpstrings as h

FEEDS_FILE       = '/home/ahmed/feeds.txt'
READ_POINT_FILE  = '/home/ahmed/feed-read.txt'
FEED_SCRIPT      = '/home/ahmed/scripts/feed-gen.py'


def _is_owner(bot, trigger):
    return trigger.nick == bot.settings.core.owner


def _load_feeds():
    feeds = []
    try:
        with open(FEEDS_FILE) as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith('#'):
                    feeds.append(line)
    except FileNotFoundError:
        pass
    return feeds


def _save_feeds(feeds):
    with open(FEEDS_FILE, 'w') as f:
        for line in feeds:
            f.write(line + '\n')


def _refresh(bot):
    try:
        result = subprocess.run(
            ['python3', FEED_SCRIPT],
            capture_output=True, text=True, timeout=60,
        )
        if result.returncode == 0:
            last = result.stdout.strip().splitlines()[-1] if result.stdout.strip() else 'done'
            bot.say(last)
        else:
            bot.say(f'error: {result.stderr.strip()[:200]}')
    except subprocess.TimeoutExpired:
        bot.say('feed-gen timed out')
    except Exception as e:
        bot.say(f'error: {e}')


@plugin.commands('feed')
def cmd_feed(bot, trigger):
    if not _is_owner(bot, trigger):
        return

    raw  = (trigger.group(2) or '').strip()
    args = raw.split(None, 2)
    sub  = args[0].lower() if args else ''

    if not sub:
        bot.say(h.FEED_TOPIC)
        return

    if sub == 'refresh':
        bot.say('refreshing...')
        _refresh(bot)
        return

    if sub == 'list':
        feeds = _load_feeds()
        if not feeds:
            bot.say('no feeds')
            return
        for line in feeds:
            bot.say(line)
        return

    if sub == 'add':
        if len(args) < 2:
            bot.say('usage: !feed add <url> [nick]')
            return
        url  = args[1]
        nick = args[2].strip() if len(args) > 2 else url
        feeds = _load_feeds()
        if any(line.split()[0] == url for line in feeds):
            bot.say(f'already following {url}')
            return
        feeds.append(f'{url} {nick}')
        _save_feeds(feeds)
        bot.say(f'added {nick}')
        _refresh(bot)
        return

    if sub == 'rm':
        if len(args) < 2:
            bot.say('usage: !feed rm <nick>')
            return
        target = args[1].strip()
        feeds  = _load_feeds()
        before = len(feeds)
        feeds  = [
            line for line in feeds
            if not (len(line.split(None, 1)) > 1 and line.split(None, 1)[1].strip() == target)
            and line.split()[0] != target
        ]
        if len(feeds) == before:
            bot.say(f'not found: {target}')
            return
        _save_feeds(feeds)
        bot.say(f'removed {target}')
        _refresh(bot)
        return

    if sub == 'read':
        if len(args) >= 2:
            date_str = args[1].strip()
            try:
                from datetime import datetime
                datetime.strptime(date_str, '%Y-%m-%d')
            except ValueError:
                bot.say('usage: !feed read [yyyy-mm-dd]')
                return
        else:
            date_str = _date.today().strftime('%Y-%m-%d')
        try:
            with open(READ_POINT_FILE, 'w') as f:
                f.write(date_str + '\n')
            bot.say(f'read point set to {date_str}')
            _refresh(bot)
        except Exception as e:
            bot.say(f'error: {e}')
        return

    bot.say(h.FEED_TOPIC)