filters.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. __filename__ = "filters.py"
  2. __author__ = "Bob Mottram"
  3. __license__ = "AGPL3+"
  4. __version__ = "1.0.0"
  5. __maintainer__ = "Bob Mottram"
  6. __email__ = "bob@freedombone.net"
  7. __status__ = "Production"
  8. import os
  9. def addFilter(baseDir: str,nickname: str,domain: str,words: str) -> bool:
  10. """Adds a filter for particular words within the content of a incoming posts
  11. """
  12. filtersFilename=baseDir+'/accounts/'+nickname+'@'+domain+'/filters.txt'
  13. if os.path.isfile(filtersFilename):
  14. if words in open(filtersFilename).read():
  15. return False
  16. filtersFile=open(filtersFilename, "a+")
  17. filtersFile.write(words+'\n')
  18. filtersFile.close()
  19. return True
  20. def removeFilter(baseDir: str,nickname: str,domain: str, \
  21. words: str) -> bool:
  22. """Removes a word filter
  23. """
  24. filtersFilename=baseDir+'/accounts/'+nickname+'@'+domain+'/filters.txt'
  25. if os.path.isfile(filtersFilename):
  26. if words in open(filtersFilename).read():
  27. with open(filtersFilename, 'r') as fp:
  28. with open(filtersFilename+'.new', 'w') as fpnew:
  29. for line in fp:
  30. line=line.replace('\n','')
  31. if line!=words:
  32. fpnew.write(line+'\n')
  33. if os.path.isfile(filtersFilename+'.new'):
  34. os.rename(filtersFilename+'.new',filtersFilename)
  35. return True
  36. return False
  37. def isFiltered(baseDir: str,nickname: str,domain: str,content: str) -> bool:
  38. """Should the given content be filtered out?
  39. This is a simple type of filter which just matches words, not a regex
  40. You can add individual words or use word1+word2 to indicate that two
  41. words must be present although not necessarily adjacent
  42. """
  43. filtersFilename=baseDir+'/accounts/'+nickname+'@'+domain+'/filters.txt'
  44. if os.path.isfile(filtersFilename):
  45. with open(filtersFilename, 'r') as fp:
  46. for line in fp:
  47. filterStr=line.replace('\n','')
  48. if '+' not in filterStr:
  49. if filterStr in content:
  50. return True
  51. else:
  52. filterWords=filterStr.replace('"','').split('+')
  53. for word in filterWords:
  54. if not word in content:
  55. return False
  56. return True
  57. return False