1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU Affero General Public License for more details.
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 TODO: indexes on foreignkeys, where useful.
21 from __future__
import print_function
26 from sqlalchemy
import Column
, Integer
, Unicode
, UnicodeText
, DateTime
, \
27 Boolean
, ForeignKey
, UniqueConstraint
, PrimaryKeyConstraint
, \
28 SmallInteger
, Date
, types
29 from sqlalchemy
.orm
import relationship
, backref
, with_polymorphic
, validates
, \
31 from sqlalchemy
.orm
.collections
import attribute_mapped_collection
32 from sqlalchemy
.sql
import and_
33 from sqlalchemy
.sql
.expression
import desc
34 from sqlalchemy
.ext
.associationproxy
import association_proxy
35 from sqlalchemy
.util
import memoized_property
37 from mediagoblin
.db
.extratypes
import (PathTupleWithSlashes
, JSONEncoded
,
39 from mediagoblin
.db
.base
import Base
, DictReadAttrProxy
, FakeCursor
40 from mediagoblin
.db
.mixin
import UserMixin
, MediaEntryMixin
, \
41 CollectionMixin
, CollectionItemMixin
, ActivityMixin
, TextCommentMixin
, \
43 from mediagoblin
.tools
.files
import delete_media_files
44 from mediagoblin
.tools
.common
import import_component
45 from mediagoblin
.tools
.routing
import extract_url_arguments
46 from mediagoblin
.tools
.text
import convert_to_tag_list_of_dicts
49 from six
.moves
.urllib
.parse
import urljoin
52 _log
= logging
.getLogger(__name__
)
54 class GenericModelReference(Base
):
56 Represents a relationship to any model that is defined with a integer pk
58 __tablename__
= "core__generic_model_reference"
60 id = Column(Integer
, primary_key
=True)
61 obj_pk
= Column(Integer
, nullable
=False)
63 # This will be the tablename of the model
64 model_type
= Column(Unicode
, nullable
=False)
66 # Constrain it so obj_pk and model_type have to be unique
67 # They should be this order as the index is generated, "model_type" will be
68 # the major order as it's put first.
70 UniqueConstraint("model_type", "obj_pk"),
74 # This can happen if it's yet to be saved
75 if self
.model_type
is None or self
.obj_pk
is None:
78 model
= self
._get
_model
_from
_type
(self
.model_type
)
79 return model
.query
.filter_by(id=self
.obj_pk
).first()
81 def set_object(self
, obj
):
84 # Check we've been given a object
85 if not issubclass(model
, Base
):
86 raise ValueError("Only models can be set as using the GMR")
88 # Check that the model has an explicit __tablename__ declaration
89 if getattr(model
, "__tablename__", None) is None:
90 raise ValueError("Models must have __tablename__ attribute")
92 # Check that it's not a composite primary key
93 primary_keys
= [key
.name
for key
in class_mapper(model
).primary_key
]
94 if len(primary_keys
) > 1:
95 raise ValueError("Models can not have composite primary keys")
97 # Check that the field on the model is a an integer field
98 pk_column
= getattr(model
, primary_keys
[0])
99 if not isinstance(pk_column
.type, Integer
):
100 raise ValueError("Only models with integer pks can be set")
102 if getattr(obj
, pk_column
.key
) is None:
103 obj
.save(commit
=False)
105 self
.obj_pk
= getattr(obj
, pk_column
.key
)
106 self
.model_type
= obj
.__tablename
__
108 def _get_model_from_type(self
, model_type
):
109 """ Gets a model from a tablename (model type) """
110 if getattr(type(self
), "_TYPE_MAP", None) is None:
111 # We want to build on the class (not the instance) a map of all the
112 # models by the table name (type) for easy lookup, this is done on
113 # the class so it can be shared between all instances
115 # to prevent circular imports do import here
116 registry
= dict(Base
._decl
_class
_registry
).values()
117 self
._TYPE
_MAP
= dict(
118 ((m
.__tablename
__, m
) for m
in registry
if hasattr(m
, "__tablename__"))
120 setattr(type(self
), "_TYPE_MAP", self
._TYPE
_MAP
)
122 return self
.__class
__._TYPE
_MAP
[model_type
]
125 def find_for_obj(cls
, obj
):
126 """ Finds a GMR for an object or returns None """
127 # Is there one for this already.
129 pk
= getattr(obj
, "id")
131 gmr
= cls
.query
.filter_by(
133 model_type
=model
.__tablename
__
139 def find_or_new(cls
, obj
):
140 """ Finds an existing GMR or creates a new one for the object """
141 gmr
= cls
.find_for_obj(obj
)
143 # If there isn't one already create one
147 model_type
=type(obj
).__tablename
__
152 class Location(Base
):
153 """ Represents a physical location """
154 __tablename__
= "core__locations"
156 id = Column(Integer
, primary_key
=True)
157 name
= Column(Unicode
)
160 position
= Column(MutationDict
.as_mutable(JSONEncoded
))
161 address
= Column(MutationDict
.as_mutable(JSONEncoded
))
164 def create(cls
, data
, obj
):
166 location
.unserialize(data
)
168 obj
.location
= location
.id
171 def serialize(self
, request
):
172 location
= {"objectType": "place"}
174 if self
.name
is not None:
175 location
["displayName"] = self
.name
178 location
["position"] = self
.position
181 location
["address"] = self
.address
185 def unserialize(self
, data
):
186 if "displayName" in data
:
187 self
.name
= data
["displayName"]
192 # nicer way to do this?
193 if "position" in data
:
194 # TODO: deal with ISO 9709 formatted string as position
195 if "altitude" in data
["position"]:
196 self
.position
["altitude"] = data
["position"]["altitude"]
198 if "direction" in data
["position"]:
199 self
.position
["direction"] = data
["position"]["direction"]
201 if "longitude" in data
["position"]:
202 self
.position
["longitude"] = data
["position"]["longitude"]
204 if "latitude" in data
["position"]:
205 self
.position
["latitude"] = data
["position"]["latitude"]
207 if "address" in data
:
208 if "formatted" in data
["address"]:
209 self
.address
["formatted"] = data
["address"]["formatted"]
211 if "streetAddress" in data
["address"]:
212 self
.address
["streetAddress"] = data
["address"]["streetAddress"]
214 if "locality" in data
["address"]:
215 self
.address
["locality"] = data
["address"]["locality"]
217 if "region" in data
["address"]:
218 self
.address
["region"] = data
["address"]["region"]
220 if "postalCode" in data
["address"]:
221 self
.address
["postalCode"] = data
["addresss"]["postalCode"]
223 if "country" in data
["address"]:
224 self
.address
["country"] = data
["address"]["country"]
226 class User(Base
, UserMixin
):
228 Base user that is common amongst LocalUser and RemoteUser.
230 This holds all the fields which are common between both the Local and Remote
233 NB: ForeignKeys should reference this User model and NOT the LocalUser or
236 __tablename__
= "core__users"
238 id = Column(Integer
, primary_key
=True)
239 url
= Column(Unicode
)
240 bio
= Column(UnicodeText
)
241 name
= Column(Unicode
)
243 # This is required for the polymorphic inheritance
244 type = Column(Unicode
)
246 created
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.utcnow
)
247 updated
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.utcnow
)
249 location
= Column(Integer
, ForeignKey("core__locations.id"))
252 get_location
= relationship("Location", lazy
="joined")
255 'polymorphic_identity': 'user',
256 'polymorphic_on': type,
259 deletion_mode
= Base
.SOFT_DELETE
261 def soft_delete(self
, *args
, **kwargs
):
262 # Find all the Collections and delete those
263 for collection
in Collection
.query
.filter_by(actor
=self
.id):
264 collection
.delete(**kwargs
)
266 # Find all the comments and delete those too
267 for comment
in TextComment
.query
.filter_by(actor
=self
.id):
268 comment
.delete(**kwargs
)
270 # Find all the activities and delete those too
271 for activity
in Activity
.query
.filter_by(actor
=self
.id):
272 activity
.delete(**kwargs
)
274 super(User
, self
).soft_delete(*args
, **kwargs
)
277 def delete(self
, *args
, **kwargs
):
278 """Deletes a User and all related entries/comments/files/..."""
279 # Collections get deleted by relationships.
281 media_entries
= MediaEntry
.query
.filter(MediaEntry
.actor
== self
.id)
282 for media
in media_entries
:
283 # TODO: Make sure that "MediaEntry.delete()" also deletes
284 # all related files/Comments
285 media
.delete(del_orphan_tags
=False, commit
=False)
287 # Delete now unused tags
288 # TODO: import here due to cyclic imports!!! This cries for refactoring
289 from mediagoblin
.db
.util
import clean_orphan_tags
290 clean_orphan_tags(commit
=False)
292 # Delete user, pass through commit=False/True in kwargs
293 username
= self
.username
294 super(User
, self
).delete(*args
, **kwargs
)
295 _log
.info('Deleted user "{0}" account'.format(username
))
297 def has_privilege(self
, privilege
, allow_admin
=True):
299 This method checks to make sure a user has all the correct privileges
300 to access a piece of content.
302 :param privilege A unicode object which represent the different
303 privileges which may give the user access to
306 :param allow_admin If this is set to True the then if the user is
307 an admin, then this will always return True
308 even if the user hasn't been given the
309 privilege. (defaults to True)
311 priv
= Privilege
.query
.filter_by(privilege_name
=privilege
).one()
312 if priv
in self
.all_privileges
:
314 elif allow_admin
and self
.has_privilege(u
'admin', allow_admin
=False):
321 Checks if this user is banned.
323 :returns True if self is banned
324 :returns False if self is not
326 return UserBan
.query
.get(self
.id) is not None
328 def serialize(self
, request
):
329 published
= UTC
.localize(self
.created
)
330 updated
= UTC
.localize(self
.updated
)
332 "published": published
.isoformat(),
333 "updated": updated
.isoformat(),
334 "objectType": self
.object_type
,
342 user
.update({"summary": self
.bio
})
344 user
.update({"url": self
.url
})
346 user
.update({"location": self
.get_location
.serialize(request
)})
350 def unserialize(self
, data
):
351 if "summary" in data
:
352 self
.bio
= data
["summary"]
354 if "location" in data
:
355 Location
.create(data
, self
)
357 class LocalUser(User
):
358 """ This represents a user registered on this instance """
359 __tablename__
= "core__local_users"
361 id = Column(Integer
, ForeignKey("core__users.id"), primary_key
=True)
362 username
= Column(Unicode
, nullable
=False, unique
=True)
363 # Note: no db uniqueness constraint on email because it's not
364 # reliable (many email systems case insensitive despite against
365 # the RFC) and because it would be a mess to implement at this
367 email
= Column(Unicode
, nullable
=False)
368 pw_hash
= Column(Unicode
)
370 # Intented to be nullable=False, but migrations would not work for it
371 # set to nullable=True implicitly.
372 wants_comment_notification
= Column(Boolean
, default
=True)
373 wants_notifications
= Column(Boolean
, default
=True)
374 license_preference
= Column(Unicode
)
375 uploaded
= Column(Integer
, default
=0)
376 upload_limit
= Column(Integer
)
379 "polymorphic_identity": "user_local",
383 # plugin data would be in a separate model
386 return '<{0} #{1} {2} {3} "{4}">'.format(
387 self
.__class
__.__name
__,
389 'verified' if self
.has_privilege(u
'active') else 'non-verified',
390 'admin' if self
.has_privilege(u
'admin') else 'user',
393 def get_public_id(self
, host
):
394 return "acct:{0}@{1}".format(self
.username
, host
)
396 def serialize(self
, request
):
398 "id": self
.get_public_id(request
.host
),
399 "preferredUsername": self
.username
,
400 "displayName": self
.get_public_id(request
.host
).split(":", 1)[1],
403 "href": request
.urlgen(
404 "mediagoblin.api.user.profile",
405 username
=self
.username
,
410 "href": request
.urlgen(
411 "mediagoblin.api.inbox",
412 username
=self
.username
,
417 "href": request
.urlgen(
418 "mediagoblin.api.feed",
419 username
=self
.username
,
426 user
.update(super(LocalUser
, self
).serialize(request
))
429 class RemoteUser(User
):
430 """ User that is on another (remote) instance """
431 __tablename__
= "core__remote_users"
433 id = Column(Integer
, ForeignKey("core__users.id"), primary_key
=True)
434 webfinger
= Column(Unicode
, unique
=True)
437 'polymorphic_identity': 'user_remote'
441 return "<{0} #{1} {2}>".format(
442 self
.__class
__.__name
__,
450 Model representing a client - Used for API Auth
452 __tablename__
= "core__clients"
454 id = Column(Unicode
, nullable
=True, primary_key
=True)
455 secret
= Column(Unicode
, nullable
=False)
456 expirey
= Column(DateTime
, nullable
=True)
457 application_type
= Column(Unicode
, nullable
=False)
458 created
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.utcnow
)
459 updated
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.utcnow
)
462 redirect_uri
= Column(JSONEncoded
, nullable
=True)
463 logo_url
= Column(Unicode
, nullable
=True)
464 application_name
= Column(Unicode
, nullable
=True)
465 contacts
= Column(JSONEncoded
, nullable
=True)
468 if self
.application_name
:
469 return "<Client {0} - {1}>".format(self
.application_name
, self
.id)
471 return "<Client {0}>".format(self
.id)
473 class RequestToken(Base
):
475 Model for representing the request tokens
477 __tablename__
= "core__request_tokens"
479 token
= Column(Unicode
, primary_key
=True)
480 secret
= Column(Unicode
, nullable
=False)
481 client
= Column(Unicode
, ForeignKey(Client
.id))
482 actor
= Column(Integer
, ForeignKey(User
.id), nullable
=True)
483 used
= Column(Boolean
, default
=False)
484 authenticated
= Column(Boolean
, default
=False)
485 verifier
= Column(Unicode
, nullable
=True)
486 callback
= Column(Unicode
, nullable
=False, default
=u
"oob")
487 created
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.utcnow
)
488 updated
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.utcnow
)
490 get_client
= relationship(Client
)
492 class AccessToken(Base
):
494 Model for representing the access tokens
496 __tablename__
= "core__access_tokens"
498 token
= Column(Unicode
, nullable
=False, primary_key
=True)
499 secret
= Column(Unicode
, nullable
=False)
500 actor
= Column(Integer
, ForeignKey(User
.id))
501 request_token
= Column(Unicode
, ForeignKey(RequestToken
.token
))
502 created
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.utcnow
)
503 updated
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.utcnow
)
505 get_requesttoken
= relationship(RequestToken
)
508 class NonceTimestamp(Base
):
510 A place the timestamp and nonce can be stored - this is for OAuth1
512 __tablename__
= "core__nonce_timestamps"
514 nonce
= Column(Unicode
, nullable
=False, primary_key
=True)
515 timestamp
= Column(DateTime
, nullable
=False, primary_key
=True)
517 class MediaEntry(Base
, MediaEntryMixin
, CommentingMixin
):
519 TODO: Consider fetching the media_files using join
521 __tablename__
= "core__media_entries"
523 id = Column(Integer
, primary_key
=True)
524 public_id
= Column(Unicode
, unique
=True, nullable
=True)
525 remote
= Column(Boolean
, default
=False)
527 actor
= Column(Integer
, ForeignKey(User
.id), nullable
=False, index
=True)
528 title
= Column(Unicode
, nullable
=False)
529 slug
= Column(Unicode
)
530 description
= Column(UnicodeText
) # ??
531 media_type
= Column(Unicode
, nullable
=False)
532 state
= Column(Unicode
, default
=u
'unprocessed', nullable
=False)
533 # or use sqlalchemy.types.Enum?
534 license
= Column(Unicode
)
535 file_size
= Column(Integer
, default
=0)
536 location
= Column(Integer
, ForeignKey("core__locations.id"))
537 get_location
= relationship("Location", lazy
="joined")
539 created
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.utcnow
,
541 updated
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.utcnow
)
543 fail_error
= Column(Unicode
)
544 fail_metadata
= Column(JSONEncoded
)
546 transcoding_progress
= Column(SmallInteger
)
548 queued_media_file
= Column(PathTupleWithSlashes
)
550 queued_task_id
= Column(Unicode
)
553 UniqueConstraint('actor', 'slug'),
556 deletion_mode
= Base
.SOFT_DELETE
558 get_actor
= relationship(User
)
560 media_files_helper
= relationship("MediaFile",
561 collection_class
=attribute_mapped_collection("name"),
562 cascade
="all, delete-orphan"
564 media_files
= association_proxy('media_files_helper', 'file_path',
565 creator
=lambda k
, v
: MediaFile(name
=k
, file_path
=v
)
568 attachment_files_helper
= relationship("MediaAttachmentFile",
569 cascade
="all, delete-orphan",
570 order_by
="MediaAttachmentFile.created"
572 attachment_files
= association_proxy("attachment_files_helper", "dict_view",
573 creator
=lambda v
: MediaAttachmentFile(
574 name
=v
["name"], filepath
=v
["filepath"])
577 tags_helper
= relationship("MediaTag",
578 cascade
="all, delete-orphan" # should be automatically deleted
580 tags
= association_proxy("tags_helper", "dict_view",
581 creator
=lambda v
: MediaTag(name
=v
["name"], slug
=v
["slug"])
584 media_metadata
= Column(MutationDict
.as_mutable(JSONEncoded
),
585 default
=MutationDict())
591 def get_uploader(self
):
593 return self
.get_actor
601 def collections(self
):
602 """ Get any collections that this MediaEntry is in """
603 return list(Collection
.query
.join(Collection
.collection_items
).join(
604 CollectionItem
.object_helper
607 GenericModelReference
.model_type
== self
.__tablename
__,
608 GenericModelReference
.obj_pk
== self
.id
612 def get_comments(self
, ascending
=False):
613 query
= Comment
.query
.join(Comment
.target_helper
).filter(and_(
614 GenericModelReference
.obj_pk
== self
.id,
615 GenericModelReference
.model_type
== self
.__tablename
__
619 query
= query
.order_by(Comment
.added
.asc())
621 query
= query
.order_by(Comment
.added
.desc())
625 def url_to_prev(self
, urlgen
):
626 """get the next 'newer' entry by this user"""
627 media
= MediaEntry
.query
.filter(
628 (MediaEntry
.actor
== self
.actor
)
629 & (MediaEntry
.state
== u
'processed')
630 & (MediaEntry
.id > self
.id)).order_by(MediaEntry
.id).first()
632 if media
is not None:
633 return media
.url_for_self(urlgen
)
635 def url_to_next(self
, urlgen
):
636 """get the next 'older' entry by this user"""
637 media
= MediaEntry
.query
.filter(
638 (MediaEntry
.actor
== self
.actor
)
639 & (MediaEntry
.state
== u
'processed')
640 & (MediaEntry
.id < self
.id)).order_by(desc(MediaEntry
.id)).first()
642 if media
is not None:
643 return media
.url_for_self(urlgen
)
645 def get_file_metadata(self
, file_key
, metadata_key
=None):
647 Return the file_metadata dict of a MediaFile. If metadata_key is given,
648 return the value of the key.
650 media_file
= MediaFile
.query
.filter_by(media_entry
=self
.id,
651 name
=six
.text_type(file_key
)).first()
655 return media_file
.file_metadata
.get(metadata_key
, None)
657 return media_file
.file_metadata
659 def set_file_metadata(self
, file_key
, **kwargs
):
661 Update the file_metadata of a MediaFile.
663 media_file
= MediaFile
.query
.filter_by(media_entry
=self
.id,
664 name
=six
.text_type(file_key
)).first()
666 file_metadata
= media_file
.file_metadata
or {}
668 for key
, value
in six
.iteritems(kwargs
):
669 file_metadata
[key
] = value
671 media_file
.file_metadata
= file_metadata
675 def media_data(self
):
676 return getattr(self
, self
.media_data_ref
)
678 def media_data_init(self
, **kwargs
):
680 Initialize or update the contents of a media entry's media_data row
682 media_data
= self
.media_data
684 if media_data
is None:
685 # Get the correct table:
686 table
= import_component(self
.media_type
+ '.models:DATA_MODEL')
687 # No media data, so actually add a new one
688 media_data
= table(**kwargs
)
689 # Get the relationship set up.
690 media_data
.get_media_entry
= self
692 # Update old media data
693 for field
, value
in six
.iteritems(kwargs
):
694 setattr(media_data
, field
, value
)
697 def media_data_ref(self
):
698 return import_component(self
.media_type
+ '.models:BACKREF_NAME')
702 # obj.__repr__() should return a str on Python 2
703 safe_title
= self
.title
.encode('utf-8', 'replace')
705 safe_title
= self
.title
707 return '<{classname} {id}: {title}>'.format(
708 classname
=self
.__class
__.__name
__,
712 def soft_delete(self
, *args
, **kwargs
):
713 # Find all of the media comments for this and delete them
714 for comment
in self
.get_comments():
715 comment
.delete(*args
, **kwargs
)
717 super(MediaEntry
, self
).soft_delete(*args
, **kwargs
)
719 def delete(self
, del_orphan_tags
=True, **kwargs
):
720 """Delete MediaEntry and all related files/attachments/comments
722 This will *not* automatically delete unused collections, which
725 :param del_orphan_tags: True/false if we delete unused Tags too
726 :param commit: True/False if this should end the db transaction"""
727 # User's CollectionItems are automatically deleted via "cascade".
728 # Comments on this Media are deleted by cascade, hopefully.
730 # Delete all related files/attachments
732 delete_media_files(self
)
733 except OSError as error
:
734 # Returns list of files we failed to delete
735 _log
.error('No such files from the user "{1}" to delete: '
736 '{0}'.format(str(error
), self
.get_actor
))
737 _log
.info('Deleted Media entry id "{0}"'.format(self
.id))
738 # Related MediaTag's are automatically cleaned, but we might
739 # want to clean out unused Tag's too.
741 # TODO: Import here due to cyclic imports!!!
742 # This cries for refactoring
743 from mediagoblin
.db
.util
import clean_orphan_tags
744 clean_orphan_tags(commit
=False)
745 # pass through commit=False/True in kwargs
746 super(MediaEntry
, self
).delete(**kwargs
)
748 def serialize(self
, request
, show_comments
=True):
749 """ Unserialize MediaEntry to object """
750 author
= self
.get_actor
751 published
= UTC
.localize(self
.created
)
752 updated
= UTC
.localize(self
.updated
)
753 public_id
= self
.get_public_id(request
.urlgen
)
756 "author": author
.serialize(request
),
757 "objectType": self
.object_type
,
758 "url": self
.url_for_self(request
.urlgen
, qualified
=True),
760 "url": urljoin(request
.host_url
, self
.thumb_url
),
763 "url": urljoin(request
.host_url
, self
.original_url
),
765 "published": published
.isoformat(),
766 "updated": updated
.isoformat(),
778 context
["displayName"] = self
.title
781 context
["content"] = self
.description
784 context
["license"] = self
.license
787 context
["location"] = self
.get_location
.serialize(request
)
789 # Always show tags, even if empty list
791 context
["tags"] = [tag
['name'] for tag
in self
.tags
]
797 l
.comment().serialize(request
) for l
in self
.get_comments()]
798 total
= len(comments
)
799 context
["replies"] = {
802 "url": request
.urlgen(
803 "mediagoblin.api.object.comments",
804 object_type
=self
.object_type
,
810 # Add image height and width if possible. We didn't use to store this
811 # data and we're not able (and maybe not willing) to re-process all
812 # images so it's possible this might not exist.
813 if self
.get_file_metadata("thumb", "height"):
814 height
= self
.get_file_metadata("thumb", "height")
815 context
["image"]["height"] = height
816 if self
.get_file_metadata("thumb", "width"):
817 width
= self
.get_file_metadata("thumb", "width")
818 context
["image"]["width"] = width
819 if self
.get_file_metadata("original", "height"):
820 height
= self
.get_file_metadata("original", "height")
821 context
["fullImage"]["height"] = height
822 if self
.get_file_metadata("original", "height"):
823 width
= self
.get_file_metadata("original", "width")
824 context
["fullImage"]["width"] = width
828 def unserialize(self
, data
):
829 """ Takes API objects and unserializes on existing MediaEntry """
830 if "displayName" in data
:
831 self
.title
= data
["displayName"]
833 if "content" in data
:
834 self
.description
= data
["content"]
836 if "license" in data
:
837 self
.license
= data
["license"]
839 if "location" in data
:
840 License
.create(data
["location"], self
)
843 self
.tags
= convert_to_tag_list_of_dicts(', '.join(data
["tags"]))
847 class FileKeynames(Base
):
849 keywords for various places.
850 currently the MediaFile keys
852 __tablename__
= "core__file_keynames"
853 id = Column(Integer
, primary_key
=True)
854 name
= Column(Unicode
, unique
=True)
857 return "<FileKeyname %r: %r>" % (self
.id, self
.name
)
860 def find_or_new(cls
, name
):
861 t
= cls
.query
.filter_by(name
=name
).first()
864 return cls(name
=name
)
867 class MediaFile(Base
):
869 TODO: Highly consider moving "name" into a new table.
870 TODO: Consider preloading said table in software
872 __tablename__
= "core__mediafiles"
874 media_entry
= Column(
875 Integer
, ForeignKey(MediaEntry
.id),
877 name_id
= Column(SmallInteger
, ForeignKey(FileKeynames
.id), nullable
=False)
878 file_path
= Column(PathTupleWithSlashes
)
879 file_metadata
= Column(MutationDict
.as_mutable(JSONEncoded
))
882 PrimaryKeyConstraint('media_entry', 'name_id'),
886 return "<MediaFile %s: %r>" % (self
.name
, self
.file_path
)
888 name_helper
= relationship(FileKeynames
, lazy
="joined", innerjoin
=True)
889 name
= association_proxy('name_helper', 'name',
890 creator
=FileKeynames
.find_or_new
894 class MediaAttachmentFile(Base
):
895 __tablename__
= "core__attachment_files"
897 id = Column(Integer
, primary_key
=True)
898 media_entry
= Column(
899 Integer
, ForeignKey(MediaEntry
.id),
901 name
= Column(Unicode
, nullable
=False)
902 filepath
= Column(PathTupleWithSlashes
)
903 created
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.utcnow
)
907 """A dict like view on this object"""
908 return DictReadAttrProxy(self
)
912 __tablename__
= "core__tags"
914 id = Column(Integer
, primary_key
=True)
915 slug
= Column(Unicode
, nullable
=False, unique
=True)
918 return "<Tag %r: %r>" % (self
.id, self
.slug
)
921 def find_or_new(cls
, slug
):
922 t
= cls
.query
.filter_by(slug
=slug
).first()
925 return cls(slug
=slug
)
928 class MediaTag(Base
):
929 __tablename__
= "core__media_tags"
931 id = Column(Integer
, primary_key
=True)
932 media_entry
= Column(
933 Integer
, ForeignKey(MediaEntry
.id),
934 nullable
=False, index
=True)
935 tag
= Column(Integer
, ForeignKey(Tag
.id), nullable
=False, index
=True)
936 name
= Column(Unicode
)
937 # created = Column(DateTime, nullable=False, default=datetime.datetime.utcnow)
940 UniqueConstraint('tag', 'media_entry'),
943 tag_helper
= relationship(Tag
)
944 slug
= association_proxy('tag_helper', 'slug',
945 creator
=Tag
.find_or_new
948 def __init__(self
, name
=None, slug
=None):
953 self
.tag_helper
= Tag
.find_or_new(slug
)
957 """A dict like view on this object"""
958 return DictReadAttrProxy(self
)
962 Link table between a response and another object that can have replies.
964 This acts as a link table between an object and the comments on it, it's
965 done like this so that you can look up all the comments without knowing
966 whhich comments are on an object before hand. Any object can be a comment
967 and more or less any object can accept comments too.
969 Important: This is NOT the old MediaComment table.
971 __tablename__
= "core__comment_links"
973 id = Column(Integer
, primary_key
=True)
975 # The GMR to the object the comment is on.
978 ForeignKey(GenericModelReference
.id),
981 target_helper
= relationship(
982 GenericModelReference
,
983 foreign_keys
=[target_id
]
985 target
= association_proxy("target_helper", "get_object",
986 creator
=GenericModelReference
.find_or_new
)
991 ForeignKey(GenericModelReference
.id),
994 comment_helper
= relationship(
995 GenericModelReference
,
996 foreign_keys
=[comment_id
]
998 comment
= association_proxy("comment_helper", "get_object",
999 creator
=GenericModelReference
.find_or_new
)
1002 added
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.utcnow
)
1005 def get_author(self
):
1007 return self
.comment().get_actor
# noqa
1009 def __getattr__(self
, attr
):
1010 if attr
.startswith('_'):
1011 # if attr starts with '_', then it's probably some internal
1012 # sqlalchemy variable. Since __getattr__ is called when
1013 # non-existing attributes are being accessed, we should not try to
1014 # fetch it from self.comment()
1015 raise AttributeError
1017 _log
.debug('Old attr is being accessed: {0}'.format(attr
))
1018 return getattr(self
.comment(), attr
) # noqa
1019 except Exception as e
:
1023 class TextComment(Base
, TextCommentMixin
, CommentingMixin
):
1025 A basic text comment, this is a usually short amount of text and nothing else
1027 # This is a legacy from when Comments where just on MediaEntry objects.
1028 __tablename__
= "core__media_comments"
1030 id = Column(Integer
, primary_key
=True)
1031 public_id
= Column(Unicode
, unique
=True)
1032 actor
= Column(Integer
, ForeignKey(User
.id), nullable
=False)
1033 created
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.utcnow
)
1034 updated
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.utcnow
)
1035 content
= Column(UnicodeText
, nullable
=False)
1036 location
= Column(Integer
, ForeignKey("core__locations.id"))
1037 get_location
= relationship("Location", lazy
="joined")
1039 # Cascade: Comments are owned by their creator. So do the full thing.
1040 # lazy=dynamic: People might post a *lot* of comments,
1041 # so make the "posted_comments" a query-like thing.
1042 get_actor
= relationship(User
,
1043 backref
=backref("posted_comments",
1045 cascade
="all, delete-orphan"))
1046 deletion_mode
= Base
.SOFT_DELETE
1048 def serialize(self
, request
):
1049 """ Unserialize to python dictionary for API """
1050 target
= self
.get_reply_to()
1051 # If this is target just.. give them nothing?
1055 target
= target
.serialize(request
, show_comments
=False)
1058 author
= self
.get_actor
1059 published
= UTC
.localize(self
.created
)
1061 "id": self
.get_public_id(request
.urlgen
),
1062 "objectType": self
.object_type
,
1063 "content": self
.content
,
1064 "inReplyTo": target
,
1065 "author": author
.serialize(request
),
1066 "published": published
.isoformat(),
1067 "updated": published
.isoformat(),
1071 context
["location"] = self
.get_location
.seralize(request
)
1075 def unserialize(self
, data
, request
):
1076 """ Takes API objects and unserializes on existing comment """
1077 if "content" in data
:
1078 self
.content
= data
["content"]
1080 if "location" in data
:
1081 Location
.create(data
["location"], self
)
1084 # Handle changing the reply ID
1085 if "inReplyTo" in data
:
1086 # Validate that the ID is correct
1088 id = extract_url_arguments(
1089 url
=data
["inReplyTo"]["id"],
1090 urlmap
=request
.app
.url_map
1095 public_id
= request
.urlgen(
1096 "mediagoblin.api.object",
1098 object_type
=data
["inReplyTo"]["objectType"],
1102 media
= MediaEntry
.query
.filter_by(public_id
=public_id
).first()
1106 # We need an ID for this model.
1107 self
.save(commit
=False)
1117 class Collection(Base
, CollectionMixin
, CommentingMixin
):
1118 """A representation of a collection of objects.
1120 This holds a group/collection of objects that could be a user defined album
1121 or their inbox, outbox, followers, etc. These are always ordered and accessable
1122 via the API and web.
1124 The collection has a number of types which determine what kind of collection
1125 it is, for example the users inbox will be of `Collection.INBOX_TYPE` that will
1126 be stored on the `Collection.type` field. It's important to set the correct type.
1128 On deletion, contained CollectionItems get automatically reaped via
1130 __tablename__
= "core__collections"
1132 id = Column(Integer
, primary_key
=True)
1133 public_id
= Column(Unicode
, unique
=True)
1134 title
= Column(Unicode
, nullable
=False)
1135 slug
= Column(Unicode
)
1136 created
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.utcnow
,
1138 updated
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.utcnow
)
1139 description
= Column(UnicodeText
)
1140 actor
= Column(Integer
, ForeignKey(User
.id), nullable
=False)
1141 num_items
= Column(Integer
, default
=0)
1143 # There are lots of different special types of collections in the pump.io API
1144 # for example: followers, following, inbox, outbox, etc. See type constants
1145 # below the fields on this model.
1146 type = Column(Unicode
, nullable
=False)
1149 location
= Column(Integer
, ForeignKey("core__locations.id"))
1150 get_location
= relationship("Location", lazy
="joined")
1152 # Cascade: Collections are owned by their creator. So do the full thing.
1153 get_actor
= relationship(User
,
1154 backref
=backref("collections",
1155 cascade
="all, delete-orphan"))
1157 UniqueConstraint("actor", "slug"),
1160 deletion_mode
= Base
.SOFT_DELETE
1162 # These are the types, It's strongly suggested if new ones are invented they
1163 # are prefixed to ensure they're unique from other types. Any types used in
1164 # the main mediagoblin should be prefixed "core-"
1165 INBOX_TYPE
= "core-inbox"
1166 OUTBOX_TYPE
= "core-outbox"
1167 FOLLOWER_TYPE
= "core-followers"
1168 FOLLOWING_TYPE
= "core-following"
1169 COMMENT_TYPE
= "core-comments"
1170 USER_DEFINED_TYPE
= "core-user-defined"
1172 def get_collection_items(self
, ascending
=False):
1173 #TODO, is this still needed with self.collection_items being available?
1174 order_col
= CollectionItem
.position
1176 order_col
= desc(order_col
)
1177 return CollectionItem
.query
.filter_by(
1178 collection
=self
.id).order_by(order_col
)
1181 safe_title
= self
.title
.encode('ascii', 'replace')
1182 return '<{classname} #{id}: {title} by {actor}>'.format(
1184 classname
=self
.__class
__.__name
__,
1188 def serialize(self
, request
):
1189 # Get all serialized output in a list
1190 items
= [i
.serialize(request
) for i
in self
.get_collection_items()]
1192 "totalItems": self
.num_items
,
1193 "url": self
.url_for_self(request
.urlgen
, qualified
=True),
1198 class CollectionItem(Base
, CollectionItemMixin
):
1199 __tablename__
= "core__collection_items"
1201 id = Column(Integer
, primary_key
=True)
1203 collection
= Column(Integer
, ForeignKey(Collection
.id), nullable
=False)
1204 note
= Column(UnicodeText
, nullable
=True)
1205 added
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.utcnow
)
1206 position
= Column(Integer
)
1207 # Cascade: CollectionItems are owned by their Collection. So do the full thing.
1208 in_collection
= relationship(Collection
,
1211 cascade
="all, delete-orphan"))
1213 # Link to the object (could be anything.
1216 ForeignKey(GenericModelReference
.id),
1220 object_helper
= relationship(
1221 GenericModelReference
,
1222 foreign_keys
=[object_id
]
1224 get_object
= association_proxy(
1227 creator
=GenericModelReference
.find_or_new
1231 UniqueConstraint('collection', 'object_id'),
1235 def dict_view(self
):
1236 """A dict like view on this object"""
1237 return DictReadAttrProxy(self
)
1240 return '<{classname} #{id}: Object {obj} in {collection}>'.format(
1242 classname
=self
.__class
__.__name
__,
1243 collection
=self
.collection
,
1244 obj
=self
.get_object()
1247 def serialize(self
, request
):
1248 return self
.get_object().serialize(request
)
1251 class ProcessingMetaData(Base
):
1252 __tablename__
= 'core__processing_metadata'
1254 id = Column(Integer
, primary_key
=True)
1255 media_entry_id
= Column(Integer
, ForeignKey(MediaEntry
.id), nullable
=False,
1257 media_entry
= relationship(MediaEntry
,
1258 backref
=backref('processing_metadata',
1259 cascade
='all, delete-orphan'))
1260 callback_url
= Column(Unicode
)
1263 def dict_view(self
):
1264 """A dict like view on this object"""
1265 return DictReadAttrProxy(self
)
1268 class CommentSubscription(Base
):
1269 __tablename__
= 'core__comment_subscriptions'
1270 id = Column(Integer
, primary_key
=True)
1272 created
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.utcnow
)
1274 media_entry_id
= Column(Integer
, ForeignKey(MediaEntry
.id), nullable
=False)
1275 media_entry
= relationship(MediaEntry
,
1276 backref
=backref('comment_subscriptions',
1277 cascade
='all, delete-orphan'))
1279 user_id
= Column(Integer
, ForeignKey(User
.id), nullable
=False)
1280 user
= relationship(User
,
1281 backref
=backref('comment_subscriptions',
1282 cascade
='all, delete-orphan'))
1284 notify
= Column(Boolean
, nullable
=False, default
=True)
1285 send_email
= Column(Boolean
, nullable
=False, default
=True)
1288 return ('<{classname} #{id}: {user} {media} notify: '
1289 '{notify} email: {email}>').format(
1291 classname
=self
.__class
__.__name
__,
1293 media
=self
.media_entry
,
1295 email
=self
.send_email
)
1298 class Notification(Base
):
1299 __tablename__
= 'core__notifications'
1300 id = Column(Integer
, primary_key
=True)
1302 object_id
= Column(Integer
, ForeignKey(GenericModelReference
.id))
1303 object_helper
= relationship(GenericModelReference
)
1304 obj
= association_proxy("object_helper", "get_object",
1305 creator
=GenericModelReference
.find_or_new
)
1307 created
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.utcnow
)
1308 user_id
= Column(Integer
, ForeignKey('core__users.id'), nullable
=False,
1310 seen
= Column(Boolean
, default
=lambda: False, index
=True)
1311 user
= relationship(
1313 backref
=backref('notifications', cascade
='all, delete-orphan'))
1316 return '<{klass} #{id}: {user}: {subject} ({seen})>'.format(
1318 klass
=self
.__class
__.__name
__,
1320 subject
=getattr(self
, 'subject', None),
1321 seen
='unseen' if not self
.seen
else 'seen')
1323 def __unicode__(self
):
1324 return u
'<{klass} #{id}: {user}: {subject} ({seen})>'.format(
1326 klass
=self
.__class
__.__name
__,
1328 subject
=getattr(self
, 'subject', None),
1329 seen
='unseen' if not self
.seen
else 'seen')
1333 Represents a report that someone might file against Media, Comments, etc.
1335 :keyword reporter_id Holds the id of the user who created
1336 the report, as an Integer column.
1337 :keyword report_content Hold the explanation left by the repor-
1338 -ter to indicate why they filed the
1339 report in the first place, as a
1341 :keyword reported_user_id Holds the id of the user who created
1342 the content which was reported, as
1344 :keyword created Holds a datetime column of when the re-
1346 :keyword resolver_id Holds the id of the moderator/admin who
1347 resolved the report.
1348 :keyword resolved Holds the DateTime object which descri-
1349 -bes when this report was resolved
1350 :keyword result Holds the UnicodeText column of the
1351 resolver's reasons for resolving
1352 the report this way. Some of this
1354 :keyword object_id Holds the ID of the GenericModelReference
1355 which points to the reported object.
1357 __tablename__
= 'core__reports'
1359 id = Column(Integer
, primary_key
=True)
1360 reporter_id
= Column(Integer
, ForeignKey(User
.id), nullable
=False)
1361 reporter
= relationship(
1363 backref
=backref("reports_filed_by",
1365 cascade
="all, delete-orphan"),
1366 primaryjoin
="User.id==Report.reporter_id")
1367 report_content
= Column(UnicodeText
)
1368 reported_user_id
= Column(Integer
, ForeignKey(User
.id), nullable
=False)
1369 reported_user
= relationship(
1371 backref
=backref("reports_filed_on",
1373 cascade
="all, delete-orphan"),
1374 primaryjoin
="User.id==Report.reported_user_id")
1375 created
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.utcnow
)
1376 resolver_id
= Column(Integer
, ForeignKey(User
.id))
1377 resolver
= relationship(
1379 backref
=backref("reports_resolved_by",
1381 cascade
="all, delete-orphan"),
1382 primaryjoin
="User.id==Report.resolver_id")
1384 resolved
= Column(DateTime
)
1385 result
= Column(UnicodeText
)
1387 object_id
= Column(Integer
, ForeignKey(GenericModelReference
.id), nullable
=True)
1388 object_helper
= relationship(GenericModelReference
)
1389 obj
= association_proxy("object_helper", "get_object",
1390 creator
=GenericModelReference
.find_or_new
)
1392 def is_archived_report(self
):
1393 return self
.resolved
is not None
1395 def is_comment_report(self
):
1396 if self
.object_id
is None:
1398 return isinstance(self
.obj(), TextComment
)
1400 def is_media_entry_report(self
):
1401 if self
.object_id
is None:
1403 return isinstance(self
.obj(), MediaEntry
)
1405 def archive(self
,resolver_id
, resolved
, result
):
1406 self
.resolver_id
= resolver_id
1407 self
.resolved
= resolved
1408 self
.result
= result
1410 class UserBan(Base
):
1412 Holds the information on a specific user's ban-state. As long as one of
1413 these is attached to a user, they are banned from accessing mediagoblin.
1414 When they try to log in, they are greeted with a page that tells them
1415 the reason why they are banned and when (if ever) the ban will be
1418 :keyword user_id Holds the id of the user this object is
1419 attached to. This is a one-to-one
1421 :keyword expiration_date Holds the date that the ban will be lifted.
1422 If this is null, the ban is permanent
1423 unless a moderator manually lifts it.
1424 :keyword reason Holds the reason why the user was banned.
1426 __tablename__
= 'core__user_bans'
1428 user_id
= Column(Integer
, ForeignKey(User
.id), nullable
=False,
1430 expiration_date
= Column(Date
)
1431 reason
= Column(UnicodeText
, nullable
=False)
1434 class Privilege(Base
):
1436 The Privilege table holds all of the different privileges a user can hold.
1437 If a user 'has' a privilege, the User object is in a relationship with the
1440 :keyword privilege_name Holds a unicode object that is the recognizable
1441 name of this privilege. This is the column
1442 used for identifying whether or not a user
1443 has a necessary privilege or not.
1446 __tablename__
= 'core__privileges'
1448 id = Column(Integer
, nullable
=False, primary_key
=True)
1449 privilege_name
= Column(Unicode
, nullable
=False, unique
=True)
1450 all_users
= relationship(
1452 backref
='all_privileges',
1453 secondary
="core__privileges_users")
1455 def __init__(self
, privilege_name
):
1457 Currently consructors are required for tables that are initialized thru
1458 the FOUNDATIONS system. This is because they need to be able to be con-
1459 -structed by a list object holding their arg*s
1461 self
.privilege_name
= privilege_name
1464 return "<Privilege %s>" % (self
.privilege_name
)
1467 class PrivilegeUserAssociation(Base
):
1469 This table holds the many-to-many relationship between User and Privilege
1472 __tablename__
= 'core__privileges_users'
1477 ForeignKey(User
.id),
1482 ForeignKey(Privilege
.id),
1485 class Generator(Base
):
1486 """ Information about what created an activity """
1487 __tablename__
= "core__generators"
1489 id = Column(Integer
, primary_key
=True)
1490 name
= Column(Unicode
, nullable
=False)
1491 published
= Column(DateTime
, default
=datetime
.datetime
.utcnow
)
1492 updated
= Column(DateTime
, default
=datetime
.datetime
.utcnow
)
1493 object_type
= Column(Unicode
, nullable
=False)
1495 deletion_mode
= Base
.SOFT_DELETE
1498 return "<{klass} {name}>".format(
1499 klass
=self
.__class
__.__name
__,
1503 def serialize(self
, request
):
1504 href
= request
.urlgen(
1505 "mediagoblin.api.object",
1506 object_type
=self
.object_type
,
1510 published
= UTC
.localize(self
.published
)
1511 updated
= UTC
.localize(self
.updated
)
1514 "displayName": self
.name
,
1515 "published": published
.isoformat(),
1516 "updated": updated
.isoformat(),
1517 "objectType": self
.object_type
,
1520 def unserialize(self
, data
):
1521 if "displayName" in data
:
1522 self
.name
= data
["displayName"]
1524 class Activity(Base
, ActivityMixin
):
1526 This holds all the metadata about an activity such as uploading an image,
1527 posting a comment, etc.
1529 __tablename__
= "core__activities"
1531 id = Column(Integer
, primary_key
=True)
1532 public_id
= Column(Unicode
, unique
=True)
1533 actor
= Column(Integer
,
1534 ForeignKey("core__users.id"),
1536 published
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.utcnow
)
1537 updated
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.utcnow
)
1539 verb
= Column(Unicode
, nullable
=False)
1540 content
= Column(Unicode
, nullable
=True)
1541 title
= Column(Unicode
, nullable
=True)
1542 generator
= Column(Integer
,
1543 ForeignKey("core__generators.id"),
1546 # Create the generic foreign keys for the object
1547 object_id
= Column(Integer
, ForeignKey(GenericModelReference
.id), nullable
=False)
1548 object_helper
= relationship(GenericModelReference
, foreign_keys
=[object_id
])
1549 object = association_proxy("object_helper", "get_object",
1550 creator
=GenericModelReference
.find_or_new
)
1552 # Create the generic foreign Key for the target
1553 target_id
= Column(Integer
, ForeignKey(GenericModelReference
.id), nullable
=True)
1554 target_helper
= relationship(GenericModelReference
, foreign_keys
=[target_id
])
1555 target
= association_proxy("target_helper", "get_object",
1556 creator
=GenericModelReference
.find_or_new
)
1558 get_actor
= relationship(User
,
1559 backref
=backref("activities",
1560 cascade
="all, delete-orphan"))
1561 get_generator
= relationship(Generator
)
1563 deletion_mode
= Base
.SOFT_DELETE
1566 if self
.content
is None:
1567 return "<{klass} verb:{verb}>".format(
1568 klass
=self
.__class
__.__name
__,
1572 return "<{klass} {content}>".format(
1573 klass
=self
.__class
__.__name
__,
1574 content
=self
.content
1577 def save(self
, set_updated
=True, *args
, **kwargs
):
1579 self
.updated
= datetime
.datetime
.now()
1580 super(Activity
, self
).save(*args
, **kwargs
)
1582 class Graveyard(Base
):
1583 """ Where models come to die """
1584 __tablename__
= "core__graveyard"
1586 id = Column(Integer
, primary_key
=True)
1587 public_id
= Column(Unicode
, nullable
=True, unique
=True)
1589 deleted
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.utcnow
)
1590 object_type
= Column(Unicode
, nullable
=False)
1592 # This could either be a deleted actor or a real actor, this must be
1593 # nullable as it we shouldn't have it set for deleted actor
1594 actor_id
= Column(Integer
, ForeignKey(GenericModelReference
.id))
1595 actor_helper
= relationship(GenericModelReference
)
1596 actor
= association_proxy("actor_helper", "get_object",
1597 creator
=GenericModelReference
.find_or_new
)
1600 return "<{klass} deleted {obj_type}>".format(
1601 klass
=type(self
).__name
__,
1602 obj_type
=self
.object_type
1605 def serialize(self
, request
):
1606 deleted
= UTC
.localize(self
.deleted
).isoformat()
1608 "id": self
.public_id
,
1609 "objectType": self
.object_type
,
1610 "published": deleted
,
1615 if self
.actor_id
is not None:
1616 context
["actor"] = self
.actor().serialize(request
)
1620 LocalUser
, RemoteUser
, User
, MediaEntry
, Tag
, MediaTag
, Comment
, TextComment
,
1621 Collection
, CollectionItem
, MediaFile
, FileKeynames
, MediaAttachmentFile
,
1622 ProcessingMetaData
, Notification
, Client
, CommentSubscription
, Report
,
1623 UserBan
, Privilege
, PrivilegeUserAssociation
, RequestToken
, AccessToken
,
1624 NonceTimestamp
, Activity
, Generator
, Location
, GenericModelReference
, Graveyard
]
1627 Foundations are the default rows that are created immediately after the tables
1628 are initialized. Each entry to this dictionary should be in the format of:
1629 ModelConstructorObject:List of Dictionaries
1630 (Each Dictionary represents a row on the Table to be created, containing each
1631 of the columns' names as a key string, and each of the columns' values as a
1634 ex. [NOTE THIS IS NOT BASED OFF OF OUR USER TABLE]
1635 user_foundations = [{'name':u'Joanna', 'age':24},
1636 {'name':u'Andrea', 'age':41}]
1638 FOUNDATIONS = {User:user_foundations}
1640 privilege_foundations
= [{'privilege_name':u
'admin'},
1641 {'privilege_name':u
'moderator'},
1642 {'privilege_name':u
'uploader'},
1643 {'privilege_name':u
'reporter'},
1644 {'privilege_name':u
'commenter'},
1645 {'privilege_name':u
'active'}]
1646 FOUNDATIONS
= {Privilege
:privilege_foundations
}
1648 ######################################################
1649 # Special, migrations-tracking table
1651 # Not listed in MODELS because this is special and not
1652 # really migrated, but used for migrations (for now)
1653 ######################################################
1655 class MigrationData(Base
):
1656 __tablename__
= "core__migrations"
1658 name
= Column(Unicode
, primary_key
=True)
1659 version
= Column(Integer
, nullable
=False, default
=0)
1661 ######################################################
1664 def show_table_init(engine_uri
):
1665 if engine_uri
is None:
1666 engine_uri
= 'sqlite:///:memory:'
1667 from sqlalchemy
import create_engine
1668 engine
= create_engine(engine_uri
, echo
=True)
1670 Base
.metadata
.create_all(engine
)
1673 if __name__
== '__main__':
1674 from sys
import argv
1680 show_table_init(uri
)