Something something like soundcloud but not like soundcloud.
Log in, upload records, done.
Simple, easy, KISS.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

models.py 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. import datetime
  2. import os
  3. from flask import current_app
  4. from flask_security import SQLAlchemyUserDatastore, UserMixin, RoleMixin
  5. from flask_sqlalchemy import SQLAlchemy
  6. from slugify import slugify
  7. from sqlalchemy import UniqueConstraint
  8. from sqlalchemy import event
  9. from sqlalchemy.ext.hybrid import Comparator
  10. from sqlalchemy.ext.hybrid import hybrid_property
  11. from sqlalchemy.sql import func
  12. from sqlalchemy_searchable import make_searchable
  13. from sqlalchemy_utils.types.choice import ChoiceType
  14. from sqlalchemy_utils.types.url import URLType
  15. from sqlalchemy_utils.types.json import JSONType
  16. from little_boxes.key import Key as LittleBoxesKey
  17. from activitypub.utils import ap_url
  18. from sqlalchemy.dialects.postgresql import UUID
  19. from sqlalchemy import text as sa_text
  20. from little_boxes import activitypub as ap
  21. from urllib.parse import urlparse
  22. db = SQLAlchemy()
  23. make_searchable(db.metadata)
  24. # #### Base ####
  25. class CaseInsensitiveComparator(Comparator):
  26. def __eq__(self, other):
  27. return func.lower(self.__clause_element__()) == func.lower(other)
  28. class Config(db.Model):
  29. __tablename__ = "config"
  30. id = db.Column(db.Integer, primary_key=True)
  31. app_name = db.Column(db.String(255), default=None)
  32. app_description = db.Column(db.Text)
  33. # #### User ####
  34. roles_users = db.Table(
  35. "roles_users",
  36. db.Column("user_id", db.Integer(), db.ForeignKey("user.id")),
  37. db.Column("role_id", db.Integer(), db.ForeignKey("role.id")),
  38. )
  39. class Role(db.Model, RoleMixin):
  40. id = db.Column(db.Integer(), primary_key=True)
  41. name = db.Column(db.String(80), unique=True, nullable=False, info={"label": "Name"})
  42. description = db.Column(db.String(255), info={"label": "Description"})
  43. __mapper_args__ = {"order_by": name}
  44. class User(db.Model, UserMixin):
  45. id = db.Column(db.Integer, primary_key=True)
  46. email = db.Column(db.String(255), unique=True, nullable=False, info={"label": "Email"})
  47. name = db.Column(db.String(255), unique=True, nullable=False, info={"label": "Username"})
  48. password = db.Column(db.String(255), nullable=False, info={"label": "Password"})
  49. active = db.Column(db.Boolean())
  50. confirmed_at = db.Column(db.DateTime())
  51. display_name = db.Column(db.String(30), nullable=True, info={"label": "Display name"})
  52. locale = db.Column(db.String(5), default="en")
  53. timezone = db.Column(db.String(255), nullable=False, default="UTC") # Managed and fed by pytz
  54. slug = db.Column(db.String(255), unique=True, nullable=True)
  55. roles = db.relationship("Role", secondary=roles_users, backref=db.backref("users", lazy="dynamic"))
  56. apitokens = db.relationship("Apitoken", backref="user", lazy="dynamic", cascade="delete")
  57. user_loggings = db.relationship("UserLogging", backref="user", lazy="dynamic", cascade="delete")
  58. loggings = db.relationship("Logging", backref="user", lazy="dynamic", cascade="delete")
  59. sounds = db.relationship("Sound", backref="user", lazy="dynamic", cascade="delete")
  60. albums = db.relationship("Album", backref="user", lazy="dynamic", cascade="delete")
  61. __mapper_args__ = {"order_by": name}
  62. def join_roles(self, string):
  63. return string.join([i.description for i in self.roles])
  64. @staticmethod
  65. def generate_slug(target, value, oldvalue, initiator):
  66. if value and (not target.slug or value != oldvalue):
  67. target.slug = value
  68. @hybrid_property
  69. def name_insensitive(self):
  70. return self.name.lower()
  71. @name_insensitive.comparator
  72. def name_insensitive(cls):
  73. return CaseInsensitiveComparator(cls.name)
  74. def __repr__(self):
  75. return f"<User(id='{self.id}', name='{self.name}')>"
  76. def username(self):
  77. if not self.display_name:
  78. return self.name
  79. elif len(self.display_name) > 0:
  80. return self.display_name
  81. else:
  82. return self.name
  83. event.listen(User.name, "set", User.generate_slug, retval=False)
  84. class Apitoken(db.Model):
  85. id = db.Column(db.Integer, primary_key=True)
  86. user_id = db.Column(db.Integer(), db.ForeignKey("user.id"), nullable=False)
  87. token = db.Column(db.String(255), unique=True, nullable=False, info={"label": "Token"})
  88. secret = db.Column(db.String(255), unique=True, nullable=False, info={"label": "Secret"})
  89. user_datastore = SQLAlchemyUserDatastore(db, User, Role)
  90. # #### Logging ####
  91. class Logging(db.Model):
  92. __tablename__ = "logging"
  93. id = db.Column(db.Integer, primary_key=True)
  94. category = db.Column(db.String(255), nullable=False, default="General")
  95. level = db.Column(db.String(255), nullable=False, default="INFO")
  96. message = db.Column(db.Text, nullable=False)
  97. timestamp = db.Column(
  98. db.DateTime(timezone=False), default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow
  99. )
  100. user_id = db.Column(db.Integer(), db.ForeignKey("user.id"), nullable=True)
  101. __mapper_args__ = {"order_by": timestamp.desc()}
  102. class UserLogging(db.Model):
  103. __tablename__ = "user_logging"
  104. id = db.Column(db.Integer, primary_key=True)
  105. category = db.Column(db.String(255), nullable=False, default="General")
  106. level = db.Column(db.String(255), nullable=False, default="INFO")
  107. message = db.Column(db.Text, nullable=False)
  108. timestamp = db.Column(
  109. db.DateTime(timezone=False), default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow
  110. )
  111. item_id = db.Column(db.Integer(), nullable=True)
  112. user_id = db.Column(db.Integer(), db.ForeignKey("user.id"), nullable=False)
  113. __mapper_args__ = {"order_by": timestamp.desc()}
  114. # #### Tracks ####
  115. class SoundInfo(db.Model):
  116. __tablename__ = "sound_info"
  117. id = db.Column(db.Integer, primary_key=True)
  118. duration = db.Column(db.Float, nullable=True)
  119. format = db.Column(db.String(255), nullable=True)
  120. rate = db.Column(db.String(255), nullable=True)
  121. channels = db.Column(db.Integer, nullable=True)
  122. codec = db.Column(db.String(255), nullable=True)
  123. waveform = db.Column(db.Text, nullable=True)
  124. waveform_error = db.Column(db.Boolean, default=False)
  125. bitrate = db.Column(db.Integer, nullable=True)
  126. bitrate_mode = db.Column(db.String(10), nullable=True)
  127. type = db.Column(db.String(20), nullable=True)
  128. type_human = db.Column(db.String(20), nullable=True)
  129. # States markers
  130. done_basic = db.Column(db.Boolean, default=False)
  131. done_waveform = db.Column(db.Boolean, default=False)
  132. sound_id = db.Column(db.Integer(), db.ForeignKey("sound.id"), nullable=False)
  133. class Sound(db.Model):
  134. __tablename__ = "sound"
  135. TRANSCODE_WAITING = 0
  136. TRANSCODE_PROCESSING = 1
  137. TRANSCODE_DONE = 2
  138. TRANSCODE_ERROR = 3
  139. id = db.Column(db.Integer, primary_key=True)
  140. title = db.Column(db.String(255), nullable=True)
  141. uploaded = db.Column(db.DateTime(timezone=False), default=datetime.datetime.utcnow)
  142. updated = db.Column(
  143. db.DateTime(timezone=False), default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow
  144. )
  145. # TODO genre
  146. # TODO tags
  147. # TODO picture ?
  148. licence = db.Column(db.Integer, nullable=False, server_default="0")
  149. description = db.Column(db.UnicodeText(), nullable=True)
  150. private = db.Column(db.Boolean(), default=False, nullable=True)
  151. slug = db.Column(db.String(255), unique=True, nullable=True)
  152. filename = db.Column(db.String(255), unique=False, nullable=True)
  153. filename_transcoded = db.Column(db.String(255), unique=False, nullable=True)
  154. filename_orig = db.Column(db.String(255), unique=False, nullable=True)
  155. album_order = db.Column(db.Integer, nullable=True)
  156. transcode_needed = db.Column(db.Boolean(), default=False, nullable=True)
  157. transcode_state = db.Column(db.Integer(), default=0, nullable=False)
  158. # 0 nothing / default / waiting, 1 processing, 2 done, 3 error
  159. user_id = db.Column(db.Integer(), db.ForeignKey("user.id"), nullable=False)
  160. album_id = db.Column(db.Integer(), db.ForeignKey("album.id"), nullable=True)
  161. sound_infos = db.relationship("SoundInfo", backref="sound_info", lazy="dynamic", cascade="delete")
  162. activity_id = db.Column(db.Integer(), db.ForeignKey("activity.id"), nullable=True)
  163. activity = db.relationship("Activity")
  164. timeline = db.relationship("Timeline", uselist=False, back_populates="sound")
  165. __mapper_args__ = {"order_by": uploaded.desc()}
  166. def elapsed(self):
  167. print("db: {0}, now: {1}".format(self.uploaded, datetime.datetime.utcnow()))
  168. el = datetime.datetime.utcnow() - self.uploaded
  169. return el.total_seconds()
  170. def path_waveform(self):
  171. fname, _ = os.path.splitext(self.filename)
  172. return os.path.join(self.user.slug, "{0}.png".format(fname))
  173. def path_sound(self, orig=False):
  174. if self.transcode_needed and self.transcode_state == self.TRANSCODE_DONE and not orig:
  175. return os.path.join(self.user.slug, self.filename_transcoded)
  176. else:
  177. return os.path.join(self.user.slug, self.filename)
  178. def licence_info(self):
  179. return licences[self.licence]
  180. def get_title(self):
  181. if not self.title:
  182. return self.filename
  183. return self.title
  184. def processing_done(self):
  185. return self.transcode_state == self.TRANSCODE_DONE
  186. def is_ready(self):
  187. infos = self.sound_infos.first()
  188. if not infos:
  189. return False
  190. return self.processing_done() and infos.done_basic
  191. class Album(db.Model):
  192. __tablename__ = "album"
  193. id = db.Column(db.Integer, primary_key=True)
  194. title = db.Column(db.String(255), nullable=True)
  195. created = db.Column(db.DateTime(timezone=False), default=datetime.datetime.utcnow)
  196. updated = db.Column(
  197. db.DateTime(timezone=False), default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow
  198. )
  199. # TODO tags
  200. description = db.Column(db.UnicodeText(), nullable=True)
  201. private = db.Column(db.Boolean(), default=False, nullable=True)
  202. slug = db.Column(db.String(255), unique=True, nullable=True)
  203. user_id = db.Column(db.Integer(), db.ForeignKey("user.id"), nullable=False)
  204. sounds = db.relationship("Sound", backref="album", lazy="dynamic")
  205. timeline = db.relationship("Timeline", uselist=False, back_populates="album")
  206. __mapper_args__ = {"order_by": created.desc()}
  207. def elapsed(self):
  208. el = datetime.datetime.utcnow() - self.created
  209. return el.total_seconds()
  210. class Timeline(db.Model):
  211. __tablename__ = "timeline"
  212. id = db.Column(db.Integer, primary_key=True)
  213. timestamp = db.Column(db.DateTime(timezone=False), default=datetime.datetime.utcnow)
  214. private = db.Column(db.Boolean, default=False)
  215. sound_id = db.Column(db.Integer(), db.ForeignKey("user.id"), nullable=False)
  216. album_id = db.Column(db.Integer(), db.ForeignKey("album.id"), nullable=False)
  217. user_id = db.Column(db.Integer(), db.ForeignKey("sound.id"), nullable=False)
  218. album = db.relationship("Album", back_populates="timeline")
  219. sound = db.relationship("Sound", back_populates="timeline")
  220. __mapper_args__ = {"order_by": timestamp.desc()}
  221. licences = {
  222. 0: {"name": "Not Specified", "id": 0, "link": "", "icon": ""},
  223. 1: {
  224. "name": "CC Attribution",
  225. "id": 1,
  226. "link": "https://creativecommons.org/licenses/by/4.0/",
  227. "icon": "creative-commons",
  228. },
  229. 2: {
  230. "name": "CC Attribution Share Alike",
  231. "id": 2,
  232. "link": "https://creativecommons.org/licenses/by-sa/4.0",
  233. "icon": "creative-commons",
  234. },
  235. 3: {
  236. "name": "CC Attribution No Derivatives",
  237. "id": 3,
  238. "link": "https://creativecommons.org/licenses/by-nd/4.0",
  239. "icon": "creative-commons",
  240. },
  241. 4: {
  242. "name": "CC Attribution Non Commercial",
  243. "id": 4,
  244. "link": "https://creativecommons.org/licenses/by-nc/4.0",
  245. "icon": "creative-commons",
  246. },
  247. 5: {
  248. "name": "CC Attribution Non Commercial - Share Alike",
  249. "id": 5,
  250. "link": "https://creativecommons.org/licenses/by-nc-sa/4.0",
  251. "icon": "creative-commons",
  252. },
  253. 6: {
  254. "name": "CC Attribution Non Commercial - No Derivatives",
  255. "id": 6,
  256. "link": "https://creativecommons.org/licenses/by-nc-nd/4.0",
  257. "icon": "creative-commons",
  258. },
  259. 7: {"name": "Public Domain Dedication", "id": 7, "link": "", "icon": ""},
  260. }
  261. @event.listens_for(Sound, "after_update")
  262. @event.listens_for(Sound, "after_insert")
  263. def make_sound_slug(mapper, connection, target):
  264. if not target.title or target.title == "":
  265. title = "{0} {1}".format(target.id, target.filename_orig)
  266. else:
  267. if slugify(target.title) == "":
  268. title = "{0} {1}".format(target.id, target.filename_orig)
  269. else:
  270. title = "{0} {1}".format(target.id, target.title)
  271. slug = slugify(title[:255])
  272. connection.execute(Sound.__table__.update().where(Sound.__table__.c.id == target.id).values(slug=slug))
  273. @event.listens_for(Album, "after_update")
  274. @event.listens_for(Album, "after_insert")
  275. def make_album_slug(mapper, connection, target):
  276. title = "{0} {1}".format(target.id, target.title)
  277. slug = slugify(title[:255])
  278. connection.execute(Album.__table__.update().where(Album.__table__.c.id == target.id).values(slug=slug))
  279. @event.listens_for(User, "after_update")
  280. def update_user_actor(mapper, connection, target):
  281. connection.execute(
  282. Actor.__table__.update().where(Actor.__table__.c.user_id == target.id).values(name=target.display_name)
  283. )
  284. # #### Federation ####
  285. ACTOR_TYPE_CHOICES = [
  286. ("Person", "Person"),
  287. ("Application", "Application"),
  288. ("Group", "Group"),
  289. ("Organization", "Organization"),
  290. ("Service", "Service"),
  291. ]
  292. # This table keeps followings in every way
  293. # (remote to local, local to local, to remote...)
  294. # Query this table directly to get list for a specific actor or target
  295. class Follower(db.Model):
  296. __tablename__ = "followers"
  297. id = db.Column(db.Integer, primary_key=True)
  298. uuid = db.Column(UUID(as_uuid=True), server_default=sa_text("uuid_generate_v4()"), unique=True)
  299. actor_id = db.Column(db.Integer, db.ForeignKey("actor.id"))
  300. target_id = db.Column(db.Integer, db.ForeignKey("actor.id"))
  301. activity_url = db.Column(URLType(), unique=True, nullable=True)
  302. creation_date = db.Column(db.DateTime(timezone=False), default=datetime.datetime.utcnow)
  303. modification_date = db.Column(db.DateTime(timezone=False), onupdate=datetime.datetime.now)
  304. actor = db.relationship("Actor", foreign_keys=[actor_id])
  305. target = db.relationship("Actor", foreign_keys=[target_id])
  306. __table_args__ = (UniqueConstraint("actor_id", "target_id", name="unique_following"),)
  307. def __repr__(self):
  308. return f"<Follower(id='{self.id}', actor_id='{self.actor_id}', target_id='{self.target_id}')>"
  309. def follow_back(self):
  310. f = (
  311. db.session.query(Follower.id)
  312. .filter(Follower.actor_id == self.target_id, Follower.target_id == self.actor_id)
  313. .first()
  314. )
  315. return f
  316. class Actor(db.Model):
  317. __tablename__ = "actor"
  318. ap_type = "Actor"
  319. id = db.Column(db.Integer, primary_key=True)
  320. url = db.Column(URLType(), unique=True, index=True)
  321. outbox_url = db.Column(URLType())
  322. inbox_url = db.Column(URLType())
  323. following_url = db.Column(URLType(), nullable=True)
  324. followers_url = db.Column(URLType(), nullable=True)
  325. shared_inbox_url = db.Column(URLType(), nullable=True)
  326. type = db.Column(ChoiceType(ACTOR_TYPE_CHOICES), server_default="Person")
  327. name = db.Column(db.String(200), nullable=True)
  328. domain = db.Column(db.String(1000), nullable=False)
  329. summary = db.Column(db.String(500), nullable=True)
  330. preferred_username = db.Column(db.String(200), nullable=True)
  331. public_key = db.Column(db.String(5000), nullable=True)
  332. private_key = db.Column(db.String(5000), nullable=True)
  333. creation_date = db.Column(db.DateTime(timezone=False), default=datetime.datetime.utcnow)
  334. last_fetch_date = db.Column(db.DateTime(timezone=False), default=datetime.datetime.utcnow)
  335. manually_approves_followers = db.Column(db.Boolean, nullable=True, server_default=None)
  336. # Who follows self
  337. followers = db.relationship("Follower", backref="followers", primaryjoin=id == Follower.target_id)
  338. # Who self follows
  339. followings = db.relationship("Follower", backref="followings", primaryjoin=id == Follower.actor_id)
  340. # Relation on itself, intermediary with actor and target
  341. # By using an Association Object, which isn't possible except by using
  342. # two relations. This may be better than only one, and some hackish things
  343. # by querying directly the old db.Table definition
  344. user_id = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=True)
  345. user = db.relationship("User", backref=db.backref("actor"))
  346. __table_args__ = (UniqueConstraint("domain", "preferred_username", name="_domain_pref_username_uc"),)
  347. def __repr__(self):
  348. return f"<Actor(id='{self.id}', user_id='{self.user_id}', preferredUsername='{self.preferred_username}', domain='{self.domain}')>"
  349. def webfinger_subject(self):
  350. return f"{self.preferred_username}@{self.domain}"
  351. def private_key_id(self):
  352. return f"{self.url}#main-key"
  353. def mention_username(self):
  354. return f"@{self.preferred_username}@{self.domain}"
  355. def is_local(self):
  356. return self.domain == current_app.config["AP_DOMAIN"]
  357. def follow(self, activity_url, target):
  358. current_app.logger.debug(f"saving: {self.id} following {target.id}")
  359. rel = Follower.query.filter(Follower.actor_id == self.id, Follower.target_id == target.id).first()
  360. if not rel:
  361. rel = Follower()
  362. rel.actor_id = self.id
  363. rel.target_id = target.id
  364. rel.activity_url = activity_url
  365. db.session.add(rel)
  366. db.session.commit()
  367. def unfollow(self, target):
  368. current_app.logger.debug(f"saving: {self.id} unfollowing {target.id}")
  369. rel = Follower.query.filter(Follower.actor_id == self.id, Follower.target_id == target.id).first()
  370. if rel:
  371. db.session.delete(rel)
  372. db.session.commit()
  373. def to_dict(self):
  374. return {
  375. "@context": ap.DEFAULT_CTX,
  376. "id": self.url,
  377. "type": self.type.code,
  378. "preferredUsername": self.preferred_username,
  379. "name": self.name,
  380. "inbox": self.inbox_url,
  381. "outbox": self.outbox_url,
  382. "followers": self.followers_url,
  383. "following": self.following_url,
  384. "manuallyApprovesFollowers": self.manually_approves_followers,
  385. "publicKey": {"id": self.private_key_id(), "owner": self.url, "publicKeyPem": self.public_key},
  386. "endpoints": {"sharedInbox": self.shared_inbox_url},
  387. }
  388. class Activity(db.Model):
  389. __tablename__ = "activity"
  390. id = db.Column(db.Integer, primary_key=True)
  391. actor = db.Column(db.Integer, db.ForeignKey("actor.id"))
  392. uuid = db.Column(UUID(as_uuid=True), server_default=sa_text("uuid_generate_v4()"), unique=True)
  393. url = db.Column(URLType(), unique=True, nullable=True)
  394. type = db.Column(db.String(100), index=True)
  395. box = db.Column(db.String(100))
  396. payload = db.Column(JSONType())
  397. creation_date = db.Column(db.DateTime(timezone=False), default=datetime.datetime.utcnow)
  398. delivered = db.Column(db.Boolean, default=None, nullable=True)
  399. delivered_date = db.Column(db.DateTime(timezone=False), nullable=True)
  400. local = db.Column(db.Boolean, default=True)
  401. meta_deleted = db.Column(db.Boolean, default=False)
  402. meta_undo = db.Column(db.Boolean, default=False)
  403. meta_pinned = db.Column(db.Boolean, default=False)
  404. def create_actor(user):
  405. """
  406. :param user: an User object
  407. :return: an Actor object
  408. """
  409. actor = Actor()
  410. # Init a new Keypair for this user
  411. key = LittleBoxesKey(owner=user.name)
  412. key.new()
  413. actor.preferred_username = user.name
  414. actor.domain = current_app.config["AP_DOMAIN"]
  415. actor.type = "Person"
  416. actor.name = user.display_name
  417. actor.manually_approves_followers = False
  418. actor.url = ap_url("url", user.name)
  419. actor.shared_inbox_url = ap_url("shared_inbox", user.name)
  420. actor.inbox_url = ap_url("inbox", user.name)
  421. actor.outbox_url = ap_url("outbox", user.name)
  422. actor.private_key = key.privkey_pem
  423. actor.public_key = key.pubkey_pem
  424. actor.followers_url = ap_url("followers", user.name)
  425. actor.following_url = ap_url("followings", user.name)
  426. return actor
  427. def create_remote_actor(activity_actor: ap.BaseActivity):
  428. """
  429. :param activity_actor: a Little Boxes Actor object
  430. :return: an Actor object
  431. """
  432. actor = Actor()
  433. print(activity_actor)
  434. actor.preferred_username = activity_actor.preferredUsername
  435. domain = urlparse(activity_actor.url)
  436. actor.domain = domain.netloc
  437. actor.type = "Person"
  438. # FIXME: test for .name, it won't exist if not set (at least for mastodon)
  439. actor.name = activity_actor.preferredUsername # mastodon don't have .name
  440. actor.manually_approves_followers = False
  441. actor.url = activity_actor.id # FIXME: or .id ??? [cf backend.py:52-53]
  442. actor.shared_inbox_url = activity_actor._data.get("endpoints", {}).get("sharedInbox")
  443. actor.inbox_url = activity_actor.inbox
  444. actor.outbox_url = activity_actor.outbox
  445. actor.public_key = activity_actor.get_key().pubkey_pem
  446. actor.summary = activity_actor.summary
  447. actor.followers_url = activity_actor.followers
  448. actor.following_url = activity_actor.following
  449. return actor
  450. def update_remote_actor(actor_id: int, activity_actor: ap.BaseActivity) -> None:
  451. """
  452. :param actor_id: an Actor db ID
  453. :param activity_actor: a Little Boxes Actor object
  454. :return: nothing
  455. """
  456. actor = Actor.query.filter(Actor.id == actor_id).first()
  457. current_app.logger.debug(f"asked to update Actor {actor_id}: {activity_actor!r}")
  458. actor.preferred_username = activity_actor.preferredUsername
  459. domain = urlparse(activity_actor.url)
  460. actor.domain = domain.netloc
  461. actor.name = activity_actor.name
  462. actor.manually_approves_followers = False
  463. actor.url = activity_actor.id # FIXME: or .id ??? [cf backend.py:52-53]
  464. actor.shared_inbox_url = activity_actor._data.get("endpoints", {}).get("sharedInbox")
  465. actor.inbox_url = activity_actor.inbox
  466. actor.outbox_url = activity_actor.outbox
  467. actor.public_key = activity_actor.get_key().pubkey_pem
  468. actor.summary = activity_actor.summary
  469. actor.followers_url = activity_actor.followers
  470. actor.following_url = activity_actor.following
  471. db.session.commit()