db.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. from pymongo import MongoClient,errors,DESCENDING,ASCENDING
  2. from bson.objectid import ObjectId
  3. import datetime
  4. import re
  5. import news
  6. class db():
  7. DB="alexis"
  8. def __init__(self):
  9. self.client = MongoClient('localhost', 27017)
  10. self.c_sources=self.client[self.DB]["sources"]
  11. self.c_articles=self.client[self.DB]["articles"]
  12. def jsonable(self, el):
  13. if el is None or "_id" not in el:
  14. return el
  15. el["_id"]=str(el["_id"])
  16. return el
  17. def filter_articles(self, filter, limit=80):
  18. db_filter={}
  19. db_filter["matches"]=True
  20. db_filter["deleted"]=False
  21. db_filter["scrap_date"]={}
  22. if "maxdate" in filter and len(filter["maxdate"])>7:
  23. db_filter["scrap_date"]["$lt"]=datetime.datetime.strptime(filter["maxdate"],"%Y-%m-%d")
  24. if "mindate" in filter and len(filter["mindate"])>7:
  25. db_filter["scrap_date"]["$gt"]=datetime.datetime.strptime(filter["mindate"],"%Y-%m-%d")
  26. if db_filter["scrap_date"]=={}:
  27. del db_filter["scrap_date"]
  28. if "site" in filter and filter["site"] != "":
  29. filter["site"]=filter["site"].replace("(","\(").replace(")","\)")
  30. db_filter["source_name"]={"$regex":".*%s.*"%filter["site"], "$options": 'i'}
  31. #db_filter["$or"]=[
  32. # {"source_name": {"$regex":".*%s.*"%filter["site"], "$options": 'i'}},
  33. # {"url": {"$regex":".*%s.*"%filter["site"], "$options": 'i' }}
  34. # ]
  35. if "minweight" in filter and filter["minweight"] != "":
  36. db_filter["weight"]={"$gt":int(filter["minweight"])}
  37. if "keyword" in filter and len(filter["keyword"]) >0:
  38. db_filter["kw"]={"$all": filter["keyword"]}
  39. #db_filter["kw.0"]={"$exists":False}
  40. pageNumber=0
  41. if "page" in filter:
  42. pageNumber=filter["page"]
  43. #print(db_filter)
  44. res = self.c_articles.find(db_filter,{"html":0,"text":0})
  45. if res is not None:
  46. toSkip=(((pageNumber-1)*limit) if pageNumber > 0 else 0)
  47. q = res.skip(toSkip).sort("scrap_date",DESCENDING).limit(limit)
  48. count = q.count()
  49. else:
  50. q = []
  51. count = 0
  52. return { 'articles': [ self.jsonable(p) for p in q ],
  53. 'count' : count }
  54. def article(self, id):
  55. ret=self.c_articles.find_one({"_id":ObjectId(id)})
  56. return self.jsonable(ret)
  57. def delete_article(self,artid):
  58. self.c_articles.update({"_id":ObjectId(artid)},{"$set":{"deleted":True}})
  59. return True
  60. def sources(self,id=None):
  61. if id is None:
  62. return [ self.jsonable(p) for p in self.c_sources.find() ]
  63. ret=self.c_sources.find_one({"_id":ObjectId(id)})
  64. return self.jsonable(ret)
  65. def rss_sources(self):
  66. return [ p for p in self.c_sources.find({"rss":1}) ]
  67. def insert_article(self,o):
  68. try:
  69. self.c_articles.insert_one(o)
  70. return True
  71. except errors.DuplicateKeyError:
  72. print("Dup")
  73. return False
  74. def purge_error(self):
  75. self.c_articles.remove({'error':True})
  76. def article_exists(self,url):
  77. ret=self.c_articles.find_one({'url':url})
  78. if ret is None:
  79. return False
  80. return True
  81. def lower_arr(self,arr):
  82. return [a.lower() for a in arr]
  83. def to_regex(self,arr): #"ACH" | "PAYMENT" | "EBAY"
  84. return [ re.compile('\\b'+w.lower()+'\\b') for w in arr ]
  85. def get_keywords_list(self):
  86. kw=self.client[self.DB]["keywords"]
  87. return [ k["keyword"] for k in kw.find({}) ]
  88. def get_keywords(self,category):
  89. kw=self.client[self.DB]["keywords"] #FIXME, split on "|" or regex
  90. ret = [ {"weight":k["weight"],
  91. "kw": k["keyword"],
  92. "pattern": self.to_regex(k["keyword"].split("|")) } for k in kw.find({}) ]#FIXME, categories
  93. return ret
  94. def add_source(self,url,rss,selector,name):
  95. self.c_sources.insert({"link":url,
  96. "rss":rss,
  97. "selector":selector,
  98. "name":name,
  99. "category":0})
  100. def reparse_articles(self,articles,kw):
  101. for a in articles:
  102. #print(a)
  103. art=self.c_articles.find_one({"url":a["url"]})
  104. res=news.match_keywords(kw,art["text"])
  105. #(matches,w_sum,matching)
  106. #if(res["matches"]):
  107. print(res)
  108. self.c_articles.update({"_id":ObjectId(a["_id"])}, {"$set": res })
  109. #matches, kw, weight