epicyon/filters.py

78 lines
2.8 KiB
Python
Raw Normal View History

2019-07-14 20:50:27 +00:00
__filename__ = "filters.py"
__author__ = "Bob Mottram"
__license__ = "AGPL3+"
2019-12-14 10:52:19 +00:00
__version__ = "1.1.0"
2019-07-14 20:50:27 +00:00
__maintainer__ = "Bob Mottram"
__email__ = "bob@freedombone.net"
__status__ = "Production"
import os
def addFilter(baseDir: str,nickname: str,domain: str,words: str) -> bool:
"""Adds a filter for particular words within the content of a incoming posts
"""
filtersFilename=baseDir+'/accounts/'+nickname+'@'+domain+'/filters.txt'
if os.path.isfile(filtersFilename):
if words in open(filtersFilename).read():
return False
filtersFile=open(filtersFilename, "a+")
filtersFile.write(words+'\n')
filtersFile.close()
return True
def removeFilter(baseDir: str,nickname: str,domain: str, \
words: str) -> bool:
"""Removes a word filter
"""
filtersFilename=baseDir+'/accounts/'+nickname+'@'+domain+'/filters.txt'
if os.path.isfile(filtersFilename):
if words in open(filtersFilename).read():
with open(filtersFilename, 'r') as fp:
with open(filtersFilename+'.new', 'w') as fpnew:
for line in fp:
line=line.replace('\n','')
2019-07-14 21:00:33 +00:00
if line!=words:
2019-07-14 20:50:27 +00:00
fpnew.write(line+'\n')
if os.path.isfile(filtersFilename+'.new'):
os.rename(filtersFilename+'.new',filtersFilename)
return True
return False
2020-02-05 14:57:10 +00:00
def isTwitterPost(content: str) -> bool:
"""Returns true if the given post content is a retweet or twitter crosspost
"""
2020-02-05 15:22:20 +00:00
if '/twitter.com' in content or '@twitter.com' in content:
2020-02-05 14:57:10 +00:00
return True
2020-02-05 15:22:20 +00:00
elif 'RT:' in content:
2020-02-05 14:57:10 +00:00
return True
return False
2019-07-14 20:50:27 +00:00
def isFiltered(baseDir: str,nickname: str,domain: str,content: str) -> bool:
"""Should the given content be filtered out?
This is a simple type of filter which just matches words, not a regex
You can add individual words or use word1+word2 to indicate that two
words must be present although not necessarily adjacent
"""
2020-02-05 14:57:10 +00:00
# optionally remove retweets
removeTwitter=baseDir+'/accounts/'+nickname+'@'+domain+'/.removeTwitter'
if os.path.isfile(removeTwitter):
if isTwitterPost(content):
return True
2019-07-14 20:50:27 +00:00
filtersFilename=baseDir+'/accounts/'+nickname+'@'+domain+'/filters.txt'
if os.path.isfile(filtersFilename):
with open(filtersFilename, 'r') as fp:
for line in fp:
filterStr=line.replace('\n','')
if '+' not in filterStr:
if filterStr in content:
return True
else:
filterWords=filterStr.replace('"','').split('+')
for word in filterWords:
if not word in content:
return False
return True
return False