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