/
models.py
1428 lines (1208 loc) · 54.1 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import datetime
import itertools
import re
import urllib2
import mimetypes
import operator
import logging
import sys
import traceback
import warnings
import tagging
import tagging.models
import vidscraper
from bs4 import BeautifulSoup
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.comments.moderation import CommentModerator, moderator
from django.contrib.sites.models import Site
from django.contrib.contenttypes import generic
from django.core.exceptions import ValidationError
from django.core.mail import EmailMessage
from django.core.signals import request_finished
from django.core.validators import ipv4_re
from django.db import models
from django.template import Context, loader
from django.utils.html import escape as html_escape
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from haystack import connections, connection_router
from mptt.models import MPTTModel
from notification import models as notification
from slugify import slugify
from localtv import utils, settings as lsettings
from localtv.managers import SiteRelatedManager, VideoManager
from localtv.signals import post_video_from_vidscraper, submit_finished
from localtv.templatetags.filters import sanitize
VIDEO_SERVICE_REGEXES = (
('YouTube', r'http://gdata\.youtube\.com/feeds/'),
('YouTube', r'http://(www\.)?youtube\.com/'),
('blip.tv', r'http://(.+\.)?blip\.tv/'),
('Vimeo', r'http://(www\.)?vimeo\.com/'),
('Dailymotion', r'http://(www\.)?dailymotion\.com/rss'))
class Thumbnailable(models.Model):
"""
A type of Model that has thumbnails generated for it. Now that we're using
Daguerre for thumbnails, this is just for backwards compatibility.
"""
# we set this to "logo" for SiteSettings, 'icon' for WidgetSettings
thumbnail_attribute = 'thumbnail'
class Meta:
abstract = True
@property
def has_thumbnail(self):
warnings.warn("has_thumbnail is deprecated and will be removed in a "
"future version.", DeprecationWarning)
return bool(getattr(self, self.thumbnail_attribute))
@property
def thumbnail_path(self):
warnings.warn("thumbnail_path is deprecated and will be removed in a "
"future version.", DeprecationWarning)
thumb_file = getattr(self, self.thumbnail_attribute)
if thumb_file:
return thumb_file.name
else:
return ''
class SiteSettings(Thumbnailable):
"""
A model for storing Site-specific settings (feature switches, custom HTML
and CSS, etc) in the database rather than in settings files. Most of
these can thus be set by site admins rather than sysadmins. There are
also a few fields for storing site event state.
"""
thumbnail_attribute = 'logo'
#: Link to the Site these settings are for.
site = models.OneToOneField(Site)
## Site styles ##
#: Custom logo image for this site.
logo = models.ImageField(upload_to=utils.UploadTo('localtv/sitesettings/logo/%Y/%m/%d/'), blank=True)
#: Custom background image for this site.
background = models.ImageField(upload_to=utils.UploadTo('localtv/sitesettings/background/%Y/%m/%d/'),
blank=True)
#: Arbitrary custom css overrides.
css = models.TextField(blank=True)
## Custom HTML ##
#: Subheader for the site.
tagline = models.CharField(max_length=4096, blank=True)
#: Arbitrary custom HTML which (currently) is used as a site description
#: on the main page.
sidebar_html = models.TextField(blank=True)
#: Arbitrary custom HTML which displays in the footer of all non-admin pages.
footer_html = models.TextField(blank=True)
#: Arbitrary custom HTML which displays on the about page.
about_html = models.TextField(blank=True)
## Site permissions ##
#: A collection of Users who have administrative access to the site.
admins = models.ManyToManyField('auth.User', blank=True,
related_name='admin_for')
#: Whether or not the Submit Video button should display or not.
#: Doesn't affect whether videos can be submitted or not.
#: See http://bugzilla.pculture.org/show_bug.cgi?id=19809
display_submit_button = models.BooleanField(default=True)
#: Whether or not users need to log in to submit videos.
submission_requires_login = models.BooleanField(default=False)
#: Whether or not an email address needs to be given with an
#: unauthenticated video submission.
submission_requires_email = models.BooleanField(default=False)
## Feature switches ##
#: Whether playlist functionality is enabled.
playlists_enabled = models.IntegerField(default=1)
#: Whether the original publication date or date added to this site
#: should be used for sorting videos.
use_original_date = models.BooleanField(
default=True,
help_text="If set, use the original date the video was posted. "
"Otherwise, use the date the video was added to this site.")
#: Whether comments should be held for moderation.
screen_all_comments = models.BooleanField(
verbose_name='Hold comments for moderation',
default=True,
help_text="Hold all comments for moderation by default?")
#: Whether leaving a comment requires you to be logged in.
comments_required_login = models.BooleanField(
default=False,
verbose_name="Require Login",
help_text="If True, comments require the user to be logged in.")
## Tracking fields ##
#: Whether a user has elected to hide the "get started" section in
#: the admin interface.
hide_get_started = models.BooleanField(default=False)
objects = SiteRelatedManager()
def __unicode__(self):
return u'%s (%s)' % (self.site.name, self.site.domain)
def user_is_admin(self, user):
"""
Return True if the given User is an admin for this SiteSettings.
"""
if not user.is_authenticated() or not user.is_active:
return False
if user.is_superuser:
return True
return self.admins.filter(pk=user.pk).exists()
def should_show_dashboard(self):
"""Returns True for backwards-compatibility."""
warnings.warn("should_show_dashboard is deprecated and will be "
"removed in a future version.", DeprecationWarning)
return True
class WidgetSettingsManager(SiteRelatedManager):
def _new_entry(self, site, using):
ws = super(WidgetSettingsManager, self)._new_entry(site, using)
try:
site_settings = SiteSettings.objects.get_cached(site, using)
except SiteSettings.DoesNotExist:
pass
else:
if site_settings.logo:
site_settings.logo.open()
ws.icon = site_settings.logo
ws.save()
return ws
class WidgetSettings(Thumbnailable):
"""
A Model which represents the options for controlling the widget creator.
"""
thumbnail_attribute = 'icon'
site = models.OneToOneField(Site)
title = models.CharField(max_length=250, blank=True)
title_editable = models.BooleanField(default=True)
icon = models.ImageField(upload_to=utils.UploadTo('localtv/widgetsettings/icon/%Y/%m/%d/'), blank=True)
icon_editable = models.BooleanField(default=False)
css = models.FileField(upload_to=utils.UploadTo('localtv/widgetsettings/css/%Y/%m/%d/'), blank=True)
css_editable = models.BooleanField(default=False)
bg_color = models.CharField(max_length=20, blank=True)
bg_color_editable = models.BooleanField(default=False)
text_color = models.CharField(max_length=20, blank=True)
text_color_editable = models.BooleanField(default=False)
border_color = models.CharField(max_length=20, blank=True)
border_color_editable = models.BooleanField(default=False)
objects = WidgetSettingsManager()
def get_title_or_reasonable_default(self):
# Is the title worth using? If so, use that.
use_title = True
if self.title.endswith('example.com'):
use_title = False
if not self.title:
use_title = False
# Okay, so either we return the title, or a sensible default
if use_title:
return html_escape(self.title)
return self.generate_reasonable_default_title()
def generate_reasonable_default_title(self):
prefix = 'Watch Videos on %s'
# Now, work on calculating what goes at the end.
site = Site.objects.get_current()
# The default suffix is a self-link. If the site name and
# site domain are plausible, do that.
if ((site.name and site.name.lower() != 'example.com') and
(site.domain and site.domain.lower() != 'example.com')):
suffix = '<a href="http://%s/">%s</a>' % (
site.domain, html_escape(site.name))
# First, we try the site name, if that's a nice string.
elif site.name and site.name.lower() != 'example.com':
suffix = site.name
# Else, we try the site domain, if that's not example.com
elif site.domain.lower() != 'example.com':
suffix = site.domain
else:
suffix = 'our video site'
return prefix % suffix
class Source(Thumbnailable):
"""
An abstract base class to represent things which are sources of multiple
videos. Current subclasses are Feed and SavedSearch.
"""
id = models.AutoField(primary_key=True)
site = models.ForeignKey(Site)
thumbnail = models.ImageField(upload_to=utils.UploadTo('localtv/source/thumbnail/%Y/%m/%d/'),
blank=True)
auto_approve = models.BooleanField(default=False)
auto_update = models.BooleanField(default=True,
help_text=_("If selected, new videos will"
" automatically be imported "
"from this source."))
user = models.ForeignKey('auth.User', null=True, blank=True)
auto_categories = models.ManyToManyField("Category", blank=True)
auto_authors = models.ManyToManyField("auth.User", blank=True,
related_name='auto_%(class)s_set')
class Meta:
abstract = True
def update(self, video_iter, source_import, clear_rejected=False):
"""
Imports videos from a feed/search. `videos` is an iterable which
returns :class:`vidscraper.videos.Video` objects. We use
:method:`.Video.from_vidscraper_video` to map the Vidscraper fields to
Video attributes.
If ``clear_rejected`` is ``True``, rejected versions of videos that are
found in the ``video_iter`` will be deleted and re-imported.
"""
author_pks = list(self.auto_authors.values_list('pk', flat=True))
category_pks = list(self.auto_categories.values_list('pk', flat=True))
import_opts = source_import.__class__._meta
from localtv.tasks import video_from_vidscraper_video, mark_import_pending
total_videos = 0
try:
for vidscraper_video in video_iter:
total_videos += 1
try:
video_from_vidscraper_video.delay(
vidscraper_video.serialize(),
site_pk=self.site_id,
import_app_label=import_opts.app_label,
import_model=import_opts.module_name,
import_pk=source_import.pk,
status=Video.PENDING,
author_pks=author_pks,
category_pks=category_pks,
clear_rejected=clear_rejected)
except Exception:
source_import.handle_error(
'Import task creation failed for %r' % (
vidscraper_video.url,),
is_skip=True,
with_exception=True)
except Exception:
source_import.fail(with_exception=True)
return
source_import.__class__._default_manager.filter(
pk=source_import.pk
).update(
total_videos=total_videos
)
mark_import_pending.delay(import_app_label=import_opts.app_label,
import_model=import_opts.module_name,
import_pk=source_import.pk)
class Feed(Source):
"""
Feed to pull videos in from.
If the same feed is used on two different sites, they will require two
separate entries here.
Fields:
- feed_url: The location of this field
- site: which site this feed belongs to
- name: human readable name for this feed
- webpage: webpage that this feed\'s content is associated with
- description: human readable description of this item
- last_updated: last time we ran self.update_items()
- when_submitted: when this feed was first registered on this site
- status: one of Feed.STATUS_CHOICES
- etag: used to see whether or not the feed has changed since our last
update.
- auto_approve: whether or not to set all videos in this feed to approved
during the import process
- user: a user that submitted this feed, if any
- auto_categories: categories that are automatically applied to videos on
import
- auto_authors: authors that are automatically applied to videos on
import
"""
INACTIVE = 0
ACTIVE = 1
STATUS_CHOICES = (
(INACTIVE, _(u'Inactive')),
(ACTIVE, _(u'Active')),
)
feed_url = models.URLField(verify_exists=False)
name = models.CharField(max_length=250)
webpage = models.URLField(verify_exists=False, blank=True)
description = models.TextField(blank=True)
last_updated = models.DateTimeField()
when_submitted = models.DateTimeField(auto_now_add=True)
etag = models.CharField(max_length=250, blank=True)
calculated_source_type = models.CharField(max_length=255, blank=True, default='')
status = models.IntegerField(choices=STATUS_CHOICES, default=INACTIVE)
class Meta:
unique_together = (
('feed_url', 'site'))
get_latest_by = 'last_updated'
def __unicode__(self):
return self.name
@models.permalink
def get_absolute_url(self):
return ('localtv_list_feed', [self.pk])
def update(self, **kwargs):
"""
Fetch and import new videos from this feed.
"""
try:
FeedImport.objects.get(source=self,
status=FeedImport.STARTED)
except FeedImport.DoesNotExist:
pass
else:
logging.info('Skipping import of %s: already in progress' % self)
return
feed_import = FeedImport.objects.create(source=self,
auto_approve=self.auto_approve)
video_iter = vidscraper.auto_feed(
self.feed_url,
max_results=None if self.status == self.INACTIVE else 100,
api_keys=lsettings.API_KEYS,
)
try:
video_iter.load()
except Exception:
feed_import.fail("Data loading failed for {source}",
with_exception=True)
return
self.etag = getattr(video_iter, 'etag', None) or ''
self.last_updated = datetime.datetime.now()
if self.status == self.INACTIVE:
# If these fields have already been changed, don't
# override those changes. Don't unset the name field
# if no further data is available.
if self.name == self.feed_url:
self.name = video_iter.title or self.name
if not self.webpage:
self.webpage = video_iter.webpage or ''
if not self.description:
self.description = video_iter.description or ''
self.save()
super(Feed, self).update(video_iter, source_import=feed_import,
**kwargs)
def source_type(self):
return self.calculated_source_type
def _calculate_source_type(self):
video_service = self.video_service()
if video_service is None:
return u'Feed'
else:
return u'User: %s' % video_service
def video_service(self):
for service, regexp in VIDEO_SERVICE_REGEXES:
if re.search(regexp, self.feed_url, re.I):
return service
def pre_save_set_calculated_source_type(instance, **kwargs):
# Always save the calculated_source_type
instance.calculated_source_type = instance._calculate_source_type()
# Plus, if the name changed, we have to recalculate all the Videos that depend on us.
try:
v = Feed.objects.get(id=instance.id)
except Feed.DoesNotExist:
return instance
if v.name != instance.name:
# recalculate all the sad little videos' calculated_source_type
for vid in instance.video_set.all():
vid.save()
models.signals.pre_save.connect(pre_save_set_calculated_source_type,
sender=Feed)
class Category(MPTTModel):
"""
A category for videos to be contained in.
Categories and tags aren't too different functionally, but categories are
more strict as they can't be defined by visitors. Categories can also be
hierarchical.
Fields:
- site: A link to the django.contrib.sites.models.Site object this object
is bound to
- name: Name of this category
- slug: a slugified verison of the name, used to create more friendly URLs
- logo: An image to associate with this category
- description: human readable description of this item
- parent: Reference to another Category. Allows you to have heirarchical
categories.
"""
site = models.ForeignKey(Site)
name = models.CharField(
max_length=80, verbose_name='Category Name',
help_text=_("The name is used to identify the category almost "
"everywhere; for example, under a video or in a "
"category widget."))
slug = models.SlugField(
verbose_name='Category Slug',
help_text=_("The \"slug\" is the URL-friendly version of the name. It "
"is usually lower-case and contains only letters, numbers "
"and hyphens."))
logo = models.ImageField(
upload_to=utils.UploadTo('localtv/category/logo/%Y/%m/%d/'),
blank=True,
verbose_name='Thumbnail/Logo',
help_text=_("Optional. For example: a leaf for 'environment' or the "
"logo of a university department."))
description = models.TextField(
blank=True, verbose_name='Description (HTML)',
help_text=_("Optional. The description is not prominent by default, but"
" some themes may show it."))
parent = models.ForeignKey(
'self', blank=True, null=True,
related_name='child_set',
verbose_name='Category Parent',
help_text=_("Categories, unlike tags, can have a hierarchy."))
class MPTTMeta:
order_insertion_by = ['name']
class Meta:
unique_together = (
('slug', 'site'),
('name', 'site'))
def __unicode__(self):
return self.name
def dashes(self):
"""
Returns a string of em dashes equal to the :class:`Category`\ 's
level. This is used to indent the category name in the admin
templates.
"""
return mark_safe('—' * self.level)
@models.permalink
def get_absolute_url(self):
return ('localtv_category', [self.slug])
def approved_set(self):
"""
Returns active videos for the category and its subcategories, ordered
by decreasing best date.
"""
opts = self._mptt_meta
lookups = {
'status': Video.ACTIVE,
'categories__left__gte': getattr(self, opts.left_attr),
'categories__left__lte': getattr(self, opts.right_attr),
'categories__tree_id': getattr(self, opts.tree_id_attr)
}
lookups = self._tree_manager._translate_lookups(**lookups)
return Video.objects.filter(**lookups).distinct()
approved_set = property(approved_set)
def unique_error_message(self, model_class, unique_check):
return 'Category with this %s already exists.' % (
unique_check[0],)
class SavedSearch(Source):
"""
A set of keywords to regularly pull in new videos from.
There's an administrative interface for doing "live searches"
Fields:
- site: site this savedsearch applies to
- query_string: a whitespace-separated list of words to search for. Words
starting with a dash will be processed as negative query terms
- when_created: date and time that this search was saved.
"""
query_string = models.TextField()
when_created = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.query_string
def update(self, **kwargs):
"""
Fetch and import new videos from this search.
"""
try:
SearchImport.objects.get(source=self,
status=SearchImport.STARTED)
except SearchImport.DoesNotExist:
pass
else:
logging.info('Skipping import of %s: already in progress' % self)
return
search_import = SearchImport.objects.create(
source=self,
auto_approve=self.auto_approve
)
searches = vidscraper.auto_search(
self.query_string,
max_results=100,
api_keys=lsettings.API_KEYS,
)
video_iters = []
for video_iter in searches:
try:
video_iter.load()
except Exception:
search_import.handle_error(u'Skipping import of search results '
u'from %s' % video_iter.__class__.__name__,
with_exception=True)
continue
video_iters.append(video_iter)
if video_iters:
super(SavedSearch, self).update(itertools.chain(*video_iters),
source_import=search_import,
**kwargs)
else:
# Mark the import as failed if none of the searches could load.
search_import.fail("All searches failed for {source}",
with_exception=False)
def source_type(self):
return u'Search'
class SourceImportIndex(models.Model):
video = models.OneToOneField('Video', unique=True)
index = models.PositiveIntegerField(blank=True, null=True)
class Meta:
abstract = True
class FeedImportIndex(SourceImportIndex):
source_import = models.ForeignKey('FeedImport', related_name='indexes')
class SearchImportIndex(SourceImportIndex):
source_import = models.ForeignKey('SearchImport', related_name='indexes')
class SourceImportError(models.Model):
message = models.TextField()
traceback = models.TextField(blank=True)
is_skip = models.BooleanField(help_text="Whether this error represents a "
"video that was skipped.")
datetime = models.DateTimeField(auto_now_add=True)
class Meta:
abstract = True
class FeedImportError(SourceImportError):
source_import = models.ForeignKey('FeedImport', related_name='errors')
class SearchImportError(SourceImportError):
source_import = models.ForeignKey('SearchImport', related_name='errors')
class SourceImport(models.Model):
STARTED = 'started'
PENDING = 'pending'
COMPLETE = 'complete'
FAILED = 'failed'
STATUS_CHOICES = (
(STARTED, _('Started')),
(PENDING, _('Pending haystack updates')),
(COMPLETE, _('Complete')),
(FAILED, _('Failed'))
)
start = models.DateTimeField(auto_now_add=True)
last_activity = models.DateTimeField(blank=True, null=True)
total_videos = models.PositiveIntegerField(blank=True, null=True)
videos_imported = models.PositiveIntegerField(default=0)
videos_skipped = models.PositiveIntegerField(default=0)
#: Caches the auto_approve of the search on the import, so that the imported
#: videos can be approved en masse at the end of the import based on the
#: settings at the beginning of the import.
auto_approve = models.BooleanField()
status = models.CharField(max_length=10, choices=STATUS_CHOICES,
default=STARTED)
class Meta:
get_latest_by = 'start'
ordering = ['-start']
abstract = True
def is_running(self):
"""
Returns True if the SourceImport is currently running.
"""
return self.status in (self.STARTED, self.PENDING)
def set_video_source(self, video):
"""
Sets the value of the correct field on the ``video`` to mark it as
having the same source as this import. Must be implemented by
subclasses.
"""
raise NotImplementedError
def get_videos(self):
raise NotImplementedError
def handle_error(self, message, is_skip=False, with_exception=False):
"""
Logs the error with the default logger and to the database.
:param message: A human-friendly description of the error that does
not contain sensitive information.
:param is_skip: ``True`` if the error results in a video being skipped.
Default: False.
:param with_exception: ``True`` if exception information should be
recorded. Default: False.
:param using: The database to use. Default: 'default'.
"""
if with_exception:
exc_info = sys.exc_info()
logging.warn(message, exc_info=exc_info)
tb = ''.join(traceback.format_exception(*exc_info))
else:
logging.warn(message)
tb = ''
self.errors.create(message=message,
source_import=self,
traceback=tb,
is_skip=is_skip)
if is_skip:
self.__class__._default_manager.filter(pk=self.pk
).update(videos_skipped=models.F('videos_skipped') + 1)
def get_index_creation_kwargs(self, video, vidscraper_video):
return {
'source_import': self,
'video': video,
'index': vidscraper_video.index
}
def handle_video(self, video, vidscraper_video):
"""
Creates an index instance connecting the video to this import.
:param video: The :class:`Video` instance which was imported.
:param vidscraper_video: The original video from :mod:`vidscraper`.
:param using: The database alias to use. Default: 'default'
"""
self.indexes.create(
**self.get_index_creation_kwargs(video, vidscraper_video))
self.__class__._default_manager.filter(pk=self.pk
).update(videos_imported=models.F('videos_imported') + 1)
def fail(self, message="Import failed for {source}", with_exception=False):
"""
Mark an import as failed, along with some post-fail cleanup.
"""
self.status = self.FAILED
self.last_activity = datetime.datetime.now()
self.save()
self.handle_error(message.format(source=self.source),
with_exception=with_exception)
self.get_videos().delete()
class FeedImport(SourceImport):
source = models.ForeignKey(Feed, related_name='imports')
def set_video_source(self, video):
video.feed_id = self.source_id
def get_videos(self):
return Video.objects.filter(feedimportindex__source_import=self)
class SearchImport(SourceImport):
source = models.ForeignKey(SavedSearch, related_name='imports')
def set_video_source(self, video):
video.search_id = self.source_id
def get_videos(self):
return Video.objects.filter(searchimportindex__source_import=self)
class Video(Thumbnailable):
"""
Fields:
- name: Name of this video
- site: Site this video is attached to
- description: Video description
- tags: A list of Tag objects associated with this item
- categories: Similar to Tags
- authors: the person/people responsible for this video
- file_url: The file this object points to (if any) ... if not
provided, at minimum we need the embed_code for the item.
- file_url_length: size of the file, in bytes
- file_url_mimetype: mimetype of the file
- when_submitted: When this item was first entered into the
database
- when_approved: When this item was marked to appear publicly on
the site
- when_published: When this file was published at its original
source (if known)
- last_featured: last time this item was featured.
- status: one of Video.STATUS_CHOICES
- feed: which feed this item came from (if any)
- website_url: The page that this item is associated with.
- embed_code: code used to embed this item.
- flash_enclosure_url: Crappy enclosure link that doesn't
actually point to a url.. the kind crappy flash video sites
give out when they don't actually want their enclosures to
point to video files.
- guid: data used to identify this video
- thumbnail_url: url to the thumbnail, if such a thing exists
- user: if not None, the user who submitted this video
- search: if not None, the SavedSearch from which this video came
- video_service_user: if not blank, the username of the user on the video
service who owns this video. We can figure out the service from the
website_url.
- contact: a free-text field for anonymous users to specify some contact
info
- notes: a free-text field to add notes about the video
"""
UNAPPROVED = 0
ACTIVE = 1
REJECTED = 2
PENDING = 3
STATUS_CHOICES = (
(UNAPPROVED, _(u'Unapproved')),
(ACTIVE, _(u'Active')),
(REJECTED, _(u'Rejected')),
(PENDING, _(u'Waiting on import to finish')),
)
site = models.ForeignKey(Site)
name = models.CharField(verbose_name="Video Name", max_length=250)
description = models.TextField(verbose_name="Video Description (optional)",
blank=True)
thumbnail_url = models.URLField(verbose_name="Thumbnail URL (optional)",
verify_exists=False, blank=True,
max_length=400)
thumbnail = models.ImageField(upload_to=utils.UploadTo('localtv/video/thumbnail/%Y/%m/%d/'),
blank=True)
categories = models.ManyToManyField(Category, blank=True)
authors = models.ManyToManyField('auth.User', blank=True,
related_name='authored_set')
file_url = models.URLField(verify_exists=False, blank=True,
max_length=2048)
file_url_length = models.IntegerField(null=True, blank=True)
file_url_mimetype = models.CharField(max_length=60, blank=True)
when_modified = models.DateTimeField(auto_now=True,
db_index=True,
default=datetime.datetime.now)
when_submitted = models.DateTimeField(auto_now_add=True)
when_approved = models.DateTimeField(null=True, blank=True)
when_published = models.DateTimeField(null=True, blank=True)
last_featured = models.DateTimeField(null=True, blank=True)
status = models.IntegerField(choices=STATUS_CHOICES, default=UNAPPROVED)
feed = models.ForeignKey(Feed, null=True, blank=True)
website_url = models.URLField(
verbose_name='Original Video Page URL (optional)',
max_length=2048,
verify_exists=False,
blank=True)
embed_code = models.TextField(verbose_name="Video <embed> code", blank=True)
flash_enclosure_url = models.URLField(verify_exists=False, max_length=2048,
blank=True)
guid = models.CharField(max_length=250, blank=True)
user = models.ForeignKey('auth.User', null=True, blank=True)
search = models.ForeignKey(SavedSearch, null=True, blank=True)
video_service_user = models.CharField(max_length=250, blank=True)
video_service_url = models.URLField(verify_exists=False, blank=True)
contact = models.CharField(verbose_name='Email (optional)', max_length=250,
blank=True)
notes = models.TextField(verbose_name='Notes (optional)', blank=True)
calculated_source_type = models.CharField(max_length=255, blank=True, default='')
objects = VideoManager()
taggeditem_set = generic.GenericRelation(tagging.models.TaggedItem,
content_type_field='content_type',
object_id_field='object_id')
class Meta:
ordering = ['-when_submitted']
get_latest_by = 'when_modified'
def __unicode__(self):
return self.name
def clean(self):
# clean is always run during ModelForm cleaning. If a model form is in
# play, rejected videos don't matter; the submission of that form
# should be considered valid. During automated imports, rejected
# videos are not excluded.
self._check_for_duplicates(exclude_rejected=True)
def _check_for_duplicates(self, exclude_rejected=True):
if not self.embed_code and not self.file_url:
raise ValidationError("Video has no embed code or file url.")
qs = Video.objects.filter(site=self.site_id)
if exclude_rejected:
qs = qs.exclude(status=Video.REJECTED)
if self.pk is not None:
qs = qs.exclude(pk=self.pk)
if self.guid and qs.filter(guid=self.guid).exists():
raise ValidationError("Another video with the same guid "
"already exists.")
if (self.website_url and
qs.filter(website_url=self.website_url).exists()):
raise ValidationError("Another video with the same website url "
"already exists.")
if self.file_url and qs.filter(file_url=self.file_url).exists():
raise ValidationError("Another video with the same file url "
"already exists.")
def clear_rejected_duplicates(self):
"""
Deletes rejected copies of this video based on the file_url,
website_url, and guid fields.
"""
if not any((self.website_url, self.file_url, self.guid)):
return
q_filter = models.Q()
if self.website_url:
q_filter |= models.Q(website_url=self.website_url)
if self.file_url:
q_filter |= models.Q(file_url=self.file_url)
if self.guid:
q_filter |= models.Q(guid=self.guid)
qs = Video.objects.filter(
site=self.site_id,
status=Video.REJECTED).filter(q_filter)
qs.delete()
@models.permalink
def get_absolute_url(self):
return ('localtv_view_video', (),
{'video_id': self.id,
'slug': slugify(self.name)[:30]})
def save(self, **kwargs):
"""
Adds support for an ```update_index`` kwarg, defaulting to ``True``.
If this kwarg is ``False``, then no index updates will be run by the
search index.
"""
# This actually relies on logic in
# :meth:`QueuedSearchIndex._enqueue_instance`
self._update_index = kwargs.pop('update_index', True)
super(Video, self).save(**kwargs)
save.alters_data = True
@classmethod
def from_vidscraper_video(cls, video, status=None, commit=True,
source_import=None, site_pk=None, authors=None,
categories=None, update_index=True):
"""
Builds a :class:`Video` instance from a
:class:`vidscraper.videos.Video` instance. If `commit` is False,
the :class:`Video` will not be saved, and the created instance will have
a `save_m2m()` method that must be called after you call `save()`.
"""
video_file = video.get_file()
if video_file and video_file.expires is None:
file_url = video_file.url
else:
file_url = None
if status is None:
status = cls.UNAPPROVED
if site_pk is None:
site_pk = settings.SITE_ID
now = datetime.datetime.now()
instance = cls(
guid=video.guid or '',
name=video.title or '',
description=video.description or '',
website_url=video.link or '',
when_published=video.publish_datetime,
file_url=file_url or '',