def send_notice(self): if self.post != None: film = list(self.post.related_film.all()[0:1]) film = film and film[0] person = list(self.post.related_person.all()[0:1]) person = person and person[0] object = film or person send([self.user], "useractivity_post", { 'post':self.post, 'link':self.post.get_absolute_url(), 'picture':object and object.get_absolute_image_url() or '', 'film':film, 'person':person, 'object':object, 'hashtags': self.get_hashtags(film), }) elif self.short_review != None: # TODO write notifications for wall posts! if self.short_review.object is not None and \ self.short_review.object.type == Object.TYPE_FILM: self.object = self.short_review.parent self.watching_object = self.short_review.parent send([self.user], "useractivity_short_review", { 'short_review':self.short_review, 'link':self.short_review.get_absolute_url(), 'picture':self.short_review.object.film.get_absolute_image_url(), 'film':self.short_review.object.film, 'hashtags': self.get_hashtags(self.short_review.object.film) }) elif self.comment != None: # for comments, create notification objects! Watching.create_notices(self)
def added_film_post_save(sender, instance, created, *args, **kw): if instance.image: d = get_image_dimensions(instance.image) if d is None or (d[0] > 71 or d[1] > 102): # Ignore all PIL errors, if image is broken # it just will not be added try: image = Image.open(instance.image.path) image = image.resize((71, 102), Image.ANTIALIAS) if image.mode != "RGB": image = image.convert("RGB") image.save(instance.image.path, "JPEG") except IOError: pass # if moderated send notification ... if instance.moderation_status != AddedFilm.STATUS_UNKNOWN \ and instance.user != instance.moderation_status_by: if notification: notification.send( [instance.user], "added_film_moderated", { "item": instance, "accepted": instance.moderation_status == AddedFilm.STATUS_ACCEPTED })
def compute_fast_recommendations_phase2(user_id, send_notice): from recom_helper import RecomHelper from film20.core.models import Recommendation from film20.showtimes.showtimes_helper import get_films from film20.showtimes.models import Channel from film20.showtimes.utils import get_today from itertools import chain import pytz helper = RecomHelper() user = User.objects.get(pk=user_id) profile = user.get_profile() if profile.country in settings.COUNTRIES_WITH_SHOWTIMES: if profile.timezone_id: timezone = pytz.timezone(profile.timezone_id) else: timezone = pytz.utc logger.warning("user %r has no timezone, using utc", user) today = get_today(timezone) theaters = Channel.objects.selected_by(user, Channel.TYPE_CINEMA) tv_channels = Channel.objects.selected_by(user, Channel.TYPE_TV_CHANNEL) for i in range(3): date = today + timedelta(days=i) for channels in (theaters, tv_channels): for film in get_films(date, channels): count_guessed_rate(user, film) if send_notice: notification.send([user], "recommendations_fast_calculated", {})
def send_recommendations_calculated_notices(): from film20.core.models import Profile for profile in Profile.objects.filter(recommendations_status=1, recommendations_notice_sent=0): notification.send([profile.user], "recommendations_calculated", {}) profile.recommendations_notice_sent = 1 profile.save()
def send_recommendations_calculated_notices(): from film20.core.models import Profile for profile in Profile.objects.filter(recommendations_status=1, recommendations_notice_sent=0): notification.send([profile.user], 'recommendations_calculated', {}) profile.recommendations_notice_sent = 1 profile.save()
def compute_fast_recommendations_phase2(user_id, send_notice): from recom_helper import RecomHelper from film20.core.models import Recommendation from film20.showtimes.showtimes_helper import get_films from film20.showtimes.models import Channel from film20.showtimes.utils import get_today from itertools import chain import pytz helper = RecomHelper() user = User.objects.get(pk=user_id) profile = user.get_profile() if profile.country in settings.COUNTRIES_WITH_SHOWTIMES: if profile.timezone_id: timezone = pytz.timezone(profile.timezone_id) else: timezone = pytz.utc logger.warning("user %r has no timezone, using utc", user) today = get_today(timezone) theaters = Channel.objects.selected_by(user, Channel.TYPE_CINEMA) tv_channels = Channel.objects.selected_by(user, Channel.TYPE_TV_CHANNEL) for i in range(3): date = today + timedelta(days=i) for channels in (theaters, tv_channels): for film in get_films(date, channels): count_guessed_rate(user, film) if send_notice: notification.send([user], 'recommendations_fast_calculated', {})
def send_notice(self): if self.post != None: film = list(self.post.related_film.all()[0:1]) film = film and film[0] person = list(self.post.related_person.all()[0:1]) person = person and person[0] object = film or person send([self.user], "useractivity_post", { 'post':self.post, 'link':self.post.get_absolute_url(), 'picture':object and object.get_absolute_image_url() or '', 'film':film, 'film_kind': gettext("TV series") if film and film.is_tv_series else gettext("film"), 'person':person, 'object':object, 'hashtags': self.get_hashtags(film), }) elif self.short_review != None: # TODO write notifications for wall posts! if self.short_review.object is not None and \ self.short_review.object.type == Object.TYPE_FILM: self.object = self.short_review.parent self.watching_object = self.short_review.parent send([self.user], "useractivity_short_review", { 'short_review':self.short_review, 'link':self.short_review.get_absolute_url(), 'picture':self.short_review.object.film.get_absolute_image_url(), 'film':self.short_review.object.film, 'hashtags': self.get_hashtags(self.short_review.object.film) }) elif self.comment != None: # for comments, create notification objects! Watching.create_notices(self)
def send_recommendations(self, user, type_label, date, days): from film20.showtimes.showtimes_helper import ScreeningSet cinemas = Channel.objects.selected_by(user, Channel.TYPE_CINEMA) tv = Channel.objects.selected_by(user, Channel.TYPE_TV_CHANNEL) to_date = date + datetime.timedelta(days=days) cinema_films = ScreeningSet( date, cinemas, user=user, days=days, without_unmatched=True).get_recommendations() tv_films = ScreeningSet(date, tv, user=user, days=days, without_unmatched=True).get_recommendations() if not cinema_films and not tv_films: logger.debug("no showtimes for %s found (at %s), skipping", user, user.get_profile().location) return def limit(films): out = [] for f in films: if f.on_wishlist and len( out ) < settings.WEEKLY_RECOMMENDATIONS_MAX_NUMBER_OF_FILMS: out.append(f) elif len( out) < settings.WEEKLY_RECOMMENDATIONS_NUMBER_OF_FILMS: out.append(f) else: break return out from film20.notification.models import send context = dict( cinema_films=limit(cinema_films), tv_films=limit(tv_films), tv_channels=tv, cinemas=cinemas, date=date, to_date=to_date, days=days, user=user, ) template = EmailTemplate.objects.get_template( 7 if self.opts.get('weekly') else 1) if template: logger.info("using template: %s" % template) context['template'] = template.generate(context) if not self.opts.get('test'): send([user], type_label, context, now=True) else: logger.info('test mode, not sending')
def test_notice(self): create_notice_type("test_notice", "Test Notice", "test notice", default=2) user, _ = User.objects.get_or_create( username='******', defaults=dict(email='*****@*****.**')) send([user], 'test_notice') self.assertTrue(any('Test Notice' in m.subject for m in mail.outbox))
def photo_post_save( sender, instance, created, *args, **kw ): # resize self image if created: image = Image.open( instance.image.path ) image.thumbnail( POSTER_DIMENSION, Image.ANTIALIAS ) if image.mode != "RGB": image = image.convert( "RGB" ) image.save( instance.image.path, "JPEG" ) if isinstance( instance.content_object, Film ) or \ isinstance( instance.content_object, Person ): # if accepted, save this photo as main if instance.moderation_status == ModeratedPhoto.STATUS_ACCEPTED: filename = "%s.jpg" % instance.content_object.permalink[:80] from film20.useractivity.models import UserActivity ua = UserActivity( user=instance.user, username=instance.user.username, activity_type = UserActivity.TYPE_POSTER, ) # in movie hires image is default ... if isinstance( instance.content_object, Film ): instance.content_object.hires_image.save( filename, instance.image ) ua.film=instance.content_object ua.film_title=instance.content_object.get_title() ua.film_permalink=instance.content_object.permalink ua.content = instance.content_object.hires_image else: instance.content_object.image.save( filename, instance.image ) # Save: # person name in object_title # person permalink in object_slug ua.person = instance.content_object ua.object_title = str( instance.content_object ) ua.object_slug = instance.content_object.permalink ua.content = instance.content_object.image ua.save() # if moderated send notification ... if instance.moderation_status != ModeratedPhoto.STATUS_UNKNOWN \ and instance.user != instance.moderation_status_by: if notification: notification.send( [ instance.user ], "photo_moderated", { "item": instance, "status": instance.moderation_status } ) else: raise NotImplementedError
def send_import_fail_notification(film_to_import, imdb_movie=None): if notification: if film_to_import.status == FilmToImport.ALREADY_IN_DB: film = imdb_movie_to_film(imdb_movie) else: film = None args = {"film_to_import": film_to_import, "film": film} notification.send([film_to_import.user], "film_import_failed", args)
def send_import_fail_notification( film_to_import, imdb_movie = None ): if notification: if film_to_import.status == FilmToImport.ALREADY_IN_DB: film = imdb_movie_to_film( imdb_movie ) else: film = None args = { "film_to_import": film_to_import, "film": film } notification.send( [ film_to_import.user ], "film_import_failed", args )
def send_recommendations(self, user, type_label, date, days): from film20.showtimes.showtimes_helper import ScreeningSet cinemas = Channel.objects.selected_by(user, Channel.TYPE_CINEMA) tv = Channel.objects.selected_by(user, Channel.TYPE_TV_CHANNEL) to_date = date + datetime.timedelta(days=days) cinema_films = ScreeningSet(date, cinemas, user=user, days=days, without_unmatched=True).get_recommendations() tv_films = ScreeningSet(date, tv, user=user, days=days, without_unmatched=True).get_recommendations() if not cinema_films and not tv_films: logger.debug("no showtimes for %s found (at %s), skipping", user, user.get_profile().location) return def limit(films): out = [] for f in films: if f.on_wishlist and len(out) < settings.WEEKLY_RECOMMENDATIONS_MAX_NUMBER_OF_FILMS: out.append(f) elif len(out) < settings.WEEKLY_RECOMMENDATIONS_NUMBER_OF_FILMS: out.append(f) else: break return out from film20.notification.models import send context = dict( cinema_films=limit(cinema_films), tv_films=limit(tv_films), tv_channels=tv, cinemas=cinemas, date=date, to_date=to_date, days=days, user=user, ) template = EmailTemplate.objects.get_template( 7 if self.opts.get( 'weekly' ) else 1 ) if template: logger.info( "using template: %s" % template ) context['template'] = template.generate( context ) if not self.opts.get('test'): send([user], type_label, context, now=True) else: logger.info('test mode, not sending')
def save(self, *args, **kw): logger.debug("saving") first_save = False if self.pk is None: first_save = True super(Followers, self).save(*args, **kw) # v hack for #FLM-1572 if first_save and self.status == Followers.FOLLOWING and self.to_user.username <> "blog": self.save_activity() notification.send( [self.to_user], "following", {"to_user": self.to_user, "from_user": self.from_user, "link": url_username_link(self.from_user)}, )
def save_model(self, request, obj, form, change): """ Saves the message for the recipient and looks in the form instance for other possible recipients. Prevents duplication by excludin the original recipient from the list of optional recipients. When changing an existing message and choosing optional recipients, the message is effectively resent to those users. """ obj.save() if notification: # Getting the appropriate notice labels for the sender and recipients. if obj.parent_msg is None: sender_label = 'messages_sent' recipients_label = 'messages_received' else: sender_label = 'messages_replied' recipients_label = 'messages_reply_received' # Notification for the sender. notification.send([obj.sender], sender_label, { 'message': obj, }) if form.cleaned_data['group'] == 'all': # send to all users recipients = User.objects.exclude(pk=obj.recipient.pk) else: # send to a group of users recipients = [] group = form.cleaned_data['group'] if group: group = Group.objects.get(pk=group) recipients.extend( list(group.user_set.exclude(pk=obj.recipient.pk))) # create messages for all found recipients for user in recipients: obj.pk = None obj.recipient = user obj.save() if notification: # Notification for the recipient. notification.send([user], recipients_label, { 'message': obj, })
def _sync_with_fb(cls, id): assoc = cls.objects.select_related().get(id=id) assoc.sync_with_fb() if assoc.fb_user_id: from film20.notification.models import send from film20.core.urlresolvers import reverse as abs_reverse friends = User.objs.active().facebook_friends(assoc.fb_user_id) send(friends, "friends_joined", { 'user': assoc.user, 'fb_user': assoc.fb_user, 'network': 'Facebook', 'profile_url': abs_reverse('show_profile', args=[assoc.user.username]), }) for friend in friends: assoc.user.followers.follow(friend)
def save(self, *args, **kw): logger.debug("saving") first_save = False if self.pk is None: first_save = True super(Followers, self).save(*args, **kw) # v hack for #FLM-1572 if first_save and self.status==Followers.FOLLOWING and self.to_user.username <> 'blog': self.save_activity() notification.send([self.to_user], "following", { 'to_user': self.to_user, 'from_user' : self.from_user, 'link' : url_username_link(self.from_user) } )
def save_model(self, request, obj, form, change): """ Saves the message for the recipient and looks in the form instance for other possible recipients. Prevents duplication by excludin the original recipient from the list of optional recipients. When changing an existing message and choosing optional recipients, the message is effectively resent to those users. """ obj.save() if notification: # Getting the appropriate notice labels for the sender and recipients. if obj.parent_msg is None: sender_label = 'messages_sent' recipients_label = 'messages_received' else: sender_label = 'messages_replied' recipients_label = 'messages_reply_received' # Notification for the sender. notification.send([obj.sender], sender_label, {'message': obj,}) if form.cleaned_data['group'] == 'all': # send to all users recipients = User.objects.exclude(pk=obj.recipient.pk) else: # send to a group of users recipients = [] group = form.cleaned_data['group'] if group: group = Group.objects.get(pk=group) recipients.extend( list(group.user_set.exclude(pk=obj.recipient.pk))) # create messages for all found recipients for user in recipients: obj.pk = None obj.recipient = user obj.save() if notification: # Notification for the recipient. notification.send([user], recipients_label, {'message' : obj,})
def added_film_post_save( sender, instance, created, *args, **kw ): if instance.image: d = get_image_dimensions( instance.image ) if d is None or ( d[0] > 71 or d[1] > 102 ): # Ignore all PIL errors, if image is broken # it just will not be added try: image = Image.open( instance.image.path ) image = image.resize( ( 71, 102 ), Image.ANTIALIAS ) if image.mode != "RGB": image = image.convert( "RGB" ) image.save( instance.image.path, "JPEG" ) except IOError: pass # if moderated send notification ... if instance.moderation_status != AddedFilm.STATUS_UNKNOWN \ and instance.user != instance.moderation_status_by: if notification: notification.send( [ instance.user ], "added_film_moderated", { "item": instance, "accepted": instance.moderation_status == AddedFilm.STATUS_ACCEPTED } )
def _sync_with_fb(cls, id): assoc = cls.objects.select_related().get(id=id) assoc.sync_with_fb() if assoc.fb_user_id: from film20.notification.models import send from film20.core.urlresolvers import reverse as abs_reverse friends = User.objs.active().facebook_friends(assoc.fb_user_id) send( friends, "friends_joined", { 'user': assoc.user, 'fb_user': assoc.fb_user, 'network': 'Facebook', 'profile_url': abs_reverse('show_profile', args=[assoc.user.username]), }) for friend in friends: assoc.user.followers.follow(friend)
def save(self, *args, **kw): email_confirmed = False username = self.cleaned_data["username"] email = self.cleaned_data.get("email") or "" password = self.cleaned_data.get("password1") tmp_username = self._tmp_username() if not tmp_username and self.request and self.request.unique_user.id: tmp_username = self.request.unique_user.username if tmp_username: match = re.match("(\w{3})-[0-9a-f]{20,26}$", tmp_username) match = match or re.match("(fb)-\d+", tmp_username) assert match # rename anonymouse user user = User.objects.get(username=tmp_username, is_active=False) user.is_active = True user.username = username user.email = email if password: user.set_password(password) user.save() profile = user.get_profile() profile.user = user profile.registration_source = match.group(1) profile.save() # update username in activities for activity in UserActivity.objects.filter(user=user): activity.username = user.username activity.save() if ( settings.RECOMMENDATIONS_ENGINE == "film20.new_recommendations.recommendations_engine" and Rating.get_user_ratings(user) > settings.RECOMMENDATIONS_MIN_VOTES_USER ): # recompute recommendations from film20.recommendations import engine engine.compute_user_features(user, True) ec = self.get_email_confirmation() if ec and ec.email_address.email == email: EmailConfirmation.objects.confirm_email(self.request.GET.get("confirmation_key")) email_confirmed = True else: # User.objects.create_user(username, email, **extra) user, created = User.objects.get_or_create(username=username, defaults={"email": email}) if created: if password: user.set_password(password) user.save() else: # user already exists, probably double form submission return user if email and not email_confirmed: add_email(user, email) defaults = {} if self.request and self.request.geo: latitude = self.request.geo.get("latitude") longitude = self.request.geo.get("longitude") country_code = self.request.geo.get("country_code") timezone = self.request.geo.get("timezone") if latitude and longitude: defaults["latitude"] = str(latitude) defaults["longitude"] = str(longitude) defaults["country"] = country_code defaults["timezone_id"] = timezone profile, created = Profile.objects.get_or_create(user=user, defaults=defaults) if not created: profile.__dict__.update(defaults) profile.save() from film20.notification import models as notification from film20.notification.models import NoticeType inform_friends = self.cleaned_data.get("inform_friends") if not inform_friends: # disable all USER_ACTIVITY notifications notice_types = NoticeType.objects.filter(type=NoticeType.TYPE_USER_ACTIVITY) for notice_type in notice_types: for medium in notification.NOTICE_MEDIA: if medium.supports(notice_type): medium.update_notification_setting(user, notice_type, False) if self.request.is_mobile: names = dict((v, k) for k, v in settings.USER_AGENTS) platform_name = names.get(self.request.platform, "") link = reverse("mobile_app") picture = None else: platform_name = "" link = reverse("main_page") picture = "/static/layout/logo.png" notification.send( [user], "useractivity_just_joined", { "user": user, "is_mobile": self.request.is_mobile, "platform": self.request.platform, "platform_name": platform_name, "link": link, "picture": picture, }, delay=30, ) return user
pass obj.tag = tag_b obj.save() # update object localized tag_list if isinstance(obj.object, ObjectLocalized): obj.object.tag_list = ', '.join([ tag.name for tag in Tag.objects.get_for_object(obj.object) ]) obj.object.save() # remove tag a tag_a.delete() # ... and commit transaction.commit() ctx['success'] = True ctx['message'] = _("Successfully renamed!") except Exception, e: transaction.rollback() ctx['message'] = _("Failed, an error occurred: %(error)s") % { 'error': e } print "sending notification to user %s" % user notification.send([user], "moderation_task_completed", ctx)
def send_notification( self ): if self.user != self.moderation_status_by and notification: notification.send( [ self.user ], "link_to_remove_moderated", { "item": self } )
def photo_post_save( sender, instance, created, *args, **kw ): # resize self image if created: image = Image.open( instance.image.path ) image.thumbnail( POSTER_DIMENSION, Image.ANTIALIAS ) if image.mode != "RGB": image = image.convert( "RGB" ) image.save( instance.image.path, "JPEG" ) if isinstance( instance.content_object, Film ) or \ isinstance( instance.content_object, Person ): # if accepted, save this photo as main if instance.moderation_status == ModeratedPhoto.STATUS_ACCEPTED: filename = "%s.jpg" % instance.content_object.permalink[:80] from film20.useractivity.models import UserActivity lang = getattr( instance, 'LANG', None if instance.in_all_languages else settings.LANGUAGE_CODE ) ua = UserActivity( user=instance.user, username=instance.user.username, activity_type = UserActivity.TYPE_POSTER, LANG = lang or settings.LANGUAGE_CODE, ) poster = Poster.objects.create( object=instance.content_object, image=instance.image, is_main=instance.is_main, LANG=lang ) # in movie hires image is default ... if isinstance( instance.content_object, Film ): #instance.content_object.hires_image.save( filename, instance.image ) ua.film=instance.content_object ua.film_title=instance.content_object.get_title() ua.film_permalink=instance.content_object.permalink ua.content = poster.image else: #instance.content_object.hires_image.save( filename, instance.image ) # Save: # person name in object_title # person permalink in object_slug ua.person = instance.content_object ua.object_title = str( instance.content_object ) ua.object_slug = instance.content_object.permalink ua.content = poster.image ua.save() # if moderated send notification ... if instance.moderation_status != ModeratedPhoto.STATUS_UNKNOWN \ and instance.user != instance.moderation_status_by: if notification: notification.send( [ instance.user ], "photo_moderated", { "item": instance, "status": instance.moderation_status } ) else: raise NotImplementedError
def test_notice(self): create_notice_type("test_notice", "Test Notice", "test notice", default=2) user, _ = User.objects.get_or_create(username='******', defaults=dict(email='*****@*****.**')) send([user], 'test_notice') self.assertTrue(any('Test Notice' in m.subject for m in mail.outbox))
ti = TaggedItem.objects.get( tag=tag_b, content_type=obj.content_type, object_id=obj.object_id ) ti.delete() except TaggedItem.DoesNotExist: pass obj.tag = tag_b obj.save() # update object localized tag_list if isinstance( obj.object, ObjectLocalized ): obj.object.tag_list = ', '.join( [ tag.name for tag in Tag.objects.get_for_object( obj.object ) ] ) obj.object.save() # remove tag a tag_a.delete() # ... and commit transaction.commit() ctx['success'] = True ctx['message'] = _( "Successfully renamed!" ) except Exception, e: transaction.rollback() ctx['message'] = _( "Failed, an error occurred: %(error)s" ) % { 'error': e } print "sending notification to user %s" % user notification.send( [ user ], "moderation_task_completed", ctx )
def run(pickle, unpickle, list, single_movie, idlist, cron_job, conntype, single_movie_title = ''): if unpickle: unpickle_movie(MOVIE_DIRECTORY) if list and pickle: movie_list = get_movie_list(MOVIE_LIST_FILE) for title in movie_list: movie = get_movie_by_title(title, conntype) save_movie_to_db(movie) pickle_movie(movie) if list: movie_list = get_movie_list(MOVIE_LIST_FILE) for title in movie_list: if title != "": movie = get_movie_by_title(title, conntype, auto=True) if movie: save_movie_to_db(movie) else: sys.exit() if single_movie: movie = get_movie_by_title(single_movie_title, conntype, auto=False) if movie: save_movie_to_db(movie) if single_movie and pickle: movie = get_movie_by_title(single_movie_title, conntype) if movie: save_movie_to_db(movie) pickle_movie(movie) if idlist: imdbids = get_ids(IDS_LIST_FILE) for imdbid in imdbids: if imdbid != "": movie = get_movie_by_id(imdbid, conntype) if movie: save_movie_to_db(movie) else: sys.exit() if cron_job: films_to_import = FilmToImport.objects.filter(imdb_id__isnull=False, is_imported=False, status=FilmToImport.ACCEPTED, \ attempts__lt = NUMBER_OF_ATTEMPTS) for film_to_import in films_to_import: try: movie = get_movie_by_id(film_to_import.imdb_id, conntype) if movie: saved_movie, status = save_movie_to_db(movie) if status == FilmToImport.ACCEPTED: if saved_movie: film_to_import.is_imported = True film_to_import.status = 1 film_to_import.attempts = film_to_import.attempts + 1 film_to_import.save() importedfilm = ImportedFilm(user=film_to_import.user, film=saved_movie) importedfilm.save() if notification: notification.send( [ importedfilm.user ], "film_imported", { "film": importedfilm } ) print "Imported: " + unicode(film_to_import.title) + "(" + unicode(film_to_import.imdb_url) + ")" else: film_to_import.status = 3 film_to_import.attempts = film_to_import.attempts + 1 film_to_import.save() send_import_fail_notification( film_to_import, movie ) else: film_to_import.attempts = film_to_import.attempts + 1 film_to_import.status = 4 film_to_import.save() send_import_fail_notification( film_to_import ) except Exception, e: import sys, traceback traceback.print_exc(file=sys.stdout) try: e.print_stack_trace() except Exception, e1: print "exception when printing stack trace!" try: print(e) print "FAILED to import: " + unicode(film_to_import.title) + "(" + unicode(film_to_import.imdb_url) + ")" except Exception, e: print "FAILED to import movie with IMDB code: " + unicode(film_to_import.imdb_url) print "Exception occured when exception handling:" print(e) film_to_import.attempts = film_to_import.attempts + 1 film_to_import.save() if film_to_import.attempts > NUMBER_OF_ATTEMPTS: film_to_import.status = 2 film_to_import.save() send_import_fail_notification( film_to_import )
def run(pickle, unpickle, list, single_movie, idlist, cron_job, conntype, single_movie_title=""): if unpickle: unpickle_movie(MOVIE_DIRECTORY) if list and pickle: movie_list = get_movie_list(MOVIE_LIST_FILE) for title in movie_list: movie = get_movie_by_title(title, conntype) save_movie_to_db(movie) pickle_movie(movie) if list: movie_list = get_movie_list(MOVIE_LIST_FILE) for title in movie_list: if title != "": movie = get_movie_by_title(title, conntype, auto=True) if movie: save_movie_to_db(movie) else: sys.exit() if single_movie: movie = get_movie_by_title(single_movie_title, conntype, auto=False) if movie: save_movie_to_db(movie) if single_movie and pickle: movie = get_movie_by_title(single_movie_title, conntype) if movie: save_movie_to_db(movie) pickle_movie(movie) if idlist: imdbids = get_ids(IDS_LIST_FILE) for imdbid in imdbids: if imdbid != "": movie = get_movie_by_id(imdbid, conntype) if movie: save_movie_to_db(movie) else: sys.exit() if cron_job: films_to_import = FilmToImport.objects.filter( imdb_id__isnull=False, is_imported=False, status=FilmToImport.ACCEPTED, attempts__lt=NUMBER_OF_ATTEMPTS ) for film_to_import in films_to_import: try: movie = get_movie_by_id(film_to_import.imdb_id, conntype) if movie: saved_movie, status = save_movie_to_db(movie) if status == FilmToImport.ACCEPTED: if saved_movie: film_to_import.is_imported = True film_to_import.status = 1 film_to_import.attempts = film_to_import.attempts + 1 film_to_import.save() importedfilm = ImportedFilm(user=film_to_import.user, film=saved_movie) importedfilm.save() if notification: notification.send([importedfilm.user], "film_imported", {"film": importedfilm}) print "Imported: " + unicode(film_to_import.title) + "(" + unicode( film_to_import.imdb_url ) + ")" else: film_to_import.status = 3 film_to_import.attempts = film_to_import.attempts + 1 film_to_import.save() send_import_fail_notification(film_to_import, movie) else: film_to_import.attempts = film_to_import.attempts + 1 film_to_import.status = 4 film_to_import.save() send_import_fail_notification(film_to_import) except Exception, e: import sys, traceback traceback.print_exc(file=sys.stdout) try: e.print_stack_trace() except Exception, e1: print "exception when printing stack trace!" try: print (e) print "FAILED to import: " + unicode(film_to_import.title) + "(" + unicode( film_to_import.imdb_url ) + ")" except Exception, e: print "FAILED to import movie with IMDB code: " + unicode(film_to_import.imdb_url) print "Exception occured when exception handling:" print (e) film_to_import.attempts = film_to_import.attempts + 1 film_to_import.save() if film_to_import.attempts > NUMBER_OF_ATTEMPTS: film_to_import.status = 2 film_to_import.save() send_import_fail_notification(film_to_import)