db.py 5.6 KB

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