db.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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 "title" in filter and filter["title"] != "":
  29. filter["title"]=filter["title"].replace("(","\(").replace(")","\)")
  30. db_filter["title"]={"$regex":".*%s.*"%filter["title"], "$options": 'i'}
  31. if "site" in filter and filter["site"] != "":
  32. filter["site"]=filter["site"].replace("(","\(").replace(")","\)")
  33. db_filter["source_name"]={"$regex":".*%s.*"%filter["site"], "$options": 'i'}
  34. #db_filter["$or"]=[
  35. # {"source_name": {"$regex":".*%s.*"%filter["site"], "$options": 'i'}},
  36. # {"url": {"$regex":".*%s.*"%filter["site"], "$options": 'i' }}
  37. # ]
  38. if "minweight" in filter and filter["minweight"] != "":
  39. db_filter["weight"]={"$gt":int(filter["minweight"])}
  40. if "keyword" in filter and len(filter["keyword"]) >0:
  41. db_filter["kw"]={"$all": filter["keyword"]}
  42. #db_filter["kw.0"]={"$exists":False}
  43. pageNumber=0
  44. if "page" in filter:
  45. pageNumber=filter["page"]
  46. #print(db_filter)
  47. res = self.c_articles.find(db_filter,{"html":0,"text":0})
  48. if res is not None:
  49. toSkip=(((pageNumber-1)*limit) if pageNumber > 0 else 0)
  50. q = res.skip(toSkip).sort("scrap_date",DESCENDING).limit(limit)
  51. count = q.count()
  52. else:
  53. q = []
  54. count = 0
  55. return { 'articles': [ self.jsonable(p) for p in q ],
  56. 'count' : count }
  57. def article(self, id):
  58. ret=self.c_articles.find_one({"_id":ObjectId(id)})
  59. return self.jsonable(ret)
  60. def delete_article(self,artid):
  61. self.c_articles.update({"_id":ObjectId(artid)},{"$set":{"deleted":True}})
  62. return True
  63. def sources(self,id=None):
  64. if id is None:
  65. return [ self.jsonable(p) for p in self.c_sources.find() ]
  66. ret=self.c_sources.find_one({"_id":ObjectId(id)})
  67. return self.jsonable(ret)
  68. def rss_sources(self):
  69. return [ p for p in self.c_sources.find({"rss":1}) ]
  70. def insert_article(self,o):
  71. try:
  72. self.c_articles.insert_one(o)
  73. return True
  74. except errors.DuplicateKeyError:
  75. print("Dup")
  76. return False
  77. def purge_error(self):
  78. self.c_articles.remove({'error':True})
  79. def article_exists(self,url):
  80. ret=self.c_articles.find_one({'url':url})
  81. if ret is None:
  82. return False
  83. return True
  84. def lower_arr(self,arr):
  85. return [a.lower() for a in arr]
  86. def to_regex(self,arr): #"ACH" | "PAYMENT" | "EBAY"
  87. return [ re.compile('\\b'+w.lower()+'\\b') for w in arr ]
  88. def get_keywords_list(self):
  89. kw=self.client[self.DB]["keywords"]
  90. return [ k["keyword"] for k in kw.find({}) ]
  91. def get_keywords(self,category):
  92. kw=self.client[self.DB]["keywords"] #FIXME, split on "|" or regex
  93. ret = [ {"weight":k["weight"],
  94. "kw": k["keyword"],
  95. "pattern": self.to_regex(k["keyword"].split("|")) } for k in kw.find({}) ]#FIXME, categories
  96. return ret
  97. def add_source(self,url,rss,selector,name):
  98. self.c_sources.insert({"link":url,
  99. "rss":rss,
  100. "selector":selector,
  101. "name":name,
  102. "category":0})
  103. def reparse_articles(self,articles,kw):
  104. for a in articles:
  105. #print(a)
  106. art=self.c_articles.find_one({"url":a["url"]})
  107. res=news.match_keywords(kw,art["text"])
  108. #(matches,w_sum,matching)
  109. #if(res["matches"]):
  110. print(res)
  111. self.c_articles.update({"_id":ObjectId(a["_id"])}, {"$set": res })
  112. #matches, kw, weight