core/migration/tables/users.py

145 lines
4.9 KiB
Python
Raw Normal View History

2022-08-11 09:14:12 +00:00
from dateutil.parser import parse
from sqlalchemy.exc import IntegrityError
2022-11-18 04:46:33 +00:00
from bs4 import BeautifulSoup
2022-08-11 09:59:35 +00:00
from base.orm import local_session
2022-11-08 15:50:28 +00:00
from orm.user import AuthorFollower, User, UserRating
2022-08-11 09:14:12 +00:00
2022-09-03 10:50:14 +00:00
2022-08-11 09:14:12 +00:00
def migrate(entry):
2022-09-03 10:50:14 +00:00
if "subscribedTo" in entry:
del entry["subscribedTo"]
email = entry["emails"][0]["address"]
user_dict = {
"oid": entry["_id"],
"roles": [],
"ratings": [],
"username": email,
"email": email,
"createdAt": parse(entry["createdAt"]),
"emailConfirmed": ("@discours.io" in email) or bool(entry["emails"][0]["verified"]),
2022-09-03 10:50:14 +00:00
"muted": False, # amnesty
"bio": entry["profile"].get("bio", ""),
"notifications": [],
"links": [],
"name": "anonymous",
2022-11-28 20:29:02 +00:00
"password": entry["services"]["password"].get("bcrypt")
2022-09-03 10:50:14 +00:00
}
2022-11-28 20:29:02 +00:00
2022-09-03 10:50:14 +00:00
if "updatedAt" in entry:
user_dict["updatedAt"] = parse(entry["updatedAt"])
if "wasOnineAt" in entry:
2022-10-05 15:54:29 +00:00
user_dict["lastSeen"] = parse(entry["wasOnlineAt"])
2022-09-03 10:50:14 +00:00
if entry.get("profile"):
# slug
user_dict["slug"] = (
entry["profile"].get("path").lower().replace(" ", "-").strip()
)
2022-11-18 05:52:26 +00:00
bio = BeautifulSoup(entry.get("profile").get("bio") or "", features="lxml").text
2022-11-18 17:54:37 +00:00
if bio.startswith('<'):
2022-11-19 11:35:34 +00:00
print('[migration] bio! ' + bio)
2022-11-18 17:54:37 +00:00
bio = BeautifulSoup(bio, features="lxml").text
2022-11-18 04:46:33 +00:00
bio = bio.replace('\(', '(').replace('\)', ')')
2022-09-03 10:50:14 +00:00
# userpic
try:
user_dict["userpic"] = (
"https://assets.discours.io/unsafe/100x/"
+ entry["profile"]["thumborId"]
)
except KeyError:
try:
user_dict["userpic"] = entry["profile"]["image"]["url"]
except KeyError:
user_dict["userpic"] = ""
2022-08-11 09:14:12 +00:00
2022-09-03 10:50:14 +00:00
# name
fn = entry["profile"].get("firstName", "")
ln = entry["profile"].get("lastName", "")
name = user_dict["slug"] if user_dict["slug"] else "anonymous"
name = fn if fn else name
name = (name + " " + ln) if ln else name
name = (
entry["profile"]["path"].lower().strip().replace(" ", "-")
if len(name) < 2
else name
)
user_dict["name"] = name
2022-08-11 09:14:12 +00:00
2022-09-03 10:50:14 +00:00
# links
fb = entry["profile"].get("facebook", False)
if fb:
user_dict["links"].append(fb)
vk = entry["profile"].get("vkontakte", False)
if vk:
user_dict["links"].append(vk)
tr = entry["profile"].get("twitter", False)
if tr:
user_dict["links"].append(tr)
ws = entry["profile"].get("website", False)
if ws:
user_dict["links"].append(ws)
2022-08-11 09:14:12 +00:00
2022-09-03 10:50:14 +00:00
# some checks
if not user_dict["slug"] and len(user_dict["links"]) > 0:
user_dict["slug"] = user_dict["links"][0].split("/")[-1]
2022-08-11 09:14:12 +00:00
2022-09-03 10:50:14 +00:00
user_dict["slug"] = user_dict.get("slug", user_dict["email"].split("@")[0])
oid = user_dict["oid"]
user_dict["slug"] = user_dict["slug"].lower().strip().replace(" ", "-")
try:
user = User.create(**user_dict.copy())
except IntegrityError:
2022-09-03 10:50:14 +00:00
print("[migration] cannot create user " + user_dict["slug"])
with local_session() as session:
old_user = (
session.query(User).filter(User.slug == user_dict["slug"]).first()
)
old_user.oid = oid
user = old_user
if not user:
print("[migration] ERROR: cannot find user " + user_dict["slug"])
raise Exception
user_dict["id"] = user.id
return user_dict
2022-08-11 09:14:12 +00:00
def migrate_2stage(entry, id_map):
2022-09-03 10:50:14 +00:00
ce = 0
for rating_entry in entry.get("ratings", []):
rater_oid = rating_entry["createdBy"]
rater_slug = id_map.get(rater_oid)
if not rater_slug:
ce += 1
# print(rating_entry)
continue
oid = entry["_id"]
author_slug = id_map.get(oid)
2022-11-29 12:36:46 +00:00
2022-09-03 10:50:14 +00:00
with local_session() as session:
try:
2022-11-29 12:36:46 +00:00
rater = session.query(User).where(User.slug == rater_slug).one()
user = session.query(User).where(User.slug == author_slug).one()
user_rating_dict = {
"value": rating_entry["value"],
"rater_id": rater.id,
"user_id": user.id,
}
2022-09-03 10:50:14 +00:00
user_rating = UserRating.create(**user_rating_dict)
2022-09-18 14:29:21 +00:00
if user_rating_dict['value'] > 0:
af = AuthorFollower.create(
2022-11-29 12:36:46 +00:00
author_id=user.id,
follower_id=rater.id,
2022-09-18 14:29:21 +00:00
auto=True
)
session.add(af)
session.add(user_rating)
2022-09-03 10:50:14 +00:00
session.commit()
except IntegrityError:
print("[migration] cannot rate " + author_slug + "`s by " + rater_slug)
2022-09-03 10:50:14 +00:00
except Exception as e:
print(e)
return ce