def save(self, profile_callback=None): username = self.cleaned_data['username'] new_password = self.cleaned_data.get('new_password', None) old_password = self.cleaned_data.get('old_password', None) email = self.cleaned_data.get('email', None) custom_css = self.cleaned_data.get('custom_css', None) custom_js = self.cleaned_data.get('custom_js', None) if username and self.user.username != username: change_password(self.user, self.user.username, username) self.user.username = username self.user.save() social_profile = MSocialProfile.get_user(self.user.pk) social_profile.username = username social_profile.save() if self.user.email != email: self.user.email = email self.user.save() sp = MSocialProfile.get_user(self.user.pk) sp.email = email sp.save() if old_password or new_password: change_password(self.user, old_password, new_password) MCustomStyling.save_user(self.user.pk, custom_css, custom_js)
def profile(request): user = get_user(request.user) user_id = request.GET.get('user_id', user.pk) include_activities_html = request.REQUEST.get('include_activities_html', None) user_profile = MSocialProfile.get_user(user_id) user_profile.count_follows() user_profile = user_profile.to_json(include_follows=True, common_follows_with_user=user.pk) profile_ids = set(user_profile['followers_youknow'] + user_profile['followers_everybody'] + user_profile['following_youknow'] + user_profile['following_everybody']) profiles = MSocialProfile.profiles(profile_ids) activities, _ = MActivity.user(user_id, page=1, public=True) logging.user(request, "~BB~FRLoading social profile: %s" % user_profile['username']) payload = { 'user_profile': user_profile, # XXX TODO: Remove following 4 vestigial params. 'followers_youknow': user_profile['followers_youknow'], 'followers_everybody': user_profile['followers_everybody'], 'following_youknow': user_profile['following_youknow'], 'following_everybody': user_profile['following_everybody'], 'profiles': dict([(p.user_id, p.to_json(compact=True)) for p in profiles]), 'activities': activities, } if include_activities_html: payload['activities_html'] = render_to_string('reader/activities_module.xhtml', { 'activities': activities, 'username': user_profile['username'], 'public': True, }) return payload
def unfollow(request): profile = MSocialProfile.get_user(request.user.pk) user_id = request.POST['user_id'] try: unfollow_user_id = int(user_id) except ValueError: try: unfollow_user_id = int(user_id.replace('social:', '')) unfollow_profile = MSocialProfile.get_user(unfollow_user_id) except (ValueError, MSocialProfile.DoesNotExist): unfollow_username = user_id.replace('social:', '') try: unfollow_profile = MSocialProfile.objects.get(username=unfollow_username) except MSocialProfile.DoesNotExist: raise Http404 unfollow_user_id = unfollow_profile.user_id profile.unfollow_user(unfollow_user_id) unfollow_profile = MSocialProfile.get_user(unfollow_user_id) logging.user(request, "~BB~FRUnfollowing: %s" % unfollow_profile.username) return { 'user_profile': profile.to_json(include_follows=True), 'unfollow_profile': unfollow_profile.to_json(common_follows_with_user=request.user.pk), }
def follow(request): profile = MSocialProfile.get_user(request.user.pk) user_id = request.POST['user_id'] try: follow_user_id = int(user_id) except ValueError: try: follow_user_id = int(user_id.replace('social:', '')) follow_profile = MSocialProfile.get_user(follow_user_id) except (ValueError, MSocialProfile.DoesNotExist): follow_username = user_id.replace('social:', '') try: follow_profile = MSocialProfile.objects.get(username=follow_username) except MSocialProfile.DoesNotExist: raise Http404 follow_user_id = follow_profile.user_id profile.follow_user(follow_user_id) follow_profile = MSocialProfile.get_user(follow_user_id) social_params = { 'user_id': request.user.pk, 'subscription_user_id': follow_user_id, 'include_favicon': True, 'update_counts': True, } follow_subscription = MSocialSubscription.feeds(calculate_scores=True, **social_params) logging.user(request, "~BB~FRFollowing: %s" % follow_profile.username) return { "user_profile": profile.to_json(include_follows=True), "follow_profile": follow_profile.to_json(common_follows_with_user=request.user.pk), "follow_subscription": follow_subscription, }
def load_user_friends(request): user = get_user(request.user) social_profile, _ = MSocialProfile.objects.get_or_create(user_id=user.pk) social_services, _ = MSocialServices.objects.get_or_create(user_id=user.pk) following_profiles = MSocialProfile.profiles(social_profile.following_user_ids) follower_profiles = MSocialProfile.profiles(social_profile.follower_user_ids) recommended_users = social_profile.recommended_users() following_profiles = [p.to_json(include_following_user=user.pk) for p in following_profiles] follower_profiles = [p.to_json(include_following_user=user.pk) for p in follower_profiles] logging.user( request, "~BB~FRLoading Friends (%s following, %s followers)" % (social_profile.following_count, social_profile.follower_count), ) return { "services": social_services, "autofollow": social_services.autofollow, "user_profile": social_profile.to_json(include_follows=True), "following_profiles": following_profiles, "follower_profiles": follower_profiles, "recommended_users": recommended_users, }
def render_recommended_users(context): user = get_user(context['user']) profile = MSocialProfile.profile(user.pk) return { 'user': user, 'profile': profile, }
def render_feeds_skeleton(context): user = get_user(context['user']) social_profile = MSocialProfile.get_user(user.pk) return { 'user': user, 'social_profile': social_profile, 'MEDIA_URL': settings.MEDIA_URL, }
def render_getting_started(context): user = get_user(context['user']) profile = MSocialProfile.profile(user.pk) return { 'user': user, 'user_profile': user.profile, 'social_profile': profile, }
def load_user_profile(request): social_profile = MSocialProfile.get_user(request.user.pk) social_services, _ = MSocialServices.objects.get_or_create(user_id=request.user.pk) logging.user(request, "~BB~FRLoading social profile and blurblog settings") return { 'services': social_services, 'user_profile': social_profile.to_json(include_follows=True, include_settings=True), }
def set_account_settings(request): code = 1 message = '' post_settings = request.POST if post_settings[ 'username'] and request.user.username != post_settings['username']: try: User.objects.get(username__iexact=post_settings['username']) except User.DoesNotExist: request.user.username = post_settings['username'] request.user.save() social_profile = MSocialProfile.get_user(request.user.pk) social_profile.username = post_settings['username'] social_profile.save() else: code = -1 message = "This username is already taken. Try something different." if request.user.email != post_settings['email']: if not post_settings['email'] or not User.objects.filter( email=post_settings['email']).count(): request.user.email = post_settings['email'] request.user.save() else: code = -2 message = "This email is already being used by another account. Try something different." if code != -1 and (post_settings['old_password'] or post_settings['new_password']): code = change_password(request.user, post_settings['old_password'], post_settings['new_password']) if code == -3: message = "Your old password is incorrect." payload = { "username": request.user.username, "email": request.user.email, "social_profile": MSocialProfile.profile(request.user.pk) } return dict(code=code, message=message, payload=payload)
def save_blurblog_settings(request): data = request.POST profile = MSocialProfile.get_user(request.user.pk) profile.custom_css = data.get('custom_css', None) profile.custom_bgcolor = data.get('custom_bgcolor', None) profile.blurblog_title = data.get('blurblog_title', None) profile.save() logging.user(request, "~BB~FRSaving blurblog settings") return dict(code=1, user_profile=profile.to_json(include_follows=True, include_settings=True))
def shared_stories_rss_feed(request, user_id, username): try: user = User.objects.get(pk=user_id) except User.DoesNotExist: raise Http404 username = username and username.lower() profile = MSocialProfile.get_user(user.pk) if not username or profile.username_slug.lower() != username: params = {"username": profile.username_slug, "user_id": user.pk} return HttpResponseRedirect(reverse("shared-stories-rss-feed", kwargs=params)) social_profile = MSocialProfile.get_user(user_id) data = {} data["title"] = social_profile.title data["link"] = social_profile.blurblog_url data["description"] = "Stories shared by %s on NewsBlur." % user.username data["lastBuildDate"] = datetime.datetime.utcnow() data["items"] = [] data["generator"] = "NewsBlur" data["docs"] = None shared_stories = MSharedStory.objects.filter(user_id=user.pk).order_by("-shared_date")[:25] for shared_story in shared_stories: story_data = { "title": shared_story.story_title, "link": shared_story.story_permalink, "description": shared_story.story_content_z and zlib.decompress(shared_story.story_content_z), "author": shared_story.story_author_name, "categories": shared_story.story_tags, "guid": shared_story.story_guid, "pubDate": shared_story.shared_date, } data["items"].append(RSS.RSSItem(**story_data)) rss = RSS.RSS2(**data) return HttpResponse(rss.to_xml())
def shared_stories_rss_feed(request, user_id, username): try: user = User.objects.get(pk=user_id) except User.DoesNotExist: raise Http404 username = username and username.lower() profile = MSocialProfile.get_user(user.pk) if not username or profile.username_slug.lower() != username: params = {'username': profile.username_slug, 'user_id': user.pk} return HttpResponseRedirect(reverse('shared-stories-rss-feed', kwargs=params)) social_profile = MSocialProfile.get_user(user_id) data = {} data['title'] = social_profile.title data['link'] = social_profile.blurblog_url data['description'] = "Stories shared by %s on NewsBlur." % user.username data['lastBuildDate'] = datetime.datetime.utcnow() data['items'] = [] data['generator'] = 'NewsBlur' data['docs'] = None shared_stories = MSharedStory.objects.filter(user_id=user.pk).order_by('-shared_date')[:25] for shared_story in shared_stories: story_data = { 'title': shared_story.story_title, 'link': shared_story.story_permalink, 'description': shared_story.story_content_z and zlib.decompress(shared_story.story_content_z), 'author': shared_story.story_author_name, 'categories': shared_story.story_tags, 'guid': shared_story.story_guid, 'pubDate': shared_story.shared_date, } data['items'].append(RSS.RSSItem(**story_data)) rss = RSS.RSS2(**data) return HttpResponse(rss.to_xml())
def profile(request): user = get_user(request.user) user_id = request.GET.get("user_id", user.pk) categories = request.GET.getlist("category") include_activities_html = request.REQUEST.get("include_activities_html", None) user_profile = MSocialProfile.get_user(user_id) user_profile.count_follows() user_profile = user_profile.to_json(include_follows=True, common_follows_with_user=user.pk) profile_ids = set( user_profile["followers_youknow"] + user_profile["followers_everybody"] + user_profile["following_youknow"] + user_profile["following_everybody"] ) profiles = MSocialProfile.profiles(profile_ids) activities, _ = MActivity.user(user_id, page=1, public=True, categories=categories) logging.user(request, "~BB~FRLoading social profile: %s" % user_profile["username"]) payload = { "user_profile": user_profile, # XXX TODO: Remove following 4 vestigial params. "followers_youknow": user_profile["followers_youknow"], "followers_everybody": user_profile["followers_everybody"], "following_youknow": user_profile["following_youknow"], "following_everybody": user_profile["following_everybody"], "profiles": dict([(p.user_id, p.to_json(compact=True)) for p in profiles]), "activities": activities, } if include_activities_html: payload["activities_html"] = render_to_string( "reader/activities_module.xhtml", {"activities": activities, "username": user_profile["username"], "public": True}, ) return payload
def set_account_settings(request): code = 1 message = '' post_settings = request.POST if post_settings['username'] and request.user.username != post_settings['username']: try: User.objects.get(username__iexact=post_settings['username']) except User.DoesNotExist: request.user.username = post_settings['username'] request.user.save() social_profile = MSocialProfile.get_user(request.user.pk) social_profile.username = post_settings['username'] social_profile.save() else: code = -1 message = "This username is already taken. Try something different." if request.user.email != post_settings['email']: if not post_settings['email'] or not User.objects.filter(email=post_settings['email']).count(): request.user.email = post_settings['email'] request.user.save() else: code = -2 message = "This email is already being used by another account. Try something different." if code != -1 and (post_settings['old_password'] or post_settings['new_password']): code = change_password(request.user, post_settings['old_password'], post_settings['new_password']) if code == -3: message = "Your old password is incorrect." payload = { "username": request.user.username, "email": request.user.email, "social_profile": MSocialProfile.profile(request.user.pk) } return dict(code=code, message=message, payload=payload)
def save_user_profile(request): data = request.POST profile = MSocialProfile.get_user(request.user.pk) profile.location = data['location'] profile.bio = data['bio'] profile.website = data['website'] profile.save() social_services = MSocialServices.objects.get(user_id=request.user.pk) profile = social_services.set_photo(data['photo_service']) logging.user(request, "~BB~FRSaving social profile") return dict(code=1, user_profile=profile.to_json(include_follows=True))
def add_site_load_script(request, token): code = 0 usf = None profile = None user_profile = None starred_counts = {} def image_base64(image_name, path='icons/circular/'): image_file = open( os.path.join(settings.MEDIA_ROOT, 'img/%s%s' % (path, image_name)), 'rb') return base64.b64encode(image_file.read()).decode('utf-8') accept_image = image_base64('newuser_icn_setup.png') error_image = image_base64('newuser_icn_sharewith_active.png') new_folder_image = image_base64('g_icn_arrow_right.png') add_image = image_base64('g_icn_expand_hover.png') try: profiles = Profile.objects.filter(secret_token=token) if profiles: profile = profiles[0] usf = UserSubscriptionFolders.objects.get(user=profile.user) user_profile = MSocialProfile.get_user(user_id=profile.user.pk) starred_counts = MStarredStoryCounts.user_counts(profile.user.pk) else: code = -1 except Profile.DoesNotExist: code = -1 except UserSubscriptionFolders.DoesNotExist: code = -1 return render( request, 'api/share_bookmarklet.js', { 'code': code, 'token': token, 'folders': (usf and usf.folders) or [], 'user': profile and profile.user or {}, 'user_profile': user_profile and json.encode(user_profile.canonical()) or {}, 'starred_counts': json.encode(starred_counts), 'accept_image': accept_image, 'error_image': error_image, 'add_image': add_image, 'new_folder_image': new_folder_image, }, content_type='application/javascript')
def social_feed_trainer(request): social_user_id = request.REQUEST.get("user_id") social_profile = MSocialProfile.get_user(social_user_id) social_user = get_object_or_404(User, pk=social_user_id) user = get_user(request) social_profile.count_stories() classifier = social_profile.to_json() classifier["classifiers"] = get_classifiers_for_user(user, social_user_id=classifier["id"]) classifier["num_subscribers"] = social_profile.follower_count classifier["feed_tags"] = [] classifier["feed_authors"] = [] logging.user(user, "~FGLoading social trainer on ~SB%s: %s" % (social_user.username, social_profile.title)) return [classifier]
def set_account_settings(request): code = -1 message = 'OK' form = AccountSettingsForm(user=request.user, data=request.POST) if form.is_valid(): form.save() code = 1 else: message = form.errors[form.errors.keys()[0]][0] payload = { "username": request.user.username, "email": request.user.email, "social_profile": MSocialProfile.profile(request.user.pk) } return dict(code=code, message=message, payload=payload)
def add_site_load_script(request, token): code = 0 usf = None profile = None user_profile = None def image_base64(image_name, path="icons/circular/"): image_file = open(os.path.join(settings.MEDIA_ROOT, "img/%s%s" % (path, image_name))) return base64.b64encode(image_file.read()) accept_image = image_base64("newuser_icn_setup.png") error_image = image_base64("newuser_icn_sharewith_active.png") new_folder_image = image_base64("g_icn_arrow_right.png") add_image = image_base64("g_icn_expand_hover.png") try: profiles = Profile.objects.filter(secret_token=token) if profiles: profile = profiles[0] usf = UserSubscriptionFolders.objects.get(user=profile.user) user_profile = MSocialProfile.get_user(user_id=profile.user.pk) else: code = -1 except Profile.DoesNotExist: code = -1 except UserSubscriptionFolders.DoesNotExist: code = -1 return render_to_response( "api/share_bookmarklet.js", { "code": code, "token": token, "folders": (usf and usf.folders) or [], "user": profile and profile.user or {}, "user_profile": user_profile and json.encode(user_profile.canonical()) or {}, "accept_image": accept_image, "error_image": error_image, "add_image": add_image, "new_folder_image": new_folder_image, }, context_instance=RequestContext(request), mimetype="application/javascript", )
def welcome(request, **kwargs): user = get_user(request) statistics = MStatistics.all() social_profile = MSocialProfile.get_user(user.pk) if request.method == "POST": pass else: login_form = LoginForm(prefix='login') signup_form = SignupForm(prefix='signup') return { 'user_profile': hasattr(user, 'profile') and user.profile, 'login_form': login_form, 'signup_form': signup_form, 'statistics': statistics, 'social_profile': social_profile, 'post_request': request.method == 'POST' }, "reader/welcome.xhtml"
def save_user_profile(request): data = request.POST website = data["website"] if website and not website.startswith("http"): website = "http://" + website profile = MSocialProfile.get_user(request.user.pk) profile.location = data["location"] profile.bio = data["bio"] profile.website = website profile.save() social_services = MSocialServices.objects.get(user_id=request.user.pk) profile = social_services.set_photo(data["photo_service"]) logging.user(request, "~BB~FRSaving social profile") return dict(code=1, user_profile=profile.to_json(include_follows=True))
def add_site_load_script(request, token): code = 0 usf = None profile = None user_profile = None def image_base64(image_name, path='icons/silk/'): image_file = open( os.path.join(settings.MEDIA_ROOT, 'img/%s%s' % (path, image_name))) return base64.b64encode(image_file.read()) accept_image = image_base64('accept.png') error_image = image_base64('error.png') new_folder_image = image_base64('arrow_down_right.png') add_image = image_base64('add.png') try: profiles = Profile.objects.filter(secret_token=token) if profiles: profile = profiles[0] usf = UserSubscriptionFolders.objects.get(user=profile.user) user_profile = MSocialProfile.get_user(user_id=profile.user.pk) else: code = -1 except Profile.DoesNotExist: code = -1 except UserSubscriptionFolders.DoesNotExist: code = -1 return render_to_response('api/share_bookmarklet.js', { 'code': code, 'token': token, 'folders': (usf and usf.folders) or [], 'user': profile and profile.user or {}, 'user_profile': user_profile and json.encode(user_profile.to_json()) or {}, 'accept_image': accept_image, 'error_image': error_image, 'add_image': add_image, 'new_folder_image': new_folder_image, }, context_instance=RequestContext(request), mimetype='application/javascript')
def add_site_load_script(request, token): code = 0 usf = None profile = None; user_profile = None; def image_base64(image_name, path='icons/silk/'): image_file = open(os.path.join(settings.MEDIA_ROOT, 'img/%s%s' % (path, image_name))) return base64.b64encode(image_file.read()) accept_image = image_base64('accept.png') error_image = image_base64('error.png') new_folder_image = image_base64('arrow_down_right.png') add_image = image_base64('add.png') try: profiles = Profile.objects.filter(secret_token=token) if profiles: profile = profiles[0] usf = UserSubscriptionFolders.objects.get( user=profile.user ) user_profile = MSocialProfile.get_user(user_id=profile.user.pk) else: code = -1 except Profile.DoesNotExist: code = -1 except UserSubscriptionFolders.DoesNotExist: code = -1 return render_to_response('api/share_bookmarklet.js', { 'code': code, 'token': token, 'folders': (usf and usf.folders) or [], 'user': profile and profile.user or {}, 'user_profile': user_profile and json.encode(user_profile.to_json()) or {}, 'accept_image': accept_image, 'error_image': error_image, 'add_image': add_image, 'new_folder_image': new_folder_image, }, context_instance=RequestContext(request), mimetype='application/javascript')
def save(self, profile_callback=None): username = self.cleaned_data["username"] new_password = self.cleaned_data.get("new_password", None) old_password = self.cleaned_data.get("old_password", None) email = self.cleaned_data.get("email", None) if username and self.user.username != username: change_password(self.user, self.user.username, username) self.user.username = username self.user.save() social_profile = MSocialProfile.get_user(self.user.pk) social_profile.username = username social_profile.save() if self.user.email != email: self.user.email = email self.user.save() if old_password or new_password: change_password(self.user, old_password, new_password)
def load_social_statistics(request, social_user_id, username=None): stats = dict() social_profile = MSocialProfile.get_user(social_user_id) social_profile.save_feed_story_history_statistics() social_profile.save_classifier_counts() # Stories per month - average and month-by-month breakout stats['average_stories_per_month'] = social_profile.average_stories_per_month stats['story_count_history'] = social_profile.story_count_history # Subscribers stats['subscriber_count'] = social_profile.follower_count stats['num_subscribers'] = social_profile.follower_count # Classifier counts stats['classifier_counts'] = social_profile.feed_classifier_counts logging.user(request, "~FBStatistics social: ~SB%s ~FG(%s subs)" % ( social_profile.user_id, social_profile.follower_count)) return stats
def dashboard(request, **kwargs): user = request.user feed_count = UserSubscription.objects.filter(user=user).count() recommended_feeds = RecommendedFeed.objects.filter(is_public=True, approved_date__lte=datetime.datetime.now() ).select_related('feed')[:2] unmoderated_feeds = [] if user.is_staff: unmoderated_feeds = RecommendedFeed.objects.filter(is_public=False, declined_date__isnull=True ).select_related('feed')[:2] statistics = MStatistics.all() social_profile = MSocialProfile.get_user(user.pk) start_import_from_google_reader = request.session.get('import_from_google_reader', False) if start_import_from_google_reader: del request.session['import_from_google_reader'] if not user.is_active: url = "https://%s%s" % (Site.objects.get_current().domain, reverse('stripe-form')) return HttpResponseRedirect(url) logging.user(request, "~FBLoading dashboard") return { 'user_profile': user.profile, 'feed_count': feed_count, 'account_images': range(1,4), 'recommended_feeds': recommended_feeds, 'unmoderated_feeds': unmoderated_feeds, 'statistics': statistics, 'social_profile': social_profile, 'start_import_from_google_reader': start_import_from_google_reader, 'debug': settings.DEBUG }, "reader/dashboard.xhtml"
def check_share_on_site(request, token): code = 0 story_url = request.GET['story_url'] rss_url = request.GET.get('rss_url') callback = request.GET['callback'] other_stories = None same_stories = None usersub = None message = None user = None if not story_url: code = -1 else: try: user_profile = Profile.objects.get(secret_token=token) user = user_profile.user except Profile.DoesNotExist: code = -1 logging.user(request.user, "~FBFinding feed (check_share_on_site): %s" % rss_url) feed = Feed.get_feed_from_url(rss_url, create=False, fetch=False) if not feed: logging.user(request.user, "~FBFinding feed (check_share_on_site): %s" % story_url) feed = Feed.get_feed_from_url(story_url, create=False, fetch=False) if not feed: parsed_url = urlparse.urlparse(story_url) base_url = "%s://%s%s" % (parsed_url.scheme, parsed_url.hostname, parsed_url.path) logging.user(request.user, "~FBFinding feed (check_share_on_site): %s" % base_url) feed = Feed.get_feed_from_url(base_url, create=False, fetch=False) if not feed: logging.user(request.user, "~FBFinding feed (check_share_on_site): %s" % (base_url + '/')) feed = Feed.get_feed_from_url(base_url+'/', create=False, fetch=False) if feed and user: try: usersub = UserSubscription.objects.filter(user=user, feed=feed) except UserSubscription.DoesNotExist: usersub = None feed_id = feed and feed.pk your_story, same_stories, other_stories = MSharedStory.get_shared_stories_from_site(feed_id, user_id=user_profile.user.pk, story_url=story_url) previous_stories = MSharedStory.objects.filter(user_id=user_profile.user.pk).order_by('-shared_date').limit(3) previous_stories = [{ "user_id": story.user_id, "story_title": story.story_title, "comments": story.comments, "shared_date": story.shared_date, "relative_date": relative_timesince(story.shared_date), "blurblog_permalink": story.blurblog_permalink(), } for story in previous_stories] user_ids = set([user_profile.user.pk]) for story in same_stories: user_ids.add(story['user_id']) for story in other_stories: user_ids.add(story['user_id']) users = {} profiles = MSocialProfile.profiles(user_ids) for profile in profiles: users[profile.user_id] = { "username": profile.username, "photo_url": profile.photo_url, } logging.user(user_profile.user, "~BM~FCChecking share from site: ~SB%s" % (story_url), request=request) response = HttpResponse(callback + '(' + json.encode({ 'code' : code, 'message' : message, 'feed' : feed, 'subscribed' : bool(usersub), 'your_story' : your_story, 'same_stories' : same_stories, 'other_stories' : other_stories, 'previous_stories' : previous_stories, 'users' : users, }) + ')', content_type='text/plain') response['Access-Control-Allow-Origin'] = '*' response['Access-Control-Allow-Methods'] = 'GET' return response
def EmailNewFollower(follower_user_id, followee_user_id): user_profile = MSocialProfile.get_user(followee_user_id) user_profile.send_email_for_new_follower(follower_user_id)
def run(self, follower_user_id, followee_user_id): user_profile = MSocialProfile.get_user(followee_user_id) user_profile.send_email_for_follow_request(follower_user_id)
def mark_story_as_shared(request): code = 1 feed_id = int(request.POST['feed_id']) story_id = request.POST['story_id'] comments = request.POST.get('comments', '') source_user_id = request.POST.get('source_user_id') post_to_services = request.POST.getlist('post_to_services') format = request.REQUEST.get('format', 'json') MSocialProfile.get_user(request.user.pk) story, original_story_found = MStory.find_story(feed_id, story_id) if not story: return json.json_response(request, { 'code': -1, 'message': 'Could not find the original story and no copies could be found.' }) shared_story = MSharedStory.objects.filter(user_id=request.user.pk, story_feed_id=feed_id, story_guid=story_id).limit(1).first() if not shared_story: story_db = dict([(k, v) for k, v in story._data.items() if k is not None and v is not None]) story_values = dict(user_id=request.user.pk, comments=comments, has_comments=bool(comments), story_db_id=story.id) story_db.update(story_values) shared_story = MSharedStory.objects.create(**story_db) if source_user_id: shared_story.set_source_user_id(int(source_user_id)) socialsubs = MSocialSubscription.objects.filter(subscription_user_id=request.user.pk) for socialsub in socialsubs: socialsub.needs_unread_recalc = True socialsub.save() logging.user(request, "~FCSharing ~FM%s: ~SB~FB%s" % (story.story_title[:20], comments[:30])) else: shared_story.comments = comments shared_story.has_comments = bool(comments) shared_story.save() logging.user(request, "~FCUpdating shared story ~FM%s: ~SB~FB%s" % ( story.story_title[:20], comments[:30])) if original_story_found: story.count_comments() shared_story.publish_update_to_subscribers() story = Feed.format_story(story) check_all = not original_story_found stories, profiles = MSharedStory.stories_with_comments_and_profiles([story], request.user.pk, check_all=check_all) story = stories[0] story['shared_comments'] = strip_tags(shared_story['comments'] or "") if post_to_services: for service in post_to_services: if service not in shared_story.posted_to_services: PostToService.delay(shared_story_id=shared_story.id, service=service) if shared_story.source_user_id and shared_story.comments: EmailStoryReshares.apply_async(kwargs=dict(shared_story_id=shared_story.id), countdown=60) if format == 'html': stories = MSharedStory.attach_users_to_stories(stories, profiles) return render_to_response('social/story_share.xhtml', { 'story': story, }, context_instance=RequestContext(request)) else: return json.json_response(request, { 'code': code, 'story': story, 'user_profiles': profiles, })
def load_social_stories(request, user_id, username=None): start = time.time() user = get_user(request) social_user_id = int(user_id) social_user = get_object_or_404(User, pk=social_user_id) offset = int(request.REQUEST.get('offset', 0)) limit = int(request.REQUEST.get('limit', 6)) page = request.REQUEST.get('page') order = request.REQUEST.get('order', 'newest') read_filter = request.REQUEST.get('read_filter', 'all') stories = [] if page: offset = limit * (int(page) - 1) now = localtime_for_timezone(datetime.datetime.now(), user.profile.timezone) UNREAD_CUTOFF = datetime.datetime.utcnow() - datetime.timedelta(days=settings.DAYS_OF_UNREAD) social_profile = MSocialProfile.get_user(social_user.pk) try: socialsub = MSocialSubscription.objects.get(user_id=user.pk, subscription_user_id=social_user_id) except MSocialSubscription.DoesNotExist: socialsub = None mstories = MSharedStory.objects(user_id=social_user.pk).order_by('-shared_date')[offset:offset+limit] stories = Feed.format_stories(mstories) if socialsub and (read_filter == 'unread' or order == 'oldest'): story_ids = socialsub.get_stories(order=order, read_filter=read_filter, offset=offset, limit=limit) story_date_order = "%sshared_date" % ('' if order == 'oldest' else '-') if story_ids: mstories = MSharedStory.objects(user_id=social_user.pk, story_db_id__in=story_ids).order_by(story_date_order) stories = Feed.format_stories(mstories) else: mstories = MSharedStory.objects(user_id=social_user.pk).order_by('-shared_date')[offset:offset+limit] stories = Feed.format_stories(mstories) if not stories: return dict(stories=[]) checkpoint1 = time.time() stories, user_profiles = MSharedStory.stories_with_comments_and_profiles(stories, user.pk, check_all=True) story_feed_ids = list(set(s['story_feed_id'] for s in stories)) usersubs = UserSubscription.objects.filter(user__pk=user.pk, feed__pk__in=story_feed_ids) usersubs_map = dict((sub.feed_id, sub) for sub in usersubs) unsub_feed_ids = list(set(story_feed_ids).difference(set(usersubs_map.keys()))) unsub_feeds = Feed.objects.filter(pk__in=unsub_feed_ids) unsub_feeds = [feed.canonical(include_favicon=False) for feed in unsub_feeds] date_delta = UNREAD_CUTOFF if socialsub and date_delta < socialsub.mark_read_date: date_delta = socialsub.mark_read_date # Get intelligence classifier for user classifier_feeds = list(MClassifierFeed.objects(user_id=user.pk, social_user_id=social_user_id)) classifier_authors = list(MClassifierAuthor.objects(user_id=user.pk, social_user_id=social_user_id)) classifier_titles = list(MClassifierTitle.objects(user_id=user.pk, social_user_id=social_user_id)) classifier_tags = list(MClassifierTag.objects(user_id=user.pk, social_user_id=social_user_id)) # Merge with feed specific classifiers classifier_feeds = classifier_feeds + list(MClassifierFeed.objects(user_id=user.pk, feed_id__in=story_feed_ids)) classifier_authors = classifier_authors + list(MClassifierAuthor.objects(user_id=user.pk, feed_id__in=story_feed_ids)) classifier_titles = classifier_titles + list(MClassifierTitle.objects(user_id=user.pk, feed_id__in=story_feed_ids)) classifier_tags = classifier_tags + list(MClassifierTag.objects(user_id=user.pk, feed_id__in=story_feed_ids)) checkpoint2 = time.time() story_ids = [story['id'] for story in stories] userstories_db = MUserStory.objects(user_id=user.pk, feed_id__in=story_feed_ids, story_id__in=story_ids).only('story_id') userstories = set(us.story_id for us in userstories_db) starred_stories = MStarredStory.objects(user_id=user.pk, story_feed_id__in=story_feed_ids, story_guid__in=story_ids).only('story_guid', 'starred_date') shared_stories = MSharedStory.objects(user_id=user.pk, story_feed_id__in=story_feed_ids, story_guid__in=story_ids)\ .only('story_guid', 'shared_date', 'comments') starred_stories = dict([(story.story_guid, story.starred_date) for story in starred_stories]) shared_stories = dict([(story.story_guid, dict(shared_date=story.shared_date, comments=story.comments)) for story in shared_stories]) for story in stories: story['social_user_id'] = social_user_id story_feed_id = story['story_feed_id'] # story_date = localtime_for_timezone(story['story_date'], user.profile.timezone) shared_date = localtime_for_timezone(story['shared_date'], user.profile.timezone) story['short_parsed_date'] = format_story_link_date__short(shared_date, now) story['long_parsed_date'] = format_story_link_date__long(shared_date, now) if not socialsub: story['read_status'] = 1 elif story['id'] in userstories: story['read_status'] = 1 elif story['shared_date'] < date_delta: story['read_status'] = 1 elif not usersubs_map.get(story_feed_id): story['read_status'] = 0 elif not story.get('read_status') and story['story_date'] < usersubs_map[story_feed_id].mark_read_date: story['read_status'] = 1 elif not story.get('read_status') and story['shared_date'] < date_delta: story['read_status'] = 1 # elif not story.get('read_status') and socialsub and story['shared_date'] > socialsub.last_read_date: # story['read_status'] = 0 else: story['read_status'] = 0 if story['id'] in starred_stories: story['starred'] = True starred_date = localtime_for_timezone(starred_stories[story['id']], user.profile.timezone) story['starred_date'] = format_story_link_date__long(starred_date, now) if story['id'] in shared_stories: story['shared'] = True shared_date = localtime_for_timezone(shared_stories[story['id']]['shared_date'], user.profile.timezone) story['shared_date'] = format_story_link_date__long(shared_date, now) story['shared_comments'] = strip_tags(shared_stories[story['id']]['comments']) story['intelligence'] = { 'feed': apply_classifier_feeds(classifier_feeds, story['story_feed_id'], social_user_id=social_user_id), 'author': apply_classifier_authors(classifier_authors, story), 'tags': apply_classifier_tags(classifier_tags, story), 'title': apply_classifier_titles(classifier_titles, story), } classifiers = sort_classifiers_by_feed(user=user, feed_ids=story_feed_ids, classifier_feeds=classifier_feeds, classifier_authors=classifier_authors, classifier_titles=classifier_titles, classifier_tags=classifier_tags) if socialsub: socialsub.feed_opens += 1 socialsub.save() diff1 = checkpoint1-start diff2 = checkpoint2-start logging.user(request, "~FYLoading ~FMshared stories~FY: ~SB%s%s ~SN(~SB%.4ss/%.4ss~SN)" % ( social_profile.title[:22], ('~SN/p%s' % page) if page > 1 else '', diff1, diff2)) return { "stories": stories, "user_profiles": user_profiles, "feeds": unsub_feeds, "classifiers": classifiers, }
def load_social_settings(request, social_user_id, username=None): social_profile = MSocialProfile.get_user(social_user_id) return social_profile.to_json()
def check_share_on_site(request, token): code = 0 story_url = request.GET["story_url"] rss_url = request.GET.get("rss_url") callback = request.GET["callback"] other_stories = None same_stories = None usersub = None message = None user = None if not story_url: code = -1 else: try: user_profile = Profile.objects.get(secret_token=token) user = user_profile.user except Profile.DoesNotExist: code = -1 feed = Feed.get_feed_from_url(rss_url, create=False, fetch=False) if not feed: feed = Feed.get_feed_from_url(story_url, create=False, fetch=False) if not feed: parsed_url = urlparse.urlparse(story_url) base_url = "%s://%s%s" % (parsed_url.scheme, parsed_url.hostname, parsed_url.path) feed = Feed.get_feed_from_url(base_url, create=False, fetch=False) if not feed: feed = Feed.get_feed_from_url(base_url + "/", create=False, fetch=False) if feed and user: try: usersub = UserSubscription.objects.filter(user=user, feed=feed) except UserSubscription.DoesNotExist: usersub = None feed_id = feed and feed.pk your_story, same_stories, other_stories = MSharedStory.get_shared_stories_from_site( feed_id, user_id=user_profile.user.pk, story_url=story_url ) previous_stories = MSharedStory.objects.filter(user_id=user_profile.user.pk).order_by("-shared_date").limit(3) previous_stories = [ { "user_id": story.user_id, "story_title": story.story_title, "comments": story.comments, "shared_date": story.shared_date, "relative_date": relative_timesince(story.shared_date), "blurblog_permalink": story.blurblog_permalink(), } for story in previous_stories ] user_ids = set([user_profile.user.pk]) for story in same_stories: user_ids.add(story["user_id"]) for story in other_stories: user_ids.add(story["user_id"]) users = {} profiles = MSocialProfile.profiles(user_ids) for profile in profiles: users[profile.user_id] = {"username": profile.username, "photo_url": profile.photo_url} logging.user(user_profile.user, "~BM~FCChecking share from site: ~SB%s" % (story_url), request=request) response = HttpResponse( callback + "(" + json.encode( { "code": code, "message": message, "feed": feed, "subscribed": bool(usersub), "your_story": your_story, "same_stories": same_stories, "other_stories": other_stories, "previous_stories": previous_stories, "users": users, } ) + ")", mimetype="text/plain", ) response["Access-Control-Allow-Origin"] = "*" response["Access-Control-Allow-Methods"] = "GET" return response
def check_share_on_site(request, token): code = 0 story_url = request.GET['story_url'] rss_url = request.GET.get('rss_url') callback = request.GET['callback'] other_stories = None same_stories = None usersub = None message = None user = None if not story_url: code = -1 else: try: user_profile = Profile.objects.get(secret_token=token) user = user_profile.user except Profile.DoesNotExist: code = -1 feed = Feed.get_feed_from_url(rss_url, create=False, fetch=False) if not feed: feed = Feed.get_feed_from_url(story_url, create=False, fetch=False) if not feed: parsed_url = urlparse.urlparse(story_url) base_url = "%s://%s%s" % (parsed_url.scheme, parsed_url.hostname, parsed_url.path) feed = Feed.get_feed_from_url(base_url, create=False, fetch=False) if not feed: feed = Feed.get_feed_from_url(base_url+'/', create=False, fetch=False) if feed and user: try: usersub = UserSubscription.objects.filter(user=user, feed=feed) except UserSubscription.DoesNotExist: usersub = None feed_id = feed and feed.pk your_story, same_stories, other_stories = MSharedStory.get_shared_stories_from_site(feed_id, user_id=user_profile.user.pk, story_url=story_url) previous_stories = MSharedStory.objects.filter(user_id=user_profile.user.pk).order_by('-shared_date').limit(3) previous_stories = [{ "user_id": story.user_id, "story_title": story.story_title, "comments": story.comments, "shared_date": story.shared_date, "relative_date": relative_timesince(story.shared_date), "blurblog_permalink": story.blurblog_permalink(), } for story in previous_stories] user_ids = set([user_profile.user.pk]) for story in same_stories: user_ids.add(story['user_id']) for story in other_stories: user_ids.add(story['user_id']) users = {} profiles = MSocialProfile.profiles(user_ids) for profile in profiles: users[profile.user_id] = { "username": profile.username, "photo_url": profile.photo_url, } logging.user(user_profile.user, "~BM~FCChecking share from site: ~SB%s" % (story_url), request=request) response = HttpResponse(callback + '(' + json.encode({ 'code' : code, 'message' : message, 'feed' : feed, 'subscribed' : bool(usersub), 'your_story' : your_story, 'same_stories' : same_stories, 'other_stories' : other_stories, 'previous_stories' : previous_stories, 'users' : users, }) + ')', mimetype='text/plain') response['Access-Control-Allow-Origin'] = '*' response['Access-Control-Allow-Methods'] = 'GET' return response