Merge branch 'master' of github.com:samuelclay/NewsBlur

* 'master' of github.com:samuelclay/NewsBlur: (68 commits)
  Marking read stories in Feed view as very much read. Gradientizing, too.
  Fixing /m/ for no good reason.
  File under "fucking finally": Adding client-side error handling and callbacks for feeds and river.
  Fixing missing stories being updated bug.
  Fixing issues around embedded content. Santizing HTML, but =preserving embed, object, and params.
  Fixing iOS bug around the story progress indicator not being updated when returning from suspended state.
  Bumping up the subscriber expire, now that I've got my wits back.
  Stepping up feed fetch intervals.
  No longer sanitizing HTML in feed parsing. I hope this doesn't bite me. But now Flash videos will appear in the feed.
  Adding iphone icon as a logo that I can submit to sites.
  Brief cleanup.
  Finished suggestion to add unread counts to window title. Now a preference.
  Adding color transform to read stories in Feed view.
  As per a suggestion, making the max-width of the Feed view set to 700px. Great idea.
  Fixing bug in send_story_email -- newlines in the subject line. Doh. Also adding story_Date to read_stories, in the hopes it could fix another bug for bad unread counts.
  Fixing issues around broken existing stories on secondary vs primary.
  Fixing mark_feed_stories_as_read, and fixing a bad MStory query.
  Finishing the revamping mark as read button. Now confirms, as well as allows choice between entire feed/folder or just visible stories.
  Adding bullshit user agent string because some sites are sniffing for browsers in order to serve the correct site.
  Swapping out Instapaper and Email.
  ...
This commit is contained in:
Samuel Clay 2011-11-15 19:48:21 -08:00
commit d084d5dcbb
52 changed files with 5681 additions and 297 deletions

View file

@ -1,6 +1,7 @@
from utils import log as logging
from django.shortcuts import get_object_or_404
from django.views.decorators.http import require_POST
from mongoengine.queryset import OperationError
from apps.rss_feeds.models import Feed
from apps.reader.models import UserSubscription
from apps.analyzer.models import MClassifierTitle, MClassifierAuthor, MClassifierFeed, MClassifierTag
@ -57,8 +58,10 @@ def save_classifier(request):
}
if content_type in ('author', 'tag', 'title'):
classifier_dict.update({content_type: post_content})
classifier, created = ClassifierCls.objects.get_or_create(**classifier_dict)
try:
classifier, created = ClassifierCls.objects.get_or_create(**classifier_dict)
except OperationError:
continue
if score == 0:
classifier.delete()
elif classifier.score != score:

View file

@ -25,7 +25,9 @@ def login(request):
login_user(request, form.get_user())
logging.user(request, "~FG~BB~SKAPI Login~FW")
code = 1
else:
errors = dict(method="Invalid method. Use POST. You used %s" % request.method)
return dict(code=code, errors=errors)
@json.json_view
@ -42,6 +44,9 @@ def signup(request):
login_user(request, new_user)
logging.user(request, "~FG~SB~BBAPI NEW SIGNUP~FW")
code = 1
else:
errors = dict(method="Invalid method. Use POST. You used %s" % request.method)
return dict(code=code, errors=errors)

View file

@ -157,9 +157,13 @@ def import_from_google_reader(request):
if request.user.is_authenticated():
reader_importer = GoogleReaderImporter(request.user)
reader_importer.import_feeds()
reader_importer.import_starred_items()
code = 1
try:
reader_importer.import_feeds()
reader_importer.import_starred_items()
except AssertionError:
code = -1
else:
code = 1
if 'import_from_google_reader' in request.session:
del request.session['import_from_google_reader']

View file

@ -6,6 +6,7 @@ from django.db import models, IntegrityError
from django.conf import settings
from django.contrib.auth.models import User
from django.core.cache import cache
from mongoengine.queryset import OperationError
from apps.reader.managers import UserSubscriptionManager
from apps.rss_feeds.models import Feed, MStory, DuplicateFeed
from apps.analyzer.models import MClassifierFeed, MClassifierAuthor, MClassifierTag, MClassifierTitle
@ -63,11 +64,13 @@ class UserSubscription(models.Model):
try:
super(UserSubscription, self).save(*args, **kwargs)
except IntegrityError:
duplicate_feed = DuplicateFeed.objects.filter(duplicate_feed_id=self.feed.pk)
already_subscribed = UserSubscription.objects.filter(user=self.user, feed=duplicate_feed.feed)
if duplicate_feed and not already_subscribed:
self.feed = duplicate_feed[0].feed
super(UserSubscription, self).save(*args, **kwargs)
duplicate_feeds = DuplicateFeed.objects.filter(duplicate_feed_id=self.feed.pk)
for duplicate_feed in duplicate_feeds:
already_subscribed = UserSubscription.objects.filter(user=self.user, feed=duplicate_feed.feed)
if not already_subscribed:
self.feed = duplicate_feed.feed
super(UserSubscription, self).save(*args, **kwargs)
break
else:
self.delete()
@ -138,6 +141,54 @@ class UserSubscription(models.Model):
MUserStory.delete_marked_as_read_stories(self.user.pk, self.feed.pk)
self.save()
def mark_story_ids_as_read(self, story_ids, request=None):
data = dict(code=0, payload=story_ids)
if not request:
request = self.user
if not self.needs_unread_recalc:
self.needs_unread_recalc = True
self.save()
if len(story_ids) > 1:
logging.user(request, "~FYRead %s stories in feed: %s" % (len(story_ids), self.feed))
else:
logging.user(request, "~FYRead story in feed: %s" % (self.feed))
for story_id in story_ids:
try:
story = MStory.objects.get(story_feed_id=self.feed.pk, story_guid=story_id)
except MStory.DoesNotExist:
# Story has been deleted, probably by feed_fetcher.
continue
except MStory.MultipleObjectsReturned:
continue
now = datetime.datetime.utcnow()
date = now if now > story.story_date else story.story_date # For handling future stories
m = MUserStory(story=story, user_id=self.user.pk,
feed_id=self.feed.pk, read_date=date,
story_id=story_id, story_date=story.story_date)
try:
m.save()
except OperationError, e:
original_m = MUserStory.objects.get(story=story, user_id=self.user.pk, feed_id=self.feed.pk)
logging.user(request, "~BRMarked story as read error: %s" % (e))
logging.user(request, "~BRMarked story as read: %s" % (story_id))
logging.user(request, "~BROrigin story as read: %s" % (m.story.story_guid))
logging.user(request, "~BRMarked story id: %s" % (original_m.story_id))
logging.user(request, "~BROrigin story guid: %s" % (original_m.story.story_guid))
logging.user(request, "~BRRead now date: %s, original read: %s, story_date: %s." % (m.read_date, original_m.read_date, story.story_date))
original_m.story_id = story_id
original_m.read_date = date
original_m.story_date = story.story_date
original_m.save()
except OperationError, e:
logging.user(request, "~BRCan't even save: %s" % (original_m.story_id))
pass
return data
def calculate_feed_scores(self, silent=False, stories_db=None):
# now = datetime.datetime.strptime("2009-07-06 22:30:03", "%Y-%m-%d %H:%M:%S")
@ -236,9 +287,10 @@ class UserSubscription(models.Model):
self.save()
# if (self.unread_count_positive == 0 and
# self.unread_count_neutral == 0):
# self.mark_feed_read()
if (self.unread_count_positive == 0 and
self.unread_count_neutral == 0 and
self.unread_count_negative == 0):
self.mark_feed_read()
cache.delete('usersub:%s' % self.user.id)
@ -260,6 +312,7 @@ class MUserStory(mongo.Document):
feed_id = mongo.IntField()
read_date = mongo.DateTimeField()
story_id = mongo.StringField()
story_date = mongo.DateTimeField()
story = mongo.ReferenceField(MStory, unique_with=('user_id', 'feed_id'))
meta = {
@ -307,7 +360,7 @@ class UserSubscriptionFolders(models.Model):
self.folders = json.encode(user_sub_folders)
self.save()
def delete_feed(self, feed_id, in_folder):
def delete_feed(self, feed_id, in_folder, commit_delete=True):
def _find_feed_in_folders(old_folders, folder_name='', multiples_found=False, deleted=False):
new_folders = []
for k, folder in enumerate(old_folders):
@ -336,7 +389,7 @@ class UserSubscriptionFolders(models.Model):
self.folders = json.encode(user_sub_folders)
self.save()
if not multiples_found and deleted:
if not multiples_found and deleted and commit_delete:
try:
user_sub = UserSubscription.objects.get(user=self.user, feed=feed_id)
except Feed.DoesNotExist:
@ -347,11 +400,12 @@ class UserSubscriptionFolders(models.Model):
feed=duplicate_feed[0].feed)
except Feed.DoesNotExist:
return
user_sub.delete()
if user_sub:
user_sub.delete()
MUserStory.objects(user_id=self.user.pk, feed_id=feed_id).delete()
def delete_folder(self, folder_to_delete, in_folder, feed_ids_in_folder):
def _find_folder_in_folders(old_folders, folder_name, feeds_to_delete):
def delete_folder(self, folder_to_delete, in_folder, feed_ids_in_folder, commit_delete=True):
def _find_folder_in_folders(old_folders, folder_name, feeds_to_delete, deleted_folder=None):
new_folders = []
for k, folder in enumerate(old_folders):
if isinstance(folder, int):
@ -362,18 +416,22 @@ class UserSubscriptionFolders(models.Model):
for f_k, f_v in folder.items():
if f_k == folder_to_delete and folder_name == in_folder:
logging.user(self.user, "~FBDeleting folder '~SB%s~SN' in '%s': %s" % (f_k, folder_name, folder))
deleted_folder = folder
else:
nf, feeds_to_delete = _find_folder_in_folders(f_v, f_k, feeds_to_delete)
nf, feeds_to_delete, deleted_folder = _find_folder_in_folders(f_v, f_k, feeds_to_delete, deleted_folder)
new_folders.append({f_k: nf})
return new_folders, feeds_to_delete
return new_folders, feeds_to_delete, deleted_folder
user_sub_folders = json.decode(self.folders)
user_sub_folders, feeds_to_delete = _find_folder_in_folders(user_sub_folders, '', feed_ids_in_folder)
user_sub_folders, feeds_to_delete, deleted_folder = _find_folder_in_folders(user_sub_folders, '', feed_ids_in_folder)
self.folders = json.encode(user_sub_folders)
self.save()
UserSubscription.objects.filter(user=self.user, feed__in=feeds_to_delete).delete()
if commit_delete:
UserSubscription.objects.filter(user=self.user, feed__in=feeds_to_delete).delete()
return deleted_folder
def rename_folder(self, folder_to_rename, new_folder_name, in_folder):
def _find_folder_in_folders(old_folders, folder_name):
@ -396,6 +454,27 @@ class UserSubscriptionFolders(models.Model):
user_sub_folders = _find_folder_in_folders(user_sub_folders, '')
self.folders = json.encode(user_sub_folders)
self.save()
def move_feed_to_folder(self, feed_id, in_folder=None, to_folder=None):
user_sub_folders = json.decode(self.folders)
self.delete_feed(feed_id, in_folder, commit_delete=False)
user_sub_folders = json.decode(self.folders)
user_sub_folders = add_object_to_folder(int(feed_id), to_folder, user_sub_folders)
self.folders = json.encode(user_sub_folders)
self.save()
return self
def move_folder_to_folder(self, folder_name, in_folder=None, to_folder=None):
user_sub_folders = json.decode(self.folders)
deleted_folder = self.delete_folder(folder_name, in_folder, [], commit_delete=False)
user_sub_folders = json.decode(self.folders)
user_sub_folders = add_object_to_folder(deleted_folder, to_folder, user_sub_folders)
self.folders = json.encode(user_sub_folders)
self.save()
return self
class Feature(models.Model):
"""

View file

@ -18,6 +18,7 @@ urlpatterns = patterns('',
url(r'^starred_stories', views.load_starred_stories, name='load-starred-stories'),
url(r'^mark_all_as_read', views.mark_all_as_read, name='mark-all-as-read'),
url(r'^mark_story_as_read', views.mark_story_as_read, name='mark-story-as-read'),
url(r'^mark_feed_stories_as_read', views.mark_feed_stories_as_read, name='mark-feed-stories-as-read'),
url(r'^mark_story_as_unread', views.mark_story_as_unread),
url(r'^mark_story_as_starred', views.mark_story_as_starred),
url(r'^mark_story_as_unstarred', views.mark_story_as_unstarred),
@ -26,6 +27,8 @@ urlpatterns = patterns('',
url(r'^delete_folder', views.delete_folder, name='delete-folder'),
url(r'^rename_feed', views.rename_feed, name='rename-feed'),
url(r'^rename_folder', views.rename_folder, name='rename-folder'),
url(r'^move_feed_to_folder', views.move_feed_to_folder, name='move-feed-to-folder'),
url(r'^move_folder_to_folder', views.move_folder_to_folder, name='move-folder-to-folder'),
url(r'^add_url', views.add_url),
url(r'^add_folder', views.add_folder),
url(r'^add_feature', views.add_feature, name='add-feature'),

View file

@ -15,9 +15,9 @@ from django.conf import settings
from django.core.mail import mail_admins
from django.core.validators import email_re
from django.core.mail import EmailMultiAlternatives
from pymongo.helpers import OperationFailure
from collections import defaultdict
from operator import itemgetter
from mongoengine.queryset import OperationError
from apps.recommendations.models import RecommendedFeed
from apps.analyzer.models import MClassifierTitle, MClassifierAuthor, MClassifierFeed, MClassifierTag
from apps.analyzer.models import apply_classifier_titles, apply_classifier_feeds, apply_classifier_authors, apply_classifier_tags
@ -39,6 +39,8 @@ from utils.story_functions import format_story_link_date__long
from utils.story_functions import bunch
from utils.story_functions import story_score
from utils import log as logging
from utils.view_functions import get_argument_or_404
from utils.ratelimit import ratelimit
from vendor.timezones.utilities import localtime_for_timezone
SINGLE_DAY = 60*60*24
@ -152,6 +154,7 @@ def autologin(request, username, secret):
return HttpResponseRedirect(reverse('index') + next)
@ratelimit(minutes=1, requests=20)
@json.json_view
def load_feeds(request):
user = get_user(request)
@ -159,6 +162,7 @@ def load_feeds(request):
not_yet_fetched = False
include_favicons = request.REQUEST.get('include_favicons', False)
flat = request.REQUEST.get('flat', False)
update_counts = request.REQUEST.get('update_counts', False)
if flat: return load_feeds_flat(request)
@ -175,6 +179,8 @@ def load_feeds(request):
for sub in user_subs:
pk = sub.feed.pk
if update_counts:
sub.calculate_feed_scores(silent=True)
feeds[pk] = sub.canonical(include_favicon=include_favicons)
if feeds[pk].get('not_yet_fetched'):
not_yet_fetched = True
@ -260,6 +266,7 @@ def load_feeds_flat(request):
data = dict(flat_folders=flat_folders, feeds=feeds, user=user.username)
return data
@ratelimit(minutes=1, requests=10)
@json.json_view
def refresh_feeds(request):
start = datetime.datetime.utcnow()
@ -334,7 +341,7 @@ def load_single_feed(request, feed_id):
page = int(request.REQUEST.get('page', 1))
dupe_feed_id = None
userstories_db = None
if page: offset = limit * (page-1)
if not feed_id: raise Http404
@ -517,7 +524,7 @@ def load_river_stories(request):
# if feed_counts[feed_id] > max_feed_count:
# max_feed_count = feed_counts[feed_id]
feed_last_reads[feed_id] = int(time.mktime(usersub.mark_read_date.timetuple()))
feed_counts = sorted(feed_counts.items(), key=itemgetter(1))[:50]
feed_counts = sorted(feed_counts.items(), key=itemgetter(1))[:40]
feed_ids = [f[0] for f in feed_counts]
feed_last_reads = dict([(str(feed_id), feed_last_reads[feed_id]) for feed_id in feed_ids
if feed_id in feed_last_reads])
@ -543,7 +550,10 @@ def load_river_stories(request):
'feed_last_reads': feed_last_reads
}
)
mstories = [story.value for story in mstories if story and story.value]
try:
mstories = [story.value for story in mstories if story and story.value]
except OperationFailure, e:
raise e
mstories = sorted(mstories, cmp=lambda x, y: cmp(story_score(y, bottom_delta), story_score(x, bottom_delta)))
@ -644,7 +654,7 @@ def mark_all_as_read(request):
@json.json_view
def mark_story_as_read(request):
story_ids = request.REQUEST.getlist('story_id')
feed_id = int(request.REQUEST['feed_id'])
feed_id = int(get_argument_or_404(request, 'feed_id'))
try:
usersub = UserSubscription.objects.select_related('feed').get(user=request.user, feed=feed_id)
@ -658,58 +668,41 @@ def mark_story_as_read(request):
return dict(code=-1)
else:
return dict(code=-1)
if not usersub.needs_unread_recalc:
usersub.needs_unread_recalc = True
usersub.save()
data = dict(code=0, payload=story_ids)
if len(story_ids) > 1:
logging.user(request, "~FYRead %s stories in feed: %s" % (len(story_ids), usersub.feed))
else:
logging.user(request, "~FYRead story in feed: %s" % (usersub.feed))
for story_id in story_ids:
try:
story = MStory.objects.get(story_feed_id=feed_id, story_guid=story_id)
except MStory.DoesNotExist:
# Story has been deleted, probably by feed_fetcher.
continue
now = datetime.datetime.utcnow()
date = now if now > story.story_date else story.story_date # For handling future stories
m = MUserStory(story=story, user_id=request.user.pk, feed_id=feed_id, read_date=date, story_id=story_id)
try:
m.save()
except OperationError:
logging.user(request, "~BRMarked story as read: Duplicate Story -> %s" % (story_id))
logging.user(request, "~BRRead now date: %s, story_date: %s, story_id: %s." % (m.read_date, story.story_date, story.story_guid))
logging.user(request, "~BRSubscription mark_read_date: %s, oldest_unread_story_date: %s" % (
usersub.mark_read_date, usersub.oldest_unread_story_date))
m = MUserStory.objects.get(story=story, user_id=request.user.pk, feed_id=feed_id)
logging.user(request, "~BROriginal read date: %s, story id: %s, story.id: %s" % (m.read_date, m.story_id, m.story.id))
m.story_id = story_id
m.read_date = date
m.save()
data = usersub.mark_story_ids_as_read(story_ids, request=request)
return data
@ajax_login_required
@json.json_view
def mark_feed_stories_as_read(request):
feeds_stories = request.REQUEST.get('feeds_stories', "{}")
feeds_stories = json.decode(feeds_stories)
for feed_id, story_ids in feeds_stories.items():
feed_id = int(feed_id)
try:
usersub = UserSubscription.objects.select_related('feed').get(user=request.user, feed=feed_id)
except (UserSubscription.DoesNotExist, Feed.DoesNotExist):
duplicate_feed = DuplicateFeed.objects.filter(duplicate_feed_id=feed_id)
if duplicate_feed:
try:
usersub = UserSubscription.objects.get(user=request.user,
feed=duplicate_feed[0].feed)
except (UserSubscription.DoesNotExist, Feed.DoesNotExist):
continue
else:
continue
usersub.mark_story_ids_as_read(story_ids)
return dict(code=1)
@ajax_login_required
@json.json_view
def mark_story_as_unread(request):
story_id = request.POST['story_id']
feed_id = int(request.POST['feed_id'])
try:
usersub = UserSubscription.objects.select_related('feed').get(user=request.user, feed=feed_id)
except Feed.DoesNotExist:
duplicate_feed = DuplicateFeed.objects.filter(duplicate_feed_id=feed_id)
if duplicate_feed:
try:
usersub = UserSubscription.objects.get(user=request.user,
feed=duplicate_feed[0].feed)
except Feed.DoesNotExist:
return dict(code=-1)
usersub = UserSubscription.objects.select_related('feed').get(user=request.user, feed=feed_id)
if not usersub.needs_unread_recalc:
usersub.needs_unread_recalc = True
@ -717,9 +710,25 @@ def mark_story_as_unread(request):
data = dict(code=0, payload=dict(story_id=story_id))
logging.user(request, "~FY~SBUnread~SN story in feed: %s" % (usersub.feed))
story = MStory.objects(story_feed_id=feed_id, story_guid=story_id)[0]
m = MUserStory.objects(story=story, user_id=request.user.pk, feed_id=feed_id)
if story.story_date < usersub.mark_read_date:
# Story is outside the mark as read range, so invert all stories before.
newer_stories = MStory.objects(story_feed_id=story.story_feed_id,
story_date__gte=story.story_date,
story_date__lte=usersub.mark_read_date
).only('story_guid')
newer_stories = [s.story_guid for s in newer_stories]
usersub.mark_read_date = story.story_date - datetime.timedelta(minutes=1)
usersub.needs_unread_recalc = True
usersub.save()
# Mark stories as read only after the mark_read_date has been moved, otherwise
# these would be ignored.
data = usersub.mark_story_ids_as_read(newer_stories, request=request)
m = MUserStory.objects(story_id=story_id, user_id=request.user.pk, feed_id=feed_id)
m.delete()
return data
@ -740,7 +749,8 @@ def mark_feed_as_read(request):
us = UserSubscription.objects.get(feed=feed, user=request.user)
try:
us.mark_feed_read()
if us:
us.mark_feed_read()
except IntegrityError:
code = -1
else:
@ -857,6 +867,30 @@ def rename_folder(request):
return dict(code=1)
@ajax_login_required
@json.json_view
def move_feed_to_folder(request):
feed_id = int(request.POST['feed_id'])
in_folder = request.POST.get('in_folder', '')
to_folder = request.POST.get('to_folder', '')
user_sub_folders = get_object_or_404(UserSubscriptionFolders, user=request.user)
user_sub_folders = user_sub_folders.move_feed_to_folder(feed_id, in_folder=in_folder, to_folder=to_folder)
return dict(code=1, folders=json.decode(user_sub_folders.folders))
@ajax_login_required
@json.json_view
def move_folder_to_folder(request):
folder_name = request.POST['folder_name']
in_folder = request.POST.get('in_folder', '')
to_folder = request.POST.get('to_folder', '')
user_sub_folders = get_object_or_404(UserSubscriptionFolders, user=request.user)
user_sub_folders = user_sub_folders.move_folder_to_folder(folder_name, in_folder=in_folder, to_folder=to_folder)
return dict(code=1, folders=json.decode(user_sub_folders.folders))
@login_required
def add_feature(request):
if not request.user.is_staff:
@ -1064,6 +1098,7 @@ def send_story_email(request):
text = render_to_string('mail/email_story_text.xhtml', locals())
html = render_to_string('mail/email_story_html.xhtml', locals())
subject = "%s is sharing a story with you: \"%s\"" % (from_name, story['story_title'])
subject = subject.replace('\n', ' ')
msg = EmailMultiAlternatives(subject, text,
from_email='NewsBlur <%s>' % from_address,
to=[to_address],

View file

@ -7,6 +7,7 @@ from utils import feed_fetcher
from utils.management_functions import daemonize
import socket
import datetime
import redis
class Command(BaseCommand):
@ -63,6 +64,12 @@ class Command(BaseCommand):
options['compute_scores'] = True
import pymongo
db = pymongo.Connection(settings.MONGODB_SLAVE['host'], slave_okay=True, replicaset='nbset').newsblur
options['slave_db'] = db
disp = feed_fetcher.Dispatcher(options, num_workers)
feeds_queue = []

View file

@ -4,11 +4,11 @@ import random
import re
import math
import mongoengine as mongo
import redis
import zlib
import urllib
from collections import defaultdict
from operator import itemgetter
from BeautifulSoup import BeautifulStoneSoup
# from nltk.collocations import TrigramCollocationFinder, BigramCollocationFinder, TrigramAssocMeasures, BigramAssocMeasures
from django.db import models
from django.db import IntegrityError
@ -29,6 +29,7 @@ from utils.feed_functions import timelimit, TimeoutError
from utils.feed_functions import relative_timesince
from utils.feed_functions import seconds_timesince
from utils.story_functions import pre_process_story
from utils.story_functions import bunch
from utils.diff import HTMLDiff
ENTRY_NEW, ENTRY_UPDATED, ENTRY_SAME, ENTRY_ERR = range(4)
@ -236,6 +237,7 @@ class Feed(models.Model):
# %s - %s - %s
# """ % (feed_address, self.__dict__, pprint(self.__dict__))
# mail_admins('Wierdo alert', message, fail_silently=True)
logging.debug(" ---> Feed points to 'Wierdo', ignoring.")
return False
try:
self.feed_address = feed_address
@ -549,7 +551,7 @@ class Feed(models.Model):
self.data.feed_classifier_counts = json.encode(scores)
self.data.save()
def update(self, force=False, single_threaded=True, compute_scores=True):
def update(self, force=False, single_threaded=True, compute_scores=True, slave_db=None):
from utils import feed_fetcher
try:
self.feed_address = self.feed_address % {'NEWSBLUR_DIR': settings.NEWSBLUR_DIR}
@ -565,6 +567,7 @@ class Feed(models.Model):
'single_threaded': single_threaded,
'force': force,
'compute_scores': compute_scores,
'slave_db': slave_db,
}
disp = feed_fetcher.Dispatcher(options, 1)
disp.add_jobs([[self.pk]])
@ -623,6 +626,16 @@ class Feed(models.Model):
# logging.debug('- Updated story in feed (%s - %s): %s / %s' % (self.feed_title, story.get('title'), len(existing_story.story_content), len(story_content)))
story_guid = story.get('guid') or story.get('id') or story.get('link')
original_content = None
try:
if existing_story and existing_story.id:
existing_story = MStory.objects.get(id=existing_story.id)
elif existing_story and existing_story.story_guid:
existing_story = MStory.objects.get(story_feed_id=existing_story.story_feed_id, story_guid=existing_story.story_guid)
else:
raise MStory.DoesNotExist
except MStory.DoesNotExist:
ret_values[ENTRY_ERR] += 1
continue
if existing_story.story_original_content_z:
original_content = zlib.decompress(existing_story.story_original_content_z)
elif existing_story.story_content_z:
@ -742,11 +755,19 @@ class Feed(models.Model):
# print "Found %s user stories. Deleting..." % userstories.count()
userstories.delete()
def get_stories(self, offset=0, limit=25, force=False):
def get_stories(self, offset=0, limit=25, force=False, slave=False):
stories = cache.get('feed_stories:%s-%s-%s' % (self.id, offset, limit), [])
if not stories or force:
stories_db = MStory.objects(story_feed_id=self.pk)[offset:offset+limit]
if slave:
import pymongo
db = pymongo.Connection(['db01'], slave_okay=True, replicaset='nbset').newsblur
stories_db_orig = db.stories.find({"story_feed_id": self.pk})[offset:offset+limit]
stories_db = []
for story in stories_db_orig:
stories_db.append(bunch(story))
else:
stories_db = MStory.objects(story_feed_id=self.pk)[offset:offset+limit]
stories = Feed.format_stories(stories_db, self.pk)
cache.set('feed_stories:%s-%s-%s' % (self.id, offset, limit), stories)
@ -894,8 +915,8 @@ class Feed(models.Model):
# 2 subscribers:
# 1 update per day = 1 hours
# 10 updates = 20 minutes
updates_per_day_delay = 12 * 60 / max(.25, ((max(0, self.active_subscribers)**.35)
* (updates_per_month**1.2)))
updates_per_day_delay = 3 * 60 / max(.25, ((max(0, self.active_subscribers)**.2)
* (updates_per_month**0.35)))
if self.premium_subscribers > 0:
updates_per_day_delay /= min(self.active_subscribers+self.premium_subscribers, 5)
# Lots of subscribers = lots of updates
@ -1136,7 +1157,7 @@ class MFeedFetchHistory(mongo.Document):
'collection': 'feed_fetch_history',
'allow_inheritance': False,
'ordering': ['-fetch_date'],
'indexes': [('fetch_date', 'status_code'), ('feed_id', 'status_code'), ('feed_id', '-fetch_date')],
'indexes': ['-fetch_date', ('fetch_date', 'status_code'), ('feed_id', 'status_code')],
}
def save(self, *args, **kwargs):

View file

@ -1,5 +1,6 @@
from celery.task import Task
from utils import log as logging
from django.conf import settings
class UpdateFeeds(Task):
name = 'update-feeds'
@ -11,10 +12,13 @@ class UpdateFeeds(Task):
if not isinstance(feed_pks, list):
feed_pks = [feed_pks]
import pymongo
db = pymongo.Connection(settings.MONGODB_SLAVE['host'], slave_okay=True).newsblur
for feed_pk in feed_pks:
try:
feed = Feed.objects.get(pk=feed_pk)
feed.update()
feed.update(slave_db=db)
except Feed.DoesNotExist:
logging.info(" ---> Feed doesn't exist: [%s]" % feed_pk)
# logging.debug(' Updating: [%s] %s' % (feed_pks, feed))

View file

@ -36,26 +36,36 @@ class MStatistics(mongo.Document):
@classmethod
def collect_statistics(cls):
now = datetime.datetime.now()
last_day = datetime.datetime.now() - datetime.timedelta(hours=24)
cls.collect_statistics_feeds_fetched(last_day)
print "Feeds Fetched: %s" % (datetime.datetime.now() - now)
cls.collect_statistics_premium_users(last_day)
print "Premiums: %s" % (datetime.datetime.now() - now)
cls.collect_statistics_standard_users(last_day)
print "Standard users: %s" % (datetime.datetime.now() - now)
cls.collect_statistics_sites_loaded(last_day)
print "Sites loaded: %s" % (datetime.datetime.now() - now)
@classmethod
def collect_statistics_feeds_fetched(cls, last_day=None):
if not last_day:
last_day = datetime.datetime.now() - datetime.timedelta(hours=24)
feeds_fetched = MFeedFetchHistory.objects(fetch_date__gte=last_day).count()
feeds_fetched = MFeedFetchHistory.objects.count()
cls.objects(key='feeds_fetched').update_one(upsert=True, key='feeds_fetched', value=feeds_fetched)
pages_fetched = MPageFetchHistory.objects.count()
cls.objects(key='pages_fetched').update_one(upsert=True, key='pages_fetched', value=pages_fetched)
old_fetch_histories = MFeedFetchHistory.objects(fetch_date__lte=last_day)
for history in old_fetch_histories:
history.delete()
old_page_histories = MPageFetchHistory.objects(fetch_date__lte=last_day)
for history in old_page_histories:
history.delete()
from utils.feed_functions import timelimit, TimeoutError
@timelimit(60)
def delete_old_history():
MFeedFetchHistory.objects(fetch_date__lt=last_day).delete()
MPageFetchHistory.objects(fetch_date__lt=last_day).delete()
try:
delete_old_history()
except TimeoutError:
print "Timed out on deleting old history. Shit."
return feeds_fetched

View file

@ -9,7 +9,7 @@
199.15.250.229 app02 app02.newsblur.com
199.15.253.218 db01 db01.newsblur.com
199.15.253.162 db02 db02.newsblur.com
199.15.250.230 db03 db03.newsblur.com
199.15.253.226 db03 db03.newsblur.com
199.15.250.231 task01 task01.newsblur.com
199.15.250.250 task02 task02.newsblur.com
199.15.250.233 task03 task03.newsblur.com

View file

@ -1,11 +1,18 @@
upstream app_server {
server 127.0.0.1:8000 fail_timeout=1;
server 127.0.0.1:8000 fail_timeout=10 max_fails=3 ;
server app02.newsblur.com:80 fail_timeout=10 max_fails=3 ;
# server db01.newsblur.com:80 fail_timeout=10 max_fails=3 down;
}
server {
server_name newsblur.com;
rewrite ^(.*) http://www.newsblur.com$1 permanent;
}
server {
listen 80 default;
client_max_body_size 4M;
server_name _;
server_name www.newsblur.com;
location /media/admin/ {
alias /usr/local/lib/python2.6/dist-packages/Django-1.2.5-py2.6.egg/django/contrib/admin/media/;
@ -40,7 +47,8 @@ server {
location / {
if (-f /home/sclay/newsblur/media/maintenance.html) {
expires -1;
expires 10;
add_header Cache-Control private;
rewrite ^(.*)$ /media/maintenance.html last;
break;
}

42
config/redis-init Normal file
View file

@ -0,0 +1,42 @@
#!/bin/sh
#
# Simple Redis init.d script conceived to work on Linux systems
# as it does use of the /proc filesystem.
REDISPORT=6379
EXEC=/usr/local/bin/redis-server
CLIEXEC=/usr/local/bin/redis-cli
PIDFILE=/var/log/redis.pid
CONF="/etc/redis.conf"
case "$1" in
start)
if [ -f $PIDFILE ]
then
echo "$PIDFILE exists, process is already running or crashed"
else
echo "Starting Redis server..."
$EXEC $CONF
fi
;;
stop)
if [ ! -f $PIDFILE ]
then
echo "$PIDFILE does not exist, process is not running"
else
PID=$(cat $PIDFILE)
echo "Stopping ..."
$CLIEXEC -p $REDISPORT shutdown
while [ -x /proc/${PID} ]
do
echo "Waiting for Redis to shutdown ..."
sleep 1
done
echo "Redis stopped"
fi
;;
*)
echo "Please use start or stop as first argument"
;;
esac

465
config/redis.conf Normal file
View file

@ -0,0 +1,465 @@
# Redis configuration file example
# Note on units: when memory size is needed, it is possible to specifiy
# it in the usual form of 1k 5GB 4M and so forth:
#
# 1k => 1000 bytes
# 1kb => 1024 bytes
# 1m => 1000000 bytes
# 1mb => 1024*1024 bytes
# 1g => 1000000000 bytes
# 1gb => 1024*1024*1024 bytes
#
# units are case insensitive so 1GB 1Gb 1gB are all the same.
# By default Redis does not run as a daemon. Use 'yes' if you need it.
# Note that Redis will write a pid file in /var/run/redis.pid when daemonized.
daemonize yes
# When running daemonized, Redis writes a pid file in /var/run/redis.pid by
# default. You can specify a custom pid file location here.
pidfile /var/log/redis.pid
# Accept connections on the specified port, default is 6379.
# If port 0 is specified Redis will not listen on a TCP socket.
port 6379
# If you want you can bind a single interface, if the bind option is not
# specified all the interfaces will listen for incoming connections.
#
# bind 127.0.0.1
# Specify the path for the unix socket that will be used to listen for
# incoming connections. There is no default, so Redis will not listen
# on a unix socket when not specified.
#
# unixsocket /tmp/redis.sock
# unixsocketperm 755
# Close the connection after a client is idle for N seconds (0 to disable)
timeout 300
# Set server verbosity to 'debug'
# it can be one of:
# debug (a lot of information, useful for development/testing)
# verbose (many rarely useful info, but not a mess like the debug level)
# notice (moderately verbose, what you want in production probably)
# warning (only very important / critical messages are logged)
loglevel verbose
# Specify the log file name. Also 'stdout' can be used to force
# Redis to log on the standard output. Note that if you use standard
# output for logging but daemonize, logs will be sent to /dev/null
logfile /var/log/redis.log
# To enable logging to the system logger, just set 'syslog-enabled' to yes,
# and optionally update the other syslog parameters to suit your needs.
# syslog-enabled no
# Specify the syslog identity.
# syslog-ident redis
# Specify the syslog facility. Must be USER or between LOCAL0-LOCAL7.
# syslog-facility local0
# Set the number of databases. The default database is DB 0, you can select
# a different one on a per-connection basis using SELECT <dbid> where
# dbid is a number between 0 and 'databases'-1
databases 16
################################ SNAPSHOTTING #################################
#
# Save the DB on disk:
#
# save <seconds> <changes>
#
# Will save the DB if both the given number of seconds and the given
# number of write operations against the DB occurred.
#
# In the example below the behaviour will be to save:
# after 900 sec (15 min) if at least 1 key changed
# after 300 sec (5 min) if at least 10 keys changed
# after 60 sec if at least 10000 keys changed
#
# Note: you can disable saving at all commenting all the "save" lines.
save 900 1
save 300 10
save 60 10000
# Compress string objects using LZF when dump .rdb databases?
# For default that's set to 'yes' as it's almost always a win.
# If you want to save some CPU in the saving child set it to 'no' but
# the dataset will likely be bigger if you have compressible values or keys.
rdbcompression yes
# The filename where to dump the DB
dbfilename dump.rdb
# The working directory.
#
# The DB will be written inside this directory, with the filename specified
# above using the 'dbfilename' configuration directive.
#
# Also the Append Only File will be created inside this directory.
#
# Note that you must specify a directory here, not a file name.
dir /var/lib/redis
################################# REPLICATION #################################
# Master-Slave replication. Use slaveof to make a Redis instance a copy of
# another Redis server. Note that the configuration is local to the slave
# so for example it is possible to configure the slave to save the DB with a
# different interval, or to listen to another port, and so on.
#
# slaveof <masterip> <masterport>
# If the master is password protected (using the "requirepass" configuration
# directive below) it is possible to tell the slave to authenticate before
# starting the replication synchronization process, otherwise the master will
# refuse the slave request.
#
# masterauth <master-password>
# When a slave lost the connection with the master, or when the replication
# is still in progress, the slave can act in two different ways:
#
# 1) if slave-serve-stale-data is set to 'yes' (the default) the slave will
# still reply to client requests, possibly with out of data data, or the
# data set may just be empty if this is the first synchronization.
#
# 2) if slave-serve-stale data is set to 'no' the slave will reply with
# an error "SYNC with master in progress" to all the kind of commands
# but to INFO and SLAVEOF.
#
slave-serve-stale-data yes
################################## SECURITY ###################################
# Require clients to issue AUTH <PASSWORD> before processing any other
# commands. This might be useful in environments in which you do not trust
# others with access to the host running redis-server.
#
# This should stay commented out for backward compatibility and because most
# people do not need auth (e.g. they run their own servers).
#
# Warning: since Redis is pretty fast an outside user can try up to
# 150k passwords per second against a good box. This means that you should
# use a very strong password otherwise it will be very easy to break.
#
# requirepass foobared
# Command renaming.
#
# It is possilbe to change the name of dangerous commands in a shared
# environment. For instance the CONFIG command may be renamed into something
# of hard to guess so that it will be still available for internal-use
# tools but not available for general clients.
#
# Example:
#
# rename-command CONFIG b840fc02d524045429941cc15f59e41cb7be6c52
#
# It is also possilbe to completely kill a command renaming it into
# an empty string:
#
# rename-command CONFIG ""
################################### LIMITS ####################################
# Set the max number of connected clients at the same time. By default there
# is no limit, and it's up to the number of file descriptors the Redis process
# is able to open. The special value '0' means no limits.
# Once the limit is reached Redis will close all the new connections sending
# an error 'max number of clients reached'.
#
# maxclients 128
# Don't use more memory than the specified amount of bytes.
# When the memory limit is reached Redis will try to remove keys with an
# EXPIRE set. It will try to start freeing keys that are going to expire
# in little time and preserve keys with a longer time to live.
# Redis will also try to remove objects from free lists if possible.
#
# If all this fails, Redis will start to reply with errors to commands
# that will use more memory, like SET, LPUSH, and so on, and will continue
# to reply to most read-only commands like GET.
#
# WARNING: maxmemory can be a good idea mainly if you want to use Redis as a
# 'state' server or cache, not as a real DB. When Redis is used as a real
# database the memory usage will grow over the weeks, it will be obvious if
# it is going to use too much memory in the long run, and you'll have the time
# to upgrade. With maxmemory after the limit is reached you'll start to get
# errors for write operations, and this may even lead to DB inconsistency.
#
# maxmemory <bytes>
# MAXMEMORY POLICY: how Redis will select what to remove when maxmemory
# is reached? You can select among five behavior:
#
# volatile-lru -> remove the key with an expire set using an LRU algorithm
# allkeys-lru -> remove any key accordingly to the LRU algorithm
# volatile-random -> remove a random key with an expire set
# allkeys->random -> remove a random key, any key
# volatile-ttl -> remove the key with the nearest expire time (minor TTL)
# noeviction -> don't expire at all, just return an error on write operations
#
# Note: with all the kind of policies, Redis will return an error on write
# operations, when there are not suitable keys for eviction.
#
# At the date of writing this commands are: set setnx setex append
# incr decr rpush lpush rpushx lpushx linsert lset rpoplpush sadd
# sinter sinterstore sunion sunionstore sdiff sdiffstore zadd zincrby
# zunionstore zinterstore hset hsetnx hmset hincrby incrby decrby
# getset mset msetnx exec sort
#
# The default is:
#
# maxmemory-policy volatile-lru
# LRU and minimal TTL algorithms are not precise algorithms but approximated
# algorithms (in order to save memory), so you can select as well the sample
# size to check. For instance for default Redis will check three keys and
# pick the one that was used less recently, you can change the sample size
# using the following configuration directive.
#
# maxmemory-samples 3
############################## APPEND ONLY MODE ###############################
# By default Redis asynchronously dumps the dataset on disk. If you can live
# with the idea that the latest records will be lost if something like a crash
# happens this is the preferred way to run Redis. If instead you care a lot
# about your data and don't want to that a single record can get lost you should
# enable the append only mode: when this mode is enabled Redis will append
# every write operation received in the file appendonly.aof. This file will
# be read on startup in order to rebuild the full dataset in memory.
#
# Note that you can have both the async dumps and the append only file if you
# like (you have to comment the "save" statements above to disable the dumps).
# Still if append only mode is enabled Redis will load the data from the
# log file at startup ignoring the dump.rdb file.
#
# IMPORTANT: Check the BGREWRITEAOF to check how to rewrite the append
# log file in background when it gets too big.
appendonly no
# The name of the append only file (default: "appendonly.aof")
# appendfilename appendonly.aof
# The fsync() call tells the Operating System to actually write data on disk
# instead to wait for more data in the output buffer. Some OS will really flush
# data on disk, some other OS will just try to do it ASAP.
#
# Redis supports three different modes:
#
# no: don't fsync, just let the OS flush the data when it wants. Faster.
# always: fsync after every write to the append only log . Slow, Safest.
# everysec: fsync only if one second passed since the last fsync. Compromise.
#
# The default is "everysec" that's usually the right compromise between
# speed and data safety. It's up to you to understand if you can relax this to
# "no" that will will let the operating system flush the output buffer when
# it wants, for better performances (but if you can live with the idea of
# some data loss consider the default persistence mode that's snapshotting),
# or on the contrary, use "always" that's very slow but a bit safer than
# everysec.
#
# If unsure, use "everysec".
# appendfsync always
appendfsync everysec
# appendfsync no
# When the AOF fsync policy is set to always or everysec, and a background
# saving process (a background save or AOF log background rewriting) is
# performing a lot of I/O against the disk, in some Linux configurations
# Redis may block too long on the fsync() call. Note that there is no fix for
# this currently, as even performing fsync in a different thread will block
# our synchronous write(2) call.
#
# In order to mitigate this problem it's possible to use the following option
# that will prevent fsync() from being called in the main process while a
# BGSAVE or BGREWRITEAOF is in progress.
#
# This means that while another child is saving the durability of Redis is
# the same as "appendfsync none", that in pratical terms means that it is
# possible to lost up to 30 seconds of log in the worst scenario (with the
# default Linux settings).
#
# If you have latency problems turn this to "yes". Otherwise leave it as
# "no" that is the safest pick from the point of view of durability.
no-appendfsync-on-rewrite no
# Automatic rewrite of the append only file.
# Redis is able to automatically rewrite the log file implicitly calling
# BGREWRITEAOF when the AOF log size will growth by the specified percentage.
#
# This is how it works: Redis remembers the size of the AOF file after the
# latest rewrite (or if no rewrite happened since the restart, the size of
# the AOF at startup is used).
#
# This base size is compared to the current size. If the current size is
# bigger than the specified percentage, the rewrite is triggered. Also
# you need to specify a minimal size for the AOF file to be rewritten, this
# is useful to avoid rewriting the AOF file even if the percentage increase
# is reached but it is still pretty small.
#
# Specify a precentage of zero in order to disable the automatic AOF
# rewrite feature.
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
################################## SLOW LOG ###################################
# The Redis Slow Log is a system to log queries that exceeded a specified
# execution time. The execution time does not include the I/O operations
# like talking with the client, sending the reply and so forth,
# but just the time needed to actually execute the command (this is the only
# stage of command execution where the thread is blocked and can not serve
# other requests in the meantime).
#
# You can configure the slow log with two parameters: one tells Redis
# what is the execution time, in microseconds, to exceed in order for the
# command to get logged, and the other parameter is the length of the
# slow log. When a new command is logged the oldest one is removed from the
# queue of logged commands.
# The following time is expressed in microseconds, so 1000000 is equivalent
# to one second. Note that a negative number disables the slow log, while
# a value of zero forces the logging of every command.
slowlog-log-slower-than 10000
# There is no limit to this length. Just be aware that it will consume memory.
# You can reclaim memory used by the slow log with SLOWLOG RESET.
slowlog-max-len 1024
################################ VIRTUAL MEMORY ###############################
### WARNING! Virtual Memory is deprecated in Redis 2.4
### The use of Virtual Memory is strongly discouraged.
# Virtual Memory allows Redis to work with datasets bigger than the actual
# amount of RAM needed to hold the whole dataset in memory.
# In order to do so very used keys are taken in memory while the other keys
# are swapped into a swap file, similarly to what operating systems do
# with memory pages.
#
# To enable VM just set 'vm-enabled' to yes, and set the following three
# VM parameters accordingly to your needs.
vm-enabled no
# vm-enabled yes
# This is the path of the Redis swap file. As you can guess, swap files
# can't be shared by different Redis instances, so make sure to use a swap
# file for every redis process you are running. Redis will complain if the
# swap file is already in use.
#
# The best kind of storage for the Redis swap file (that's accessed at random)
# is a Solid State Disk (SSD).
#
# *** WARNING *** if you are using a shared hosting the default of putting
# the swap file under /tmp is not secure. Create a dir with access granted
# only to Redis user and configure Redis to create the swap file there.
vm-swap-file /tmp/redis.swap
# vm-max-memory configures the VM to use at max the specified amount of
# RAM. Everything that deos not fit will be swapped on disk *if* possible, that
# is, if there is still enough contiguous space in the swap file.
#
# With vm-max-memory 0 the system will swap everything it can. Not a good
# default, just specify the max amount of RAM you can in bytes, but it's
# better to leave some margin. For instance specify an amount of RAM
# that's more or less between 60 and 80% of your free RAM.
vm-max-memory 0
# Redis swap files is split into pages. An object can be saved using multiple
# contiguous pages, but pages can't be shared between different objects.
# So if your page is too big, small objects swapped out on disk will waste
# a lot of space. If you page is too small, there is less space in the swap
# file (assuming you configured the same number of total swap file pages).
#
# If you use a lot of small objects, use a page size of 64 or 32 bytes.
# If you use a lot of big objects, use a bigger page size.
# If unsure, use the default :)
vm-page-size 32
# Number of total memory pages in the swap file.
# Given that the page table (a bitmap of free/used pages) is taken in memory,
# every 8 pages on disk will consume 1 byte of RAM.
#
# The total swap size is vm-page-size * vm-pages
#
# With the default of 32-bytes memory pages and 134217728 pages Redis will
# use a 4 GB swap file, that will use 16 MB of RAM for the page table.
#
# It's better to use the smallest acceptable value for your application,
# but the default is large in order to work in most conditions.
vm-pages 134217728
# Max number of VM I/O threads running at the same time.
# This threads are used to read/write data from/to swap file, since they
# also encode and decode objects from disk to memory or the reverse, a bigger
# number of threads can help with big objects even if they can't help with
# I/O itself as the physical device may not be able to couple with many
# reads/writes operations at the same time.
# Hashes are encoded in a special way (much more memory efficient) when they
# have at max a given numer of elements, and the biggest element does not
# exceed a given threshold. You can configure this limits with the following
# configuration directives.
hash-max-zipmap-entries 512
hash-max-zipmap-value 64
# Similarly to hashes, small lists are also encoded in a special way in order
# to save a lot of space. The special representation is only used when
# you are under the following limits:
list-max-ziplist-entries 512
list-max-ziplist-value 64
# Sets have a special encoding in just one case: when a set is composed
# of just strings that happens to be integers in radix 10 in the range
# of 64 bit signed integers.
# The following configuration setting sets the limit in the size of the
# set in order to use this special memory saving encoding.
set-max-intset-entries 512
# Similarly to hashes and lists, sorted sets are also specially encoded in
# order to save a lot of space. This encoding is only used when the length and
# elements of a sorted set are below the following limits:
zset-max-ziplist-entries 128
zset-max-ziplist-value 64
# Active rehashing uses 1 millisecond every 100 milliseconds of CPU time in
# order to help rehashing the main Redis hash table (the one mapping top-level
# keys to values). The hash table implementation redis uses (see dict.c)
# performs a lazy rehashing: the more operation you run into an hash table
# that is rhashing, the more rehashing "steps" are performed, so if the
# server is idle the rehashing is never complete and some more memory is used
# by the hash table.
#
# The default is to use this millisecond 10 times every second in order to
# active rehashing the main dictionaries, freeing memory when possible.
#
# If unsure:
# use "activerehashing no" if you have hard latency requirements and it is
# not a good thing in your environment that Redis can reply form time to time
# to queries with 2 milliseconds delay.
#
# use "activerehashing yes" if you don't have such hard requirements but
# want to free memory asap when possible.
activerehashing yes
################################## INCLUDES ###################################
# Include one or more other config files here. This is useful if you
# have a standard template that goes to all redis server but also need
# to customize a few per-server settings. Include files can include
# other files, so use this wisely.
#
# include /path/to/local.conf
# include /path/to/other.conf

View file

@ -6,6 +6,8 @@ export ZSH=$HOME/.oh-my-zsh
# Look in ~/.oh-my-zsh/themes/
export ZSH_THEME="risto"
export DISABLE_AUTO_UPDATE="true"
# Set to this to use case-sensitive completion
export CASE_SENSITIVE="true"
export LC_COLLATE='C'

57
fabfile.py vendored
View file

@ -33,8 +33,8 @@ env.roledefs ={
'local': ['localhost'],
'app': ['app01.newsblur.com', 'app02.newsblur.com'],
'web': ['www.newsblur.com', 'app02.newsblur.com'],
'db': ['db01.newsblur.com', 'db02.newsblur.com'],
'task': ['task01.newsblur.com', 'task02.newsblur.com', 'task03.newsblur.com'],
'db': ['db01.newsblur.com', 'db02.newsblur.com', 'db03.newsblur.com'],
'task': ['task01.newsblur.com', 'task02.newsblur.com', 'task03.newsblur.com', 'db02.newsblur.com'],
}
# ================
@ -73,9 +73,9 @@ def deploy():
with cd(env.NEWSBLUR_PATH):
run('git pull')
run('kill -HUP `cat logs/gunicorn.pid`')
run('curl -s http://www.newsblur.com > /dev/null')
run('curl -s http://www.newsblur.com/m/ > /dev/null')
run('curl -s http://www.newsblur.com/api/add_site_load_script/ABCDEF > /dev/null')
run('curl -s http://%s > /dev/null' % env.host)
# run('curl -s http://%s/m/ > /dev/null' % env.host)
run('curl -s http://%s/api/add_site_load_script/ABCDEF > /dev/null' % env.host)
compress_media()
@roles('web')
@ -206,8 +206,11 @@ def setup_db():
setup_db_firewall()
setup_db_motd()
setup_rabbitmq()
setup_memcached()
setup_postgres()
setup_mongo()
setup_gunicorn(supervisor=False)
setup_redis()
def setup_task():
setup_common()
@ -225,10 +228,10 @@ def setup_task():
def setup_installs():
sudo('apt-get -y update')
sudo('apt-get -y upgrade')
sudo('apt-get -y install build-essential gcc scons libreadline-dev sysstat iotop git zsh python-dev locate python-software-properties libpcre3-dev libdbd-pg-perl libssl-dev make pgbouncer python-psycopg2 libmemcache0 memcached python-memcache libyaml-0-2 python-yaml python-numpy python-scipy python-imaging munin munin-node munin-plugins-extra curl ntp monit')
sudo('add-apt-repository ppa:pitti/postgresql')
sudo('apt-get -y install build-essential gcc scons libreadline-dev sysstat iotop git zsh python-dev locate python-software-properties libpcre3-dev libdbd-pg-perl libssl-dev make pgbouncer python-psycopg2 libmemcache0 python-memcache libyaml-0-2 python-yaml python-numpy python-scipy python-imaging munin munin-node munin-plugins-extra curl ntp monit')
# sudo('add-apt-repository ppa:pitti/postgresql')
sudo('apt-get -y update')
sudo('apt-get -y install postgresql-client-9.0')
sudo('apt-get -y install postgresql-client')
sudo('mkdir -p /var/run/postgresql')
sudo('chown postgres.postgres /var/run/postgresql')
put('config/munin.conf', '/etc/munin/munin.conf', use_sudo=True)
@ -288,7 +291,7 @@ def setup_psycopg():
def setup_python():
sudo('easy_install pip')
sudo('easy_install fabric django celery django-celery django-compress South django-extensions pymongo BeautifulSoup pyyaml nltk==0.9.9 lxml oauth2 pytz boto seacucumber')
sudo('easy_install fabric django celery django-celery django-compress South django-extensions pymongo BeautifulSoup pyyaml nltk==0.9.9 lxml oauth2 pytz boto seacucumber django_ses mongoengine redis')
put('config/pystartup.py', '.pystartup')
with cd(os.path.join(env.NEWSBLUR_PATH, 'vendor/cjson')):
@ -367,10 +370,10 @@ def setup_nginx():
with settings(warn_only=True):
sudo("groupadd nginx")
sudo("useradd -g nginx -d /var/www/htdocs -s /bin/false nginx")
run('wget http://sysoev.ru/nginx/nginx-0.9.5.tar.gz')
run('tar -xzf nginx-0.9.5.tar.gz')
run('rm nginx-0.9.5.tar.gz')
with cd('nginx-0.9.5'):
run('wget http://nginx.org/download/nginx-1.1.7.tar.gz')
run('tar -xzf nginx-1.1.7.tar.gz')
run('rm nginx-1.1.7.tar.gz')
with cd('nginx-1.1.7'):
run('./configure --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module')
run('make')
sudo('make install')
@ -384,6 +387,12 @@ def configure_nginx():
sudo("chmod 0755 /etc/init.d/nginx")
sudo("/usr/sbin/update-rc.d -f nginx defaults")
sudo("/etc/init.d/nginx restart")
def configure_node():
sudo("apt-get install node")
sudo("curl http://npmjs.org/install.sh | sudo sh")
sudo("npm install -g redis")
sudo("npm install -g socket.io")
# ===============
# = Setup - App =
@ -436,6 +445,10 @@ def setup_db_firewall():
sudo('ufw allow from 199.15.250.0/24 to any port 27017') # MongoDB
sudo('ufw allow from 199.15.253.0/24 to any port 5672 ') # RabbitMQ
sudo('ufw allow from 199.15.250.0/24 to any port 5672 ') # RabbitMQ
sudo('ufw allow from 199.15.250.0/24 to any port 6379 ') # Redis
sudo('ufw allow from 199.15.253.0/24 to any port 6379 ') # Redis
sudo('ufw allow from 199.15.250.0/24 to any port 11211 ') # Memcached
sudo('ufw allow from 199.15.253.0/24 to any port 11211 ') # Memcached
sudo('ufw --force enable')
def setup_db_motd():
@ -452,8 +465,11 @@ def setup_rabbitmq():
sudo('rabbitmqctl add_vhost newsblurvhost')
sudo('rabbitmqctl set_permissions -p newsblurvhost newsblur ".*" ".*" ".*"')
def setup_memcached():
sudo('apt-get -y install memcached')
def setup_postgres():
sudo('apt-get -y install postgresql-9.0 postgresql-client-9.0 postgresql-contrib-9.0 libpq-dev')
sudo('apt-get -y install postgresql postgresql-client postgresql-contrib libpq-dev')
def setup_mongo():
sudo('apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10')
@ -461,6 +477,19 @@ def setup_mongo():
sudo('echo "deb http://downloads-distro.mongodb.org/repo/debian-sysvinit dist 10gen" >> /etc/apt/sources.list')
sudo('apt-get update')
sudo('apt-get -y install mongodb-10gen')
def setup_redis():
with cd(env.VENDOR_PATH):
run('wget http://redis.googlecode.com/files/redis-2.4.2.tar.gz')
run('tar -xzf redis-2.4.2.tar.gz')
run('rm redis-2.4.2.tar.gz')
with cd(os.path.join(env.VENDOR_PATH, 'redis-2.4.2')):
sudo('make install')
put('config/redis-init', '/etc/init.d/redis', use_sudo=True)
sudo('chmod u+x /etc/init.d/redis')
put('config/redis.conf', '/etc/redis.conf', use_sudo=True)
sudo('mkdir -p /var/lib/redis')
sudo('update-rc.d redis defaults')
# ================
# = Setup - Task =

View file

@ -827,6 +827,9 @@ body.NB-theme-serif #story_pane .NB-feed-story-content {
text-transform: uppercase;
height: 14px;
}
#NB-progress.NB-progress-error .NB-progress-title {
height: auto;
}
#NB-progress .NB-progress-bar {
height:6px;
@ -855,7 +858,7 @@ body.NB-theme-serif #story_pane .NB-feed-story-content {
}
#NB-progress.NB-progress-error {
height: 120px;
height: 80px;
}
#NB-progress.NB-progress-big {
height: 72px;
@ -872,7 +875,7 @@ body.NB-theme-serif #story_pane .NB-feed-story-content {
}
#NB-progress.NB-progress-big .NB-progress-link {
margin: 14px 0 0;
margin: 6px 0 0;
}
#NB-progress.NB-progress-big .NB-progress-link a {
@ -1597,11 +1600,38 @@ background: transparent;
font-size: 16px;
padding: 0 250px 0 28px;
background: #dadada url('../theme/images/dadada_40x100_textures_03_highlight_soft_75.png') 0 50% repeat-x;
background-image: -webkit-gradient(
linear,
left bottom,
left top,
color-stop(0.36, rgba(212, 212, 212, 250)),
color-stop(0.84, rgba(244, 244, 244, 250))
);
background-image: -moz-linear-gradient(
center bottom,
rgb(212, 212, 212) 36%,
rgb(244, 244, 244) 84%
);
border-bottom: 1px solid #ADADAD;
position: relative;
overflow: hidden;
}
#story_pane .read .NB-feed-story-header-info {
background-image: -webkit-gradient(
linear,
left bottom,
left top,
color-stop(0.36, rgba(214, 214, 214, 250)),
color-stop(0.84, rgba(230, 230, 230, 250))
);
background-image: -moz-linear-gradient(
center bottom,
rgb(212, 212, 212) 36%,
rgb(244, 244, 244) 84%
);
}
#story_pane .NB-feed-story-header-feed {
background: #404040 url('../img/reader/feed_view_feed_background.png') repeat-x 0 0;
background-image: -webkit-gradient(
@ -1723,6 +1753,10 @@ background: transparent;
text-shadow: 1px 1px 0 #e8e8e8;
}
#story_pane .read a.NB-feed-story-title {
color: #1C212F;
}
#story_pane a.NB-feed-story-title:hover,
#story_pane a.NB-feed-story-title:hover .NB-score-1,
#story_pane a.NB-feed-story-title:hover .NB-score--1 {
@ -1738,6 +1772,9 @@ background: transparent;
text-shadow: 1px 1px 0 #F0F0F0;
cursor: pointer;
}
#story_pane .read .NB-feed-story-author {
color: #A0A0A0;
}
#story_pane .NB-feed-story-author.NB-score-1 {
color: #34912E;
}
@ -1791,6 +1828,10 @@ background: transparent;
-webkit-border-radius: 4px;
cursor: pointer;
}
#story_pane .read .NB-feed-story-tag {
color: #B1ADA3;
}
#story_pane .NB-feed-story-tag.NB-score-1 {
/* Green */
background-color: #34912E;
@ -1886,6 +1927,7 @@ background: transparent;
#story_pane .NB-feed-story-content {
margin: 0 140px 32px 28px;
padding: 12px 0px;
max-width: 700px;
}
#story_pane .NB-feed-story-endbar {
@ -1930,6 +1972,35 @@ background: transparent;
height: 8px;
}
/* ============== */
/* = Feed Error = */
/* ============== */
#story_taskbar .NB-feed-error {
position: absolute;
top: 0;
margin: 2px 0 0 0;
width: 120px;
height: 20px;
}
#story_taskbar .NB-feed-error .NB-feed-error-text {
text-transform: uppercase;
font-size: 10px;
text-align: center;
font-weight: bold;
color: #4E0A0B;
text-shadow: 1px 1px 0 #D8D8D8;
}
#story_taskbar .NB-feed-error .NB-feed-error-icon {
margin: 3px 0 0 0;
width: 24px;
height: 19px;
background: transparent url('../img/reader/warning.png') no-repeat 0 0;
float: left;
}
/* ======================= */
/* = Story Modifications = */
/* ======================= */
@ -4171,9 +4242,6 @@ background: transparent;
background: transparent url('../img/icons/silk/exclamation.png') no-repeat 0 1px;
font-weight: bold;
}
.NB-menu-manage .NB-menu-manage-move {
display: none;
}
.NB-menu-manage .NB-menu-manage-move .NB-menu-manage-image {
background: transparent url('../img/icons/silk/arrow_branch.png') no-repeat 0px 2px;
}
@ -4267,7 +4335,7 @@ background: transparent;
background: transparent url('../img/icons/silk/color_swatch.png') no-repeat 0 2px;
}
.NB-menu-manage .NB-menu-manage-story-thirdparty .NB-menu-manage-image {
background: transparent url('../img/reader/instapaper.png') no-repeat 0 1px;
background: transparent url('../img/icons/silk/email.png') no-repeat 0 1px;
}
.NB-menu-manage .NB-menu-manage-story-thirdparty .NB-menu-manage-thirdparty-icon {
width: 16px;
@ -4282,6 +4350,12 @@ background: transparent;
.NB-menu-manage .NB-menu-manage-story-thirdparty .NB-menu-manage-thirdparty-readitlater {
background: transparent url('../img/reader/readitlater.png') no-repeat 0 0;
}
.NB-menu-manage .NB-menu-manage-story-thirdparty .NB-menu-manage-thirdparty-pinboard {
background: transparent url('../img/reader/pinboard.png') no-repeat 0 0;
}
.NB-menu-manage .NB-menu-manage-story-thirdparty .NB-menu-manage-thirdparty-googleplus {
background: transparent url('../img/reader/googleplus.png') no-repeat 0 0;
}
.NB-menu-manage .NB-menu-manage-story-thirdparty .NB-menu-manage-thirdparty-readability {
background: transparent url('../img/reader/readability.png') no-repeat 0 0;
}
@ -4316,11 +4390,25 @@ background: transparent;
.NB-menu-manage .NB-menu-manage-story-thirdparty.NB-menu-manage-highlight-readitlater .NB-menu-manage-thirdparty-readitlater {
opacity: 1;
}
.NB-menu-manage .NB-menu-manage-story-thirdparty.NB-menu-manage-highlight-email .NB-menu-manage-image,
.NB-menu-manage .NB-menu-manage-story-thirdparty.NB-menu-manage-highlight-email .NB-menu-manage-thirdparty-icon {
.NB-menu-manage .NB-menu-manage-story-thirdparty.NB-menu-manage-highlight-pinboard .NB-menu-manage-image,
.NB-menu-manage .NB-menu-manage-story-thirdparty.NB-menu-manage-highlight-pinboard .NB-menu-manage-thirdparty-icon {
opacity: .2;
}
.NB-menu-manage .NB-menu-manage-story-thirdparty.NB-menu-manage-highlight-email .NB-menu-manage-thirdparty-email {
.NB-menu-manage .NB-menu-manage-story-thirdparty.NB-menu-manage-highlight-pinboard .NB-menu-manage-thirdparty-pinboard {
opacity: 1;
}
.NB-menu-manage .NB-menu-manage-story-thirdparty.NB-menu-manage-highlight-googleplus .NB-menu-manage-image,
.NB-menu-manage .NB-menu-manage-story-thirdparty.NB-menu-manage-highlight-googleplus .NB-menu-manage-thirdparty-icon {
opacity: .2;
}
.NB-menu-manage .NB-menu-manage-story-thirdparty.NB-menu-manage-highlight-googleplus .NB-menu-manage-thirdparty-googleplus {
opacity: 1;
}
.NB-menu-manage .NB-menu-manage-story-thirdparty.NB-menu-manage-highlight-instapaper .NB-menu-manage-image,
.NB-menu-manage .NB-menu-manage-story-thirdparty.NB-menu-manage-highlight-instapaper .NB-menu-manage-thirdparty-icon {
opacity: .2;
}
.NB-menu-manage .NB-menu-manage-story-thirdparty.NB-menu-manage-highlight-instapaper .NB-menu-manage-thirdparty-instapaper {
opacity: 1;
}
@ -5367,6 +5455,12 @@ background: transparent;
clear: both;
float: left;
}
.NB-modal-preferences .NB-preference .NB-preference-options input[type=radio] {
margin-top: 4px;
}
.NB-modal-preferences .NB-preference .NB-preference-options input[type=checkbox] {
margin-top: 5px;
}
.NB-modal-preferences .NB-preference .NB-preference-options label {
padding-left: 4px;
margin: 0 0 4px 0;
@ -5471,8 +5565,14 @@ background: transparent;
.NB-modal-preferences .NB-preference-story-share label[for=NB-preference-story-share-readitlater] {
background: transparent url('../img/reader/readitlater.png') no-repeat 0 0;
}
.NB-modal-preferences .NB-preference-story-share label[for=NB-preference-story-share-pinboard] {
background: transparent url('../img/reader/pinboard.png') no-repeat 0 0;
}
.NB-modal-preferences .NB-preference-story-share label[for=NB-preference-story-share-googleplus] {
background: transparent url('../img/reader/googleplus.png') no-repeat 0 0;
}
.NB-modal-preferences .NB-preference-story-share label[for=NB-preference-story-share-email] {
background: transparent url('../img/reader/email.png') no-repeat 0 0;
background: transparent url('../img/icons/silk/email.png') no-repeat 0 0;
}
.NB-modal-preferences .NB-preference-story-share label[for=NB-preference-story-share-readability] {
background: transparent url('../img/reader/readability.png') no-repeat 0 0;

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 734 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 308 B

View file

@ -41,16 +41,15 @@
- (void)renderStories:(NSArray *)newStories;
- (void)scrollViewDidScroll:(UIScrollView *)scroll;
- (IBAction)markAllRead;
- (IBAction)selectIntelligence;
- (NSDictionary *)getStoryAtRow:(NSInteger)indexPathRow;
- (void)checkScroll;
- (void)markedAsRead;
- (void)pullToRefreshViewShouldRefresh:(PullToRefreshView *)view;
- (NSDate *)pullToRefreshViewLastUpdated:(PullToRefreshView *)view;
- (void)finishedRefreshingFeed:(ASIHTTPRequest *)request;
- (void)failRefreshingFeed:(ASIHTTPRequest *)request;
- (IBAction)doOpenMarkReadActionSheet:(id)sender;
- (IBAction)doOpenSettingsActionSheet;
- (void)confirmDeleteSite;
- (void)deleteSite;

View file

@ -21,6 +21,8 @@
#define kTableViewRowHeight 65;
#define kTableViewRiverRowHeight 81;
#define kMarkReadActionSheet 1;
#define kSettingsActionSheet 2;
@implementation FeedDetailViewController
@ -524,25 +526,6 @@
}
}
- (IBAction)markAllRead {
NSString *urlString = [NSString stringWithFormat:@"http://%@/reader/mark_feed_as_read",
NEWSBLUR_URL];
NSURL *url = [NSURL URLWithString:urlString];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:[appDelegate.activeFeed objectForKey:@"id"] forKey:@"feed_id"];
[request setDelegate:nil];
[request startAsynchronous];
[appDelegate markActiveFeedAllRead];
[appDelegate.navigationController
popToViewController:[appDelegate.navigationController.viewControllers
objectAtIndex:0]
animated:YES];
}
- (void)markedAsRead {
}
- (IBAction)selectIntelligence {
NSInteger newLevel = [self.intelligenceControl selectedSegmentIndex] - 1;
NSInteger previousLevel = [appDelegate selectedIntelligence];
@ -612,6 +595,101 @@
#pragma mark -
#pragma mark Feed Actions
- (void)markFeedsReadWithAllStories:(BOOL)includeHidden {
if (appDelegate.isRiverView && includeHidden) {
// Mark folder as read
NSString *urlString = [NSString stringWithFormat:@"http://%@/reader/mark_folder_as_read",
NEWSBLUR_URL];
NSURL *url = [NSURL URLWithString:urlString];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:appDelegate.activeFolder forKey:@"folder_name"];
[request setDelegate:nil];
[request startAsynchronous];
[appDelegate markActiveFolderAllRead];
[appDelegate.navigationController
popToViewController:[appDelegate.navigationController.viewControllers
objectAtIndex:0]
animated:YES];
} else if (!appDelegate.isRiverView && includeHidden) {
// Mark feed as read
NSString *urlString = [NSString stringWithFormat:@"http://%@/reader/mark_feed_as_read",
NEWSBLUR_URL];
NSURL *url = [NSURL URLWithString:urlString];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:[appDelegate.activeFeed objectForKey:@"id"] forKey:@"feed_id"];
[request setDelegate:nil];
[request startAsynchronous];
[appDelegate markActiveFeedAllRead];
[appDelegate.navigationController
popToViewController:[appDelegate.navigationController.viewControllers
objectAtIndex:0]
animated:YES];
} else {
// Mark visible stories as read
NSDictionary *feedsStories = [appDelegate markVisibleStoriesRead];
NSString *urlString = [NSString stringWithFormat:@"http://%@/reader/mark_feed_stories_as_read",
NEWSBLUR_URL];
NSURL *url = [NSURL URLWithString:urlString];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:[feedsStories JSONRepresentation] forKey:@"feeds_stories"];
[request setDelegate:nil];
[request startAsynchronous];
[appDelegate.navigationController
popToViewController:[appDelegate.navigationController.viewControllers
objectAtIndex:0]
animated:YES];
}
}
- (IBAction)doOpenMarkReadActionSheet:(id)sender {
NSString *title = appDelegate.isRiverView ?
appDelegate.activeFolder :
[appDelegate.activeFeed objectForKey:@"feed_title"];
UIActionSheet *options = [[UIActionSheet alloc]
initWithTitle:title
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
int visibleUnreadCount = appDelegate.visibleUnreadCount;
int totalUnreadCount = [appDelegate unreadCount];
NSArray *buttonTitles = nil;
if (visibleUnreadCount >= totalUnreadCount || visibleUnreadCount <= 0) {
NSString *visibleText = [NSString stringWithFormat:@"Mark %@ read",
appDelegate.isRiverView ?
@"entire folder" :
@"this site"];
buttonTitles = [NSArray arrayWithObjects:visibleText, nil];
options.destructiveButtonIndex = 0;
} else {
NSString *visibleText = [NSString stringWithFormat:@"Mark %@ read",
visibleUnreadCount == 1 ?
@"this story as" :
[NSString stringWithFormat:@"these %d stories",
visibleUnreadCount]];
NSString *entireText = [NSString stringWithFormat:@"Mark %@ read",
appDelegate.isRiverView ?
@"entire folder" :
@"this site"];
buttonTitles = [NSArray arrayWithObjects:visibleText, entireText, nil];
options.destructiveButtonIndex = 1;
}
for (id title in buttonTitles) {
[options addButtonWithTitle:title];
}
options.cancelButtonIndex = [options addButtonWithTitle:@"Cancel"];
options.tag = kMarkReadActionSheet;
[options showInView:self.view];
[options release];
}
- (IBAction)doOpenSettingsActionSheet {
UIActionSheet *options = [[UIActionSheet alloc]
initWithTitle:[appDelegate.activeFeed objectForKey:@"feed_title"]
@ -625,14 +703,32 @@
[options addButtonWithTitle:title];
}
options.cancelButtonIndex = [options addButtonWithTitle:@"Cancel"];
options.tag = kSettingsActionSheet;
[options showInView:self.view];
[options release];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0) {
[self confirmDeleteSite];
NSLog(@"Action option #%d", buttonIndex);
if (actionSheet.tag == 1) {
int visibleUnreadCount = appDelegate.visibleUnreadCount;
int totalUnreadCount = [appDelegate unreadCount];
if (visibleUnreadCount >= totalUnreadCount || visibleUnreadCount <= 0) {
if (buttonIndex == 0) {
[self markFeedsReadWithAllStories:YES];
}
} else {
if (buttonIndex == 0) {
[self markFeedsReadWithAllStories:NO];
} else if (buttonIndex == 1) {
[self markFeedsReadWithAllStories:YES];
}
}
} else if (actionSheet.tag == 2) {
if (buttonIndex == 0) {
[self confirmDeleteSite];
}
}
}

View file

@ -76,7 +76,7 @@
<object class="IBUISegmentedControl" id="122945842">
<reference key="NSNextResponder" ref="929039419"/>
<int key="NSvFlags">292</int>
<string key="NSFrame">{{93, 8}, {161, 30}}</string>
<string key="NSFrame">{{79, 8}, {161, 30}}</string>
<reference key="NSSuperview" ref="929039419"/>
<reference key="NSWindow"/>
<reference key="NSNextKeyView"/>
@ -134,8 +134,9 @@
<object class="NSMutableArray" key="IBUIItems">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="IBUIBarButtonItem" id="625055884">
<string key="IBUITitle">All Read</string>
<string key="IBUITitle">Read</string>
<string key="targetRuntimeIdentifier">IBCocoaTouchFramework</string>
<float key="IBUIWidth">48</float>
<int key="IBUIStyle">1</int>
<reference key="IBUIToolbar" ref="929039419"/>
</object>
@ -160,7 +161,7 @@
<string key="NSResourceName">settings_icon.png</string>
</object>
<string key="targetRuntimeIdentifier">IBCocoaTouchFramework</string>
<float key="IBUIWidth">42</float>
<float key="IBUIWidth">48</float>
<int key="IBUIStyle">1</int>
<reference key="IBUIToolbar" ref="929039419"/>
</object>
@ -241,11 +242,11 @@
</object>
<object class="IBConnectionRecord">
<object class="IBCocoaTouchEventConnection" key="connection">
<string key="label">markAllRead</string>
<string key="label">doOpenMarkReadActionSheet:</string>
<reference key="source" ref="625055884"/>
<reference key="destination" ref="372490531"/>
</object>
<int key="connectionID">51</int>
<int key="connectionID">62</int>
</object>
<object class="IBConnectionRecord">
<object class="IBCocoaTouchEventConnection" key="connection">
@ -400,7 +401,7 @@
<reference key="dict.values" ref="0"/>
</object>
<nil key="sourceID"/>
<int key="maxID">61</int>
<int key="maxID">62</int>
</object>
<object class="IBClassDescriber" key="IBDocument.Classes">
<object class="NSMutableArray" key="referencedPartialClassDescriptions">
@ -646,8 +647,8 @@
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="NSArray" key="dict.sortedKeys">
<bool key="EncodedWithXMLCoder">YES</bool>
<string>doOpenMarkReadActionSheet:</string>
<string>doOpenSettingsActionSheet</string>
<string>markAllRead</string>
<string>selectIntelligence</string>
</object>
<object class="NSMutableArray" key="dict.values">
@ -661,18 +662,18 @@
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="NSArray" key="dict.sortedKeys">
<bool key="EncodedWithXMLCoder">YES</bool>
<string>doOpenMarkReadActionSheet:</string>
<string>doOpenSettingsActionSheet</string>
<string>markAllRead</string>
<string>selectIntelligence</string>
</object>
<object class="NSMutableArray" key="dict.values">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="IBActionInfo">
<string key="name">doOpenSettingsActionSheet</string>
<string key="name">doOpenMarkReadActionSheet:</string>
<string key="candidateClassName">id</string>
</object>
<object class="IBActionInfo">
<string key="name">markAllRead</string>
<string key="name">doOpenSettingsActionSheet</string>
<string key="candidateClassName">id</string>
</object>
<object class="IBActionInfo">
@ -1269,6 +1270,7 @@
<string>appDelegate</string>
<string>buttonNext</string>
<string>buttonPrevious</string>
<string>feedTitleGradient</string>
<string>progressView</string>
<string>toolbar</string>
<string>webView</string>
@ -1279,6 +1281,7 @@
<string>NewsBlurAppDelegate</string>
<string>UIBarButtonItem</string>
<string>UIBarButtonItem</string>
<string>UIView</string>
<string>UIProgressView</string>
<string>UIToolbar</string>
<string>UIWebView</string>
@ -1292,6 +1295,7 @@
<string>appDelegate</string>
<string>buttonNext</string>
<string>buttonPrevious</string>
<string>feedTitleGradient</string>
<string>progressView</string>
<string>toolbar</string>
<string>webView</string>
@ -1314,6 +1318,10 @@
<string key="name">buttonPrevious</string>
<string key="candidateClassName">UIBarButtonItem</string>
</object>
<object class="IBToOneOutletInfo">
<string key="name">feedTitleGradient</string>
<string key="candidateClassName">UIView</string>
</object>
<object class="IBToOneOutletInfo">
<string key="name">progressView</string>
<string key="candidateClassName">UIProgressView</string>

View file

@ -40,7 +40,9 @@
int storyCount;
int originalStoryCount;
NSInteger selectedIntelligence;
int visibleUnreadCount;
NSMutableArray * recentlyReadStories;
NSMutableSet * recentlyReadFeeds;
NSMutableArray * readStories;
NSDictionary * dictFolders;
@ -69,8 +71,10 @@
@property (readwrite, retain) NSURL * activeOriginalStoryURL;
@property (readwrite) int storyCount;
@property (readwrite) int originalStoryCount;
@property (readwrite) int visibleUnreadCount;
@property (readwrite) NSInteger selectedIntelligence;
@property (readwrite, retain) NSMutableArray * recentlyReadStories;
@property (readwrite, retain) NSMutableSet * recentlyReadFeeds;
@property (readwrite, retain) NSMutableArray * readStories;
@property (nonatomic, retain) NSDictionary *dictFolders;
@ -103,7 +107,12 @@
- (int)unreadCountForFeed:(NSString *)feedId;
- (int)unreadCountForFolder:(NSString *)folderName;
- (void)markActiveStoryRead;
- (NSDictionary *)markVisibleStoriesRead;
- (void)markStoryRead:(NSString *)storyId feedId:(id)feedId;
- (void)markStoryRead:(NSDictionary *)story feed:(NSDictionary *)feed;
- (void)markActiveFeedAllRead;
- (void)markActiveFolderAllRead;
- (void)markFeedAllRead:(id)feedId;
- (void)calculateStoryLocations;
+ (int)computeStoryScore:(NSDictionary *)intelligence;
+ (UIView *)makeGradientView:(CGRect)rect startColor:(NSString *)start endColor:(NSString *)end;

View file

@ -37,10 +37,12 @@
@synthesize activeFeedStoryLocationIds;
@synthesize activeStory;
@synthesize storyCount;
@synthesize visibleUnreadCount;
@synthesize originalStoryCount;
@synthesize selectedIntelligence;
@synthesize activeOriginalStoryURL;
@synthesize recentlyReadStories;
@synthesize recentlyReadFeeds;
@synthesize readStories;
@synthesize dictFolders;
@ -63,6 +65,7 @@
- (void)viewDidLoad {
self.selectedIntelligence = 1;
self.visibleUnreadCount = 0;
[self setRecentlyReadStories:[NSMutableArray array]];
}
@ -85,6 +88,7 @@
[activeStory release];
[activeOriginalStoryURL release];
[recentlyReadStories release];
[recentlyReadFeeds release];
[readStories release];
[dictFolders release];
@ -349,7 +353,8 @@
- (void)setStories:(NSArray *)activeFeedStoriesValue {
self.activeFeedStories = activeFeedStoriesValue;
self.storyCount = [self.activeFeedStories count];
[self setRecentlyReadStories:[NSMutableArray array]];
self.recentlyReadStories = [NSMutableArray array];
self.recentlyReadFeeds = [NSMutableSet set];
[self calculateStoryLocations];
}
@ -363,9 +368,55 @@
int activeIndex = [[activeFeedStoryLocations objectAtIndex:activeLocation] intValue];
NSDictionary *feed = [self.dictFeeds objectForKey:feedIdStr];
NSDictionary *story = [activeFeedStories objectAtIndex:activeIndex];
if (self.activeFeed != feed) {
// NSLog(@"activeFeed; %@, feed: %@", activeFeed, feed);
self.activeFeed = feed;
}
[story setValue:[NSNumber numberWithInt:1] forKey:@"read_status"];
[self.recentlyReadStories addObject:[NSNumber numberWithInt:activeLocation]];
[self markStoryRead:story feed:feed];
// NSLog(@"Marked read %d-%d: %@: %d", activeIndex, activeLocation, self.recentlyReadStories, score);
}
- (NSDictionary *)markVisibleStoriesRead {
NSMutableDictionary *feedsStories = [NSMutableDictionary dictionary];
for (NSDictionary *story in self.activeFeedStories) {
if ([[story objectForKey:@"read_status"] intValue] != 0) {
continue;
}
NSString *feedIdStr = [NSString stringWithFormat:@"%@",[story objectForKey:@"story_feed_id"]];
NSDictionary *feed = [self.dictFeeds objectForKey:feedIdStr];
if (![feedsStories objectForKey:feedIdStr]) {
[feedsStories setObject:[NSMutableArray array] forKey:feedIdStr];
}
NSMutableArray *stories = [feedsStories objectForKey:feedIdStr];
[stories addObject:[story objectForKey:@"id"]];
[self markStoryRead:story feed:feed];
}
NSLog(@"feedsStories: %@", feedsStories);
return feedsStories;
}
- (void)markStoryRead:(NSString *)storyId feedId:(id)feedId {
NSString *feedIdStr = [NSString stringWithFormat:@"%@",feedId];
NSDictionary *feed = [self.dictFeeds objectForKey:feedIdStr];
NSDictionary *story = nil;
for (NSDictionary *s in self.activeFeedStories) {
if ([[s objectForKey:@"story_guid"] isEqualToString:storyId]) {
story = s;
break;
}
}
[self markStoryRead:story feed:feed];
}
- (void)markStoryRead:(NSDictionary *)story feed:(NSDictionary *)feed {
NSString *feedIdStr = [NSString stringWithFormat:@"%@", [feed objectForKey:@"id"]];
[story setValue:[NSNumber numberWithInt:1] forKey:@"read_status"];
self.visibleUnreadCount -= 1;
if (![self.recentlyReadFeeds containsObject:[story objectForKey:@"story_feed_id"]]) {
[self.recentlyReadFeeds addObject:[story objectForKey:@"story_feed_id"]];
}
int score = [NewsBlurAppDelegate computeStoryScore:[story objectForKey:@"intelligence"]];
if (score > 0) {
int unreads = MAX(0, [[feed objectForKey:@"ps"] intValue] - 1);
@ -378,22 +429,32 @@
[feed setValue:[NSNumber numberWithInt:unreads] forKey:@"ng"];
}
[self.dictFeeds setValue:feed forKey:feedIdStr];
// NSLog(@"Marked read %d-%d: %@: %d", activeIndex, activeLocation, self.recentlyReadStories, score);
}
- (void)markActiveFeedAllRead {
id feedId = [self.activeFeed objectForKey:@"id"];
NSString *feedIdStr = [NSString stringWithFormat:@"%@",feedId];
[self markFeedAllRead:feedId];
}
- (void)markActiveFolderAllRead {
for (id feedId in [self.dictFolders objectForKey:self.activeFolder]) {
[self markFeedAllRead:feedId];
}
}
- (void)markFeedAllRead:(id)feedId {
NSString *feedIdStr = [NSString stringWithFormat:@"%@",feedId];
NSDictionary *feed = [self.dictFeeds objectForKey:feedIdStr];
[feed setValue:[NSNumber numberWithInt:0] forKey:@"ps"];
[feed setValue:[NSNumber numberWithInt:0] forKey:@"nt"];
[feed setValue:[NSNumber numberWithInt:0] forKey:@"ng"];
[self.dictFeeds setValue:feed forKey:feedIdStr];
[self.dictFeeds setValue:feed forKey:feedIdStr];
}
- (void)calculateStoryLocations {
self.visibleUnreadCount = 0;
self.activeFeedStoryLocations = [NSMutableArray array];
self.activeFeedStoryLocationIds = [NSMutableArray array];
for (int i=0; i < self.storyCount; i++) {
@ -403,6 +464,9 @@
NSNumber *location = [NSNumber numberWithInt:i];
[self.activeFeedStoryLocations addObject:location];
[self.activeFeedStoryLocationIds addObject:[story objectForKey:@"id"]];
if ([[story objectForKey:@"read_status"] intValue] == 0) {
self.visibleUnreadCount += 1;
}
}
}
}

View file

@ -70,9 +70,9 @@
}
- (void)viewWillAppear:(BOOL)animated {
// If there is an active feed, we need to update its table row to match
// the updated unread counts.
if ([appDelegate activeFeed]) {
// If there is an active feed or a set of feeds readin the river,
// we need to update its table row to match the updated unread counts.
if (appDelegate.activeFeed || appDelegate.isRiverView) {
NSMutableArray *indexPaths = [NSMutableArray array];
for (int s=0; s < [appDelegate.dictFoldersArray count]; s++) {
NSString *folderName = [appDelegate.dictFoldersArray objectAtIndex:s];
@ -81,14 +81,17 @@
for (int f=0; f < [activeFolderFeeds count]; f++) {
int location = [[activeFolderFeeds objectAtIndex:f] intValue];
id feedId = [originalFolder objectAtIndex:location];
if ([feedId compare:[appDelegate.activeFeed objectForKey:@"id"]] == NSOrderedSame) {
if ((appDelegate.isRiverView &&
[appDelegate.recentlyReadFeeds containsObject:feedId]) ||
(appDelegate.activeFeed &&
[feedId compare:[appDelegate.activeFeed objectForKey:@"id"]] == NSOrderedSame)) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:f inSection:s];
[indexPaths addObject:indexPath];
[self.stillVisibleFeeds setObject:indexPath forKey:[NSString stringWithFormat:@"%@", feedId]];
}
}
}
// NSLog(@"Refreshing feed at %@: %@", indexPaths, [appDelegate activeFeed]);
// NSLog(@"Refreshing feed at %@", indexPaths);
[self.feedTitlesTable beginUpdates];
[self.feedTitlesTable
@ -106,6 +109,7 @@
[self redrawUnreadCounts];
}
}
[self.intelligenceControl setImage:[UIImage imageNamed:@"bullet_red.png"]
forSegmentAtIndex:0];
[self.intelligenceControl setImage:[UIImage imageNamed:@"bullet_yellow.png"]

View file

@ -20,7 +20,7 @@ static const CGFloat kAddressHeight = 30.0f;
static const CGFloat kButtonWidth = 48.0f;
@interface OriginalStoryViewController : BaseViewController
<UIActionSheetDelegate, UITextFieldDelegate> {
<UIActionSheetDelegate, UITextFieldDelegate, UIWebViewDelegate> {
NewsBlurAppDelegate *appDelegate;

View file

@ -155,7 +155,10 @@
- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType {
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
if ([[[request URL] scheme] isEqual:@"mailto"]) {
[[UIApplication sharedApplication] openURL:[request URL]];
return NO;
} else if (navigationType == UIWebViewNavigationTypeLinkClicked) {
[self updateAddress:request];
return NO;
}

View file

@ -95,6 +95,7 @@
];
self.navigationItem.rightBarButtonItem = originalButton;
[originalButton release];
[super viewDidAppear:animated];
}
@ -136,7 +137,7 @@
float unreads = (float)[appDelegate unreadCount];
float total = [appDelegate originalStoryCount];
float progress = (total - unreads) / total;
// NSLog(@"Total: %f / %f = %f", unreads, total, progress);
NSLog(@"Total: %f / %f = %f", unreads, total, progress);
[progressView setProgress:progress];
}
@ -297,12 +298,11 @@
withRect:CGRectMake(0, -1, self.webView.frame.size.width, 21)];
self.feedTitleGradient.tag = 12; // Not attached yet. Remove old gradients, first.
for (UIView *subview in self.view.subviews) {
for (UIView *subview in self.webView.subviews) {
if (subview.tag == 12) {
[subview removeFromSuperview];
}
}
[self.view insertSubview:feedTitleGradient aboveSubview:self.webView];
for (NSObject *aSubView in [self.webView subviews]) {
if ([aSubView isKindOfClass:[UIScrollView class]]) {
UIScrollView * theScrollView = (UIScrollView *)aSubView;
@ -311,13 +311,35 @@
} else {
theScrollView.contentInset = UIEdgeInsetsMake(9, 0, 0, 0);
}
[self.webView insertSubview:feedTitleGradient belowSubview:theScrollView];
[theScrollView setContentOffset:CGPointMake(0, appDelegate.isRiverView ? -19 : -9) animated:NO];
// Such a fucking hack. This hides the top shadow of the scroll view
// so the gradient doesn't look like ass when the view is dragged down.
NSArray *wsv = [NSArray arrayWithArray:[theScrollView subviews]];
[[wsv objectAtIndex:7] setHidden:YES]; // Scroll to header
[[wsv objectAtIndex:9] setHidden:YES]; // Scroll to header
[[wsv objectAtIndex:3] setHidden:YES]; // Scroll to header
[[wsv objectAtIndex:5] setHidden:YES]; // Scroll to header
// UIImageView *topShadow = [[UIImageView alloc] initWithImage:[[wsv objectAtIndex:9] image]];
// topShadow.frame = [[wsv objectAtIndex:9] frame];
// [self.webView addSubview:topShadow];
// [self.webView addSubview:[wsv objectAtIndex:9]];
// Oh my god, the above code is beyond hack. It's evil. And it's going
// to break, I swear to god. This shit deserves scorn.
break;
}
}
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
self.feedTitleGradient.frame = CGRectMake(0, -1 * scrollView.contentOffset.y - self.feedTitleGradient.frame.size.height, self.feedTitleGradient.frame.size.width, self.feedTitleGradient.frame.size.height);
// NSLog(@"ContentOffset: %f %f", scrollView.contentOffset.x, scrollView.contentOffset.y);
self.feedTitleGradient.frame = CGRectMake(scrollView.contentOffset.x < 0 ? -1 * scrollView.contentOffset.x : 0,
-1 * scrollView.contentOffset.y - self.feedTitleGradient.frame.size.height,
self.feedTitleGradient.frame.size.width,
self.feedTitleGradient.frame.size.height);
}
- (IBAction)doNextUnreadStory {

View file

@ -654,6 +654,7 @@
);
CODE_SIGN_ENTITLEMENTS = Entitlements.entitlements;
CODE_SIGN_IDENTITY = "iPhone Developer";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
GCC_DYNAMIC_NO_PIC = NO;
GCC_OPTIMIZATION_LEVEL = 0;
@ -672,6 +673,7 @@
);
PRODUCT_NAME = NewsBlur;
PROVISIONING_PROFILE = "";
"PROVISIONING_PROFILE[sdk=iphoneos*]" = "";
};
name = Debug;
};
@ -685,6 +687,7 @@
);
CODE_SIGN_ENTITLEMENTS = Entitlements.entitlements;
CODE_SIGN_IDENTITY = "iPhone Developer";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = YES;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = NewsBlur_Prefix.pch;
@ -701,6 +704,7 @@
);
PRODUCT_NAME = NewsBlur;
PROVISIONING_PROFILE = "";
"PROVISIONING_PROFILE[sdk=iphoneos*]" = "";
VALIDATE_PRODUCT = YES;
};
name = Release;

View file

@ -15,7 +15,7 @@
// #define BACKGROUND_REFRESH_SECONDS -5
#define BACKGROUND_REFRESH_SECONDS -10*60
// #define NEWSBLUR_URL [NSString stringWithFormat:@"nb.local.host:8000"]
#define NEWSBLUR_URL [NSString stringWithFormat:@"www.newsblur.com"]
#define NEWSBLUR_URL [NSString stringWithFormat:@"nb.local.host:8000"]
// #define NEWSBLUR_URL [NSString stringWithFormat:@"www.newsblur.com"]
#endif

View file

@ -5,6 +5,8 @@ if (typeof NEWSBLUR.Globals == 'undefined') NEWSBLUR.Globals = {};
/* = Core NewsBlur Javascript = */
/* ============================= */
var URL_REGEX = /((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi;
NEWSBLUR.log = function(msg) {
try {
if (typeof o == "object")
@ -31,6 +33,36 @@ NEWSBLUR.log = function(msg) {
$.fn.extend({
autolink: function() {
return this.each(function(){
var desc = $(this);
desc.textNodes().each(function(){
var text = $(this);
if(text && text.parent() && text.parent()[0] && text.parent()[0].nodeName != 'A') {
text.replaceWith(this.data.replace(URL_REGEX, function($0, $1) {
return '<a href="' + $0 +'">' + $0 + '</a>';
}));
}
});
});
},
textNodes: function() {
var ret = [];
(function(el){
if (!el) return;
if ((el.nodeType == 3)) {
ret.push(el);
} else {
for (var i=0; i < el.childNodes.length; ++i) {
arguments.callee(el.childNodes[i]);
}
}
})(this[0]);
return $(ret);
},
isScrollVisible: function($elem) {
var docViewTop = 0; // $(this).scrollTop();
var docViewBottom = docViewTop + $(this).height();

View file

@ -137,7 +137,7 @@
this.flags.active_view = 'stories';
$.mobile.showPageLoadingMsg();
this.active_feed = feed_id;
this.model.load_feed(feed_id, this.page, this.page == 1, _.bind(this.build_stories, this));
this.model.load_feed(feed_id, this.page, this.page == 1, _.bind(this.build_stories, this), $.noop);
},
build_stories: function(data, first_load) {

View file

@ -293,7 +293,7 @@ NEWSBLUR.AssetModel.Reader.prototype = {
this.make_request('/reader/favicons', data, pre_callback, pre_callback, {request_type: 'GET'});
},
load_feed: function(feed_id, page, first_load, callback) {
load_feed: function(feed_id, page, first_load, callback, error_callback) {
var self = this;
var pre_callback = function(data) {
@ -309,7 +309,7 @@ NEWSBLUR.AssetModel.Reader.prototype = {
page: page,
feed_address: this.feeds[feed_id].feed_address
}, pre_callback,
$.noop,
error_callback,
{
'ajax_group': (page > 1 ? 'feed_page' : 'feed'),
'request_type': 'GET'
@ -370,7 +370,7 @@ NEWSBLUR.AssetModel.Reader.prototype = {
this.make_request('/rss_feeds/feed/'+feed_id, {}, pre_callback, $.noop, {request_type: 'GET'});
},
fetch_starred_stories: function(page, callback, first_load) {
fetch_starred_stories: function(page, callback, error_callback, first_load) {
var self = this;
var pre_callback = function(data) {
@ -381,13 +381,13 @@ NEWSBLUR.AssetModel.Reader.prototype = {
this.make_request('/reader/starred_stories', {
page: page
}, pre_callback, $.noop, {
}, pre_callback, error_callback, {
'ajax_group': (page ? 'feed_page' : 'feed'),
'request_type': 'GET'
});
},
fetch_river_stories: function(feed_id, feeds, page, callback, first_load) {
fetch_river_stories: function(feed_id, feeds, page, callback, error_callback, first_load) {
var self = this;
if (first_load || !page) this.read_stories_river_count = 0;
@ -404,7 +404,7 @@ NEWSBLUR.AssetModel.Reader.prototype = {
read_stories_count: this.read_stories_river_count,
// TODO: Remove new flag
new_flag: true
}, pre_callback, $.noop, {
}, pre_callback, error_callback, {
'ajax_group': (page ? 'feed_page' : 'feed'),
'request_type': 'GET'
});
@ -667,6 +667,32 @@ NEWSBLUR.AssetModel.Reader.prototype = {
});
},
move_feed_to_folder: function(feed_id, in_folder, to_folder, callback) {
var pre_callback = _.bind(function(data) {
this.folders = data.folders;
return callback();
}, this);
this.make_request('/reader/move_feed_to_folder', {
'feed_id': feed_id,
'in_folder': in_folder,
'to_folder': to_folder
}, pre_callback);
},
move_folder_to_folder: function(folder_name, in_folder, to_folder, callback) {
var pre_callback = _.bind(function(data) {
this.folders = data.folders;
return callback();
}, this);
this.make_request('/reader/move_folder_to_folder', {
'folder_name': folder_name,
'in_folder': in_folder,
'to_folder': to_folder
}, pre_callback);
},
preference: function(preference, value, callback) {
if (typeof value == 'undefined') {
var pref = NEWSBLUR.Preferences[preference];

View file

@ -1,5 +1,5 @@
(function($) {
(function($) {
NEWSBLUR.Reader = function() {
var self = this;
@ -519,15 +519,15 @@
return $story_title;
},
find_story_in_feed_view: function(story) {
if (!story) return;
find_story_in_feed_view: function(story_id) {
if (!story_id) return;
var $feed_view = this.$s.$feed_view;
var $stories = $('.NB-feed-story', $feed_view);
var $story;
for (var s=0, s_count = $stories.length; s < s_count; s++) {
if ($stories.eq(s).data('story') == story.id) {
if ($stories.eq(s).data('story') == story_id) {
$story = $stories.eq(s);
break;
}
@ -744,16 +744,56 @@
},
open_next_unread_story_across_feeds: function() {
var unread_count = this.active_feed && this.get_unread_count(true);
if (unread_count) {
var unread_count = this.active_feed && this.get_unread_count(true);
if (!unread_count) {
if (this.flags.river_view && false) {
// TODO: Make this work
// var $next_folder = this.get_next_unread_folder(1);
// var $folder = $next_folder.closest('li.folder');
// var folder_title = $folder.find('.folder_title_text').text();
// this.open_river_stories($folder, folder_title);
} else {
// Find next feed with unreads
var $next_feed = this.get_next_unread_feed(1);
var next_feed_id = parseInt($next_feed.attr('data-id'), 10);
this.open_feed(next_feed_id, true, $next_feed);
}
}
this.show_next_unread_story();
} else {
// Find next feed with unreads
var $next_feed = this.get_next_unread_feed(1);
var next_feed_id = parseInt($next_feed.attr('data-id'), 10);
this.open_feed(next_feed_id, true, $next_feed);
this.show_next_unread_story();
}
},
show_last_unread_story: function() {
var $story_titles = this.$s.$story_titles;
var $current_story = $('.selected', $story_titles);
var $next_story;
var unread_count = this.get_unread_count(true);
NEWSBLUR.log(['show_last_unread_story', unread_count, $current_story]);
if (unread_count) {
var unread_stories_visible = $('.story:not(.read):visible', $story_titles).length;
if (unread_stories_visible >= unread_count) {
// Choose the last unread story
$next_story = $('.story:not(.read):visible:last', $story_titles);
}
if ($next_story && $next_story.length) {
this.counts['find_last_unread_on_page_of_feed_stories_load'] = 0;
var story_id = $next_story.data('story_id');
if (story_id) {
var story = this.model.get_story(story_id);
this.push_current_story_on_history();
this.open_story(story, $next_story);
this.scroll_story_titles_to_show_selected_story_title($next_story);
}
} else if (this.counts['find_last_unread_on_page_of_feed_stories_load'] < this.constants.FILL_OUT_PAGES) {
// Nothing up, nothing down, but still unread. Load 1 page then find it.
this.counts['find_last_unread_on_page_of_feed_stories_load'] += 1;
this.load_page_of_feed_stories();
}
}
},
show_previous_story: function() {
@ -889,7 +929,7 @@
mark_story_as_read_in_feed_view: function(story, options) {
if (!story) return;
options = options || {};
$story = this.cache.feed_view_stories[story.id] || this.find_story_in_feed_view(story);
$story = this.cache.feed_view_stories[story.id] || this.find_story_in_feed_view(story.id);
if ($story) {
$story.addClass('read');
}
@ -1011,6 +1051,7 @@
this.add_url_from_querystring();
_.defer(_.bind(function() {
this.model.load_feed_favicons($.rescope(this.make_feed_favicons, this), this.flags['favicons_downloaded'], this.flags['has_chosen_feeds']);
this.setup_socket_realtime_unread_counts();
}, this));
},
@ -1634,7 +1675,8 @@
$.extend(this.counts, {
'page_fill_outs': 0,
'find_next_unread_on_page_of_feed_stories_load': 0
'find_next_unread_on_page_of_feed_stories_load': 0,
'find_last_unread_on_page_of_feed_stories_load': 0
});
this.active_feed = null;
@ -1684,7 +1726,8 @@
_.delay(_.bind(function() {
if (!delay || feed_id == self.next_feed) {
this.model.load_feed(feed_id, 1, true, $.rescope(this.post_open_feed, this));
this.model.load_feed(feed_id, 1, true, $.rescope(this.post_open_feed, this),
_.bind(this.show_stories_error, this));
}
}, this), delay || 0);
@ -1728,6 +1771,8 @@
$('.NB-feedbar-last-updated-date').text(data.last_update + ' ago');
if (this.counts['find_next_unread_on_page_of_feed_stories_load']) {
this.show_next_unread_story(true);
} else if (this.counts['find_last_unread_on_page_of_feed_stories_load']) {
this.show_last_unread_story(true);
}
this.flags['story_titles_loaded'] = true;
if (!first_load) {
@ -1803,7 +1848,7 @@
// = Feed Header =
// ===============
update_header_counts: function(skip_sites) {
update_header_counts: function(skip_sites, unread_view) {
if (!skip_sites) {
var feeds_count = _.select(this.model.feeds, function(f) {
return f.active;
@ -1822,10 +1867,28 @@
return m;
}, {'positive': 0, 'negative': 0, 'neutral': 0});
_(['positive', 'neutral', 'negative']).each(function(level) {
// This is for .NB-feeds-header-count
var $count = $('.NB-feeds-header-'+level);
$count.text(unread_counts[level]);
$count.toggleClass('NB-empty', unread_counts[level] == 0);
});
if (this.model.preference('show_unread_counts_in_title')) {
var title = 'NewsBlur (';
var counts = [];
var unread_view = _.isNumber(unread_view) && unread_view || this.model.preference('unread_view');
if (unread_view <= -1) {
counts.push(unread_counts['negative']);
}
if (unread_view <= 0) {
counts.push(unread_counts['neutral']);
}
if (unread_view <= 1) {
counts.push(unread_counts['positive']);
}
title += counts.join('/') + ')';
document.title = title;
}
},
update_starred_count: function() {
@ -1871,7 +1934,8 @@
this.switch_taskbar_view(this.story_view);
this.setup_mousemove_on_views();
this.model.fetch_starred_stories(1, _.bind(this.post_open_starred_stories, this), true);
this.model.fetch_starred_stories(1, _.bind(this.post_open_starred_stories, this),
_.bind(this.show_stories_error, this), true);
},
post_open_starred_stories: function(data, first_load) {
@ -1933,11 +1997,15 @@
this.cache['river_feeds_with_unreads'] = feeds;
this.show_stories_progress_bar(feeds.length);
this.model.fetch_river_stories(this.active_feed, feeds, 1,
_.bind(this.post_open_river_stories, this), true);
_.bind(this.post_open_river_stories, this), _.bind(this.show_stories_error, this), true);
},
post_open_river_stories: function(data, first_load) {
// NEWSBLUR.log(['post_open_river_stories', data, this.active_feed]);
if (!data) {
return this.show_stories_error();
}
if (this.active_feed && this.active_feed.indexOf('river:') != -1) {
if (!NEWSBLUR.Globals.is_premium &&
NEWSBLUR.Globals.is_authenticated &&
@ -1955,6 +2023,8 @@
this.flags['story_titles_loaded'] = true;
if (this.counts['find_next_unread_on_page_of_feed_stories_load']) {
this.show_next_unread_story(true);
} else if (this.counts['find_last_unread_on_page_of_feed_stories_load']) {
this.show_last_unread_story(true);
}
this.fill_out_story_titles();
this.prefetch_story_locations_in_feed_view();
@ -1992,6 +2062,8 @@
},
show_stories_progress_bar: function(feeds_loading) {
this.hide_stories_error();
var $progress = $.make('div', { className: 'NB-river-progress' }, [
$.make('div', { className: 'NB-river-progress-text' }),
$.make('div', { className: 'NB-river-progress-bar' })
@ -2026,6 +2098,38 @@
});
},
show_stories_error: function() {
this.hide_stories_progress_bar();
var $error = $.make('div', { className: 'NB-feed-error' }, [
$.make('div', { className: 'NB-feed-error-icon' }),
$.make('div', { className: 'NB-feed-error-text' }, 'Oh no! There was an error!')
]).css({'opacity': 0});
this.$s.$story_taskbar.append($error);
$error.animate({'opacity': 1}, {'duration': 500, 'queue': false});
// Center the progress bar
var i_width = $error.width();
var o_width = this.$s.$story_taskbar.width();
var left = (o_width / 2.0) - (i_width / 2.0);
$error.css({'left': left});
this.story_titles_clear_loading_endbar();
this.append_story_titles_endbar();
},
hide_stories_error: function() {
var $error = $('.NB-feed-error', this.$s.$story_taskbar);
$error.animate({'opacity': 0}, {
'duration': 250,
'queue': false,
'complete': function() {
$error.remove();
}
});
},
// ==========================
// = Story Pane - All Views =
// ==========================
@ -2050,7 +2154,7 @@
}
// User clicks on story, scroll them to it.
var $feed_story = this.find_story_in_feed_view(story);
var $feed_story = this.find_story_in_feed_view(story.id);
if (this.story_view == 'page') {
var $iframe_story = this.find_story_in_feed_iframe(story);
@ -2059,6 +2163,7 @@
// So just assume story not found.
this.switch_to_correct_view(false);
feed_position = this.scroll_to_story_in_story_feed(story, $feed_story);
this.show_stories_preference_in_feed_view(true);
} else {
iframe_position = this.scroll_to_story_in_iframe(story, $iframe_story);
this.switch_to_correct_view(iframe_position);
@ -2341,6 +2446,7 @@
var $feed = this.find_feed_in_feed_list(feed_id);
var $feed_counts = this.cache.$feed_counts_in_feed_list[feed_id] || $('.feed_counts_floater', $feed);
var $story_title = this.find_story_in_story_titles(story_id);
var $story = this.find_story_in_feed_view(story_id);
var $content_pane = this.$s.$content_pane;
var $floater = $('.feed_counts_floater', $content_pane);
var unread_view = this.get_unread_view_name();
@ -2348,6 +2454,7 @@
this.cache.$feed_counts_in_feed_list[feed_id] = $feed_counts;
$story_title.toggleClass('read', !unread);
$story.toggleClass('read', !unread);
// NEWSBLUR.log(['marked read', feed.ps, feed.nt, feed.ng, $story_title.is('.NB-story-positive'), $story_title.is('.NB-story-neutral'), $story_title.is('.NB-story-negative')]);
if ($story_title.is('.NB-story-positive')) {
@ -2618,6 +2725,38 @@
this.mark_story_as_read(story_id);
},
send_story_to_pinboard: function(story_id) {
var story = this.model.get_story(story_id);
var url = 'http://pinboard.in/add/?';
var pinboard_url = [
url,
'url=',
encodeURIComponent(story.story_permalink),
'&title=',
encodeURIComponent(story.story_title),
'&tags=',
encodeURIComponent(story.story_tags.join(', '))
].join('');
window.open(pinboard_url, '_blank');
this.mark_story_as_read(story_id);
},
send_story_to_googleplus: function(story_id) {
var story = this.model.get_story(story_id);
var url = 'https://plusone.google.com/_/+1/confirm'; //?hl=en&url=${url}
var googleplus_url = [
url,
'?hl=en&url=',
encodeURIComponent(story.story_permalink),
'&title=',
encodeURIComponent(story.story_title),
'&tags=',
encodeURIComponent(story.story_tags.join(', '))
].join('');
window.open(googleplus_url, '_blank');
this.mark_story_as_read(story_id);
},
send_story_to_email: function(story_id) {
NEWSBLUR.reader_send_email = new NEWSBLUR.ReaderSendEmail(story_id);
this.mark_story_as_read(story_id);
@ -2733,7 +2872,7 @@
$story_titles.hover(function() {
var $this = $(this);
var menu_height = $this.hasClass('story') ? 150 : 270;
var menu_height = $this.hasClass('story') ? 190 : 270;
if ($this.offset().top > $(window).height() - menu_height) {
$this.addClass('NB-hover-inverse');
@ -2984,14 +3123,15 @@
if (!hide_loading) this.show_feedbar_loading();
$story_titles.data('page', page+1);
if (this.active_feed == 'starred') {
this.model.fetch_starred_stories(page+1,
_.bind(this.post_open_starred_stories, this), false);
this.model.fetch_starred_stories(page+1, _.bind(this.post_open_starred_stories, this),
_.bind(this.show_stories_error, this), false);
} else if (this.flags['river_view']) {
this.model.fetch_river_stories(this.active_feed, this.cache['river_feeds_with_unreads'],
page+1, _.bind(this.post_open_river_stories, this), false);
page+1, _.bind(this.post_open_river_stories, this),
_.bind(this.show_stories_error, this), false);
} else {
this.model.load_feed(feed_id, page+1, false,
$.rescope(this.post_open_feed, this));
$.rescope(this.post_open_feed, this), _.bind(this.show_stories_error, this));
}
}
},
@ -3354,7 +3494,7 @@
$.make('span', { className: 'NB-feed-story-starred-date' }, story.starred_date))
])
]),
$.make('div', { className: 'NB-feed-story-content' }, story.story_content)
$.make('div', { className: 'NB-feed-story-content' }, this.make_story_content(story.story_content))
]).data('story', story.id).data('story_id', story.id).data('feed_id', story.story_feed_id);
if (story_has_modifications && this.model.preference('show_tooltips')) {
@ -3410,6 +3550,11 @@
if (first_load) this.show_stories_preference_in_feed_view(true);
},
make_story_content: function(story_content) {
var $story_content = $('<div>').html(story_content).autolink();
return $story_content;
},
make_story_feed_title: function(story) {
var title = story.story_title;
var feed_titles = this.model.classifiers[story.story_feed_id] &&
@ -3510,7 +3655,7 @@
if (story && this.cache.feed_title_floater_feed_id != story.story_feed_id) {
var $feed_floater = this.$s.$feed_floater;
$story = this.find_story_in_feed_view(story);
$story = this.find_story_in_feed_view(story.id);
$header = $('.NB-feed-story-header-feed', $story);
var $new_header = $header.clone();
@ -3531,7 +3676,7 @@
}
if (story && this.cache.feed_title_floater_story_id != story.id) {
$story = $story || this.find_story_in_feed_view(story);
$story = $story || this.find_story_in_feed_view(story.id);
$header = $header || $('.NB-feed-story-header-feed', $story);
$('.NB-floater').removeClass('NB-floater');
$header.addClass('NB-floater');
@ -3735,7 +3880,7 @@
});
} else if (view == 'feed') {
if (this.active_story) {
var $feed_story = this.find_story_in_feed_view(this.active_story);
var $feed_story = this.find_story_in_feed_view(this.active_story.id);
this.scroll_to_story_in_story_feed(this.active_story, $feed_story, true);
}
@ -4123,34 +4268,48 @@
$.make('div', { className: 'NB-menu-manage-image' }),
$.make('div', { className: 'NB-menu-manage-title' }, starred_title)
]),
(story.read_status && $.make('li', { className: 'NB-menu-manage-story-unread' }, [
$.make('div', { className: 'NB-menu-manage-image' }),
$.make('div', { className: 'NB-menu-manage-title' }, 'Mark as unread')
])),
$.make('li', { className: 'NB-menu-manage-story-thirdparty' }, [
(NEWSBLUR.Preferences['story_share_facebook'] && $.make('div', { className: 'NB-menu-manage-thirdparty-icon NB-menu-manage-thirdparty-facebook'}).bind('mouseenter', _.bind(function(e) {
$(e.target).siblings('.NB-menu-manage-title').text('Send to Facebook').parent().addClass('NB-menu-manage-highlight-facebook');
$(e.target).siblings('.NB-menu-manage-title').text('Facebook').parent().addClass('NB-menu-manage-highlight-facebook');
}, this)).bind('mouseleave', _.bind(function(e) {
$(e.target).siblings('.NB-menu-manage-title').text('Send to Instapaper').parent().removeClass('NB-menu-manage-highlight-facebook');
$(e.target).siblings('.NB-menu-manage-title').text('Email story').parent().removeClass('NB-menu-manage-highlight-facebook');
}, this))),
(NEWSBLUR.Preferences['story_share_twitter'] && $.make('div', { className: 'NB-menu-manage-thirdparty-icon NB-menu-manage-thirdparty-twitter'}).bind('mouseenter', _.bind(function(e) {
$(e.target).siblings('.NB-menu-manage-title').text('Send to Twitter').parent().addClass('NB-menu-manage-highlight-twitter');
$(e.target).siblings('.NB-menu-manage-title').text('Twitter').parent().addClass('NB-menu-manage-highlight-twitter');
}, this)).bind('mouseleave', _.bind(function(e) {
$(e.target).siblings('.NB-menu-manage-title').text('Send to Instapaper').parent().removeClass('NB-menu-manage-highlight-twitter');
$(e.target).siblings('.NB-menu-manage-title').text('Email story').parent().removeClass('NB-menu-manage-highlight-twitter');
}, this))),
(NEWSBLUR.Preferences['story_share_readitlater'] && $.make('div', { className: 'NB-menu-manage-thirdparty-icon NB-menu-manage-thirdparty-readitlater'}).bind('mouseenter', _.bind(function(e) {
$(e.target).siblings('.NB-menu-manage-title').text('Read It Later').parent().addClass('NB-menu-manage-highlight-readitlater');
}, this)).bind('mouseleave', _.bind(function(e) {
$(e.target).siblings('.NB-menu-manage-title').text('Send to Instapaper').parent().removeClass('NB-menu-manage-highlight-readitlater');
$(e.target).siblings('.NB-menu-manage-title').text('Email story').parent().removeClass('NB-menu-manage-highlight-readitlater');
}, this))),
(NEWSBLUR.Preferences['story_share_email'] && $.make('div', { className: 'NB-menu-manage-thirdparty-icon NB-menu-manage-thirdparty-email'}).bind('mouseenter', _.bind(function(e) {
$(e.target).siblings('.NB-menu-manage-title').text('Send to email').parent().addClass('NB-menu-manage-highlight-email');
(NEWSBLUR.Preferences['story_share_pinboard'] && $.make('div', { className: 'NB-menu-manage-thirdparty-icon NB-menu-manage-thirdparty-pinboard'}).bind('mouseenter', _.bind(function(e) {
$(e.target).siblings('.NB-menu-manage-title').text('Pinboard').parent().addClass('NB-menu-manage-highlight-pinboard');
}, this)).bind('mouseleave', _.bind(function(e) {
$(e.target).siblings('.NB-menu-manage-title').text('Send to Instapaper').parent().removeClass('NB-menu-manage-highlight-email');
$(e.target).siblings('.NB-menu-manage-title').text('Email story').parent().removeClass('NB-menu-manage-highlight-pinboard');
}, this))),
(NEWSBLUR.Preferences['story_share_googleplus'] && $.make('div', { className: 'NB-menu-manage-thirdparty-icon NB-menu-manage-thirdparty-googleplus'}).bind('mouseenter', _.bind(function(e) {
$(e.target).siblings('.NB-menu-manage-title').text('Google+').parent().addClass('NB-menu-manage-highlight-googleplus');
}, this)).bind('mouseleave', _.bind(function(e) {
$(e.target).siblings('.NB-menu-manage-title').text('Email story').parent().removeClass('NB-menu-manage-highlight-googleplus');
}, this))),
(NEWSBLUR.Preferences['story_share_instapaper'] && $.make('div', { className: 'NB-menu-manage-thirdparty-icon NB-menu-manage-thirdparty-instapaper'}).bind('mouseenter', _.bind(function(e) {
$(e.target).siblings('.NB-menu-manage-title').text('Instapaper').parent().addClass('NB-menu-manage-highlight-instapaper');
}, this)).bind('mouseleave', _.bind(function(e) {
$(e.target).siblings('.NB-menu-manage-title').text('Email story').parent().removeClass('NB-menu-manage-highlight-instapaper');
}, this))),
// (NEWSBLUR.Preferences['story_share_readability'] && $.make('div', { className: 'NB-menu-manage-thirdparty-icon NB-menu-manage-thirdparty-readability'}).bind('mouseenter', _.bind(function(e) {
// $(e.target).siblings('.NB-menu-manage-title').text('Send to Readability').parent().addClass('NB-menu-manage-highlight-readability');
// $(e.target).siblings('.NB-menu-manage-title').text('Readability').parent().addClass('NB-menu-manage-highlight-readability');
// }, this)).bind('mouseleave', _.bind(function(e) {
// $(e.target).siblings('.NB-menu-manage-title').text('Send to Instapaper').parent().removeClass('NB-menu-manage-highlight-readability');
// $(e.target).siblings('.NB-menu-manage-title').text('Email story').parent().removeClass('NB-menu-manage-highlight-readability');
// }, this))),
$.make('div', { className: 'NB-menu-manage-image' }),
$.make('div', { className: 'NB-menu-manage-title' }, 'Send to Instapaper')
$.make('div', { className: 'NB-menu-manage-title' }, 'Email story')
]).bind('click', _.bind(function(e) {
e.preventDefault();
e.stopPropagation();
@ -4163,10 +4322,14 @@
this.send_story_to_readitlater(story.id);
} else if ($target.hasClass('NB-menu-manage-thirdparty-readability')) {
this.send_story_to_readability(story.id);
} else if ($target.hasClass('NB-menu-manage-thirdparty-email')) {
this.send_story_to_email(story.id);
} else {
} else if ($target.hasClass('NB-menu-manage-thirdparty-pinboard')) {
this.send_story_to_pinboard(story.id);
} else if ($target.hasClass('NB-menu-manage-thirdparty-googleplus')) {
this.send_story_to_googleplus(story.id);
} else if ($target.hasClass('NB-menu-manage-thirdparty-instapaper')) {
this.send_story_to_instapaper(story.id);
} else {
this.send_story_to_email(story.id);
}
}, this)),
$.make('li', { className: 'NB-menu-separator' }),
@ -4175,11 +4338,6 @@
$.make('div', { className: 'NB-menu-manage-title' }, 'Intelligence trainer'),
$.make('div', { className: 'NB-menu-manage-subtitle' }, 'What you like and dislike.')
])
// (story.read_status && $.make('li', { className: 'NB-menu-separator' })),
// (story.read_status && $.make('li', { className: 'NB-menu-manage-story-unread' }, [
// $.make('div', { className: 'NB-menu-manage-image' }),
// $.make('div', { className: 'NB-menu-manage-title' }, 'Mark as unread')
// ]))
]);
$manage_menu.data('feed_id', feed_id);
$manage_menu.data('story_id', story_id);
@ -4354,7 +4512,7 @@
$('.NB-task-manage').tipsy('enable');
}
$item.removeClass('NB-showing-menu');
if ($item) $item.removeClass('NB-showing-menu');
if (animate) {
$manage_menu_container.stop().animate({
@ -4519,15 +4677,26 @@
$feed = $feed || this.find_feed_in_feed_list(feed_id);
var $parent = $feed.closest('li.folder');
var in_folder = '';
var new_folder = $('.NB-menu-manage-feed-move-confirm select').val();
if (new_folder.length <= 0) return this.hide_confirm_move_menu_item();
var to_folder = $('.NB-menu-manage-feed-move-confirm select').val();
if ($parent.length) {
in_folder = $feed.eq(0).closest('li.folder').find('.folder_title_text').eq(0).text();
}
if (to_folder == in_folder) return this.hide_confirm_move_menu_item();
this.model.move_feed_to_folder(feed_id, new_folder, function() {});
this.model.move_feed_to_folder(feed_id, in_folder, to_folder, _.bind(function() {
_.delay(_.bind(function() {
this.$s.$feed_list.css('opacity', 1).animate({'opacity': 0}, {
'duration': 100,
'complete': _.bind(function() {
this.make_feeds();
}, this)
});
}, this), 250);
this.hide_manage_menu('feed', $feed, true);
}, this));
this.hide_confirm_move_menu_item(true);
},
@ -4535,16 +4704,36 @@
manage_menu_move_folder: function(folder, $folder) {
var self = this;
var in_folder = '';
var $parent = $folder.closest('li.folder');
var new_folder = $('.NB-menu-manage-folder-move-confirm select').val();
var $parent = $folder.parents('li.folder').eq(0);
var to_folder = $('.NB-menu-manage-folder-move-confirm select').val();
var folder_name = $folder.find('.folder_title_text').eq(0).text();
var child_folders = $folder.find('.folder_title_text').map(function() {
return $(this).text();
}).get();
if (new_folder.length <= 0) return this.hide_confirm_move_menu_item();
if ($parent.length) {
in_folder = $parent.find('.folder_title_text').eq(0).text();
}
this.model.move_folder_to_folder(folder, new_folder, in_folder, function() {});
if (to_folder == in_folder ||
to_folder == folder_name ||
_.contains(child_folders, to_folder)) {
return this.hide_confirm_move_menu_item();
}
this.model.move_folder_to_folder(folder, in_folder, to_folder, _.bind(function() {
_.delay(_.bind(function() {
this.$s.$feed_list.css('opacity', 1).animate({'opacity': 0}, {
'duration': 100,
'complete': _.bind(function() {
this.make_feeds();
}, this)
});
}, this), 250);
this.hide_manage_menu('folder', $parent, true);
}, this));
this.hide_confirm_move_menu_item(true);
},
@ -4634,7 +4823,6 @@
this.model.rename_folder(folder, new_folder_name, in_folder, function() {
});
NEWSBLUR.log(['rename', $folder, new_folder_name]);
$('.folder_title_text', $folder).text(new_folder_name);
this.hide_confirm_rename_menu_item(true);
@ -4675,6 +4863,7 @@
this.switch_feed_view_unread_view(value);
this.show_feed_hidden_story_title_indicator();
this.show_story_titles_above_intelligence_level({'animate': true, 'follow': true});
this.update_header_counts(true);
},
move_intelligence_slider: function(direction) {
@ -4720,6 +4909,8 @@
.removeClass('unread_threshold_neutral')
.removeClass('unread_threshold_negative')
.addClass('unread_threshold_'+unread_view_name);
this.update_header_counts(true, unread_view);
},
get_unread_view_name: function(unread_view) {
@ -4810,7 +5001,8 @@
}
}
if (this.story_view == 'feed' && this.model.preference('feed_view_single_story')) {
if ((this.story_view == 'feed' || this.flags.page_view_showing_feed_view) &&
this.model.preference('feed_view_single_story')) {
// No need to show/hide feed view stories under single_story preference.
// If the user switches to feed/page, then no animation is happening
// and this will work anyway.
@ -4880,19 +5072,47 @@
this.model.save_exception_retry(feed_id, _.bind(this.force_feed_refresh, this, feed_id, $feed));
},
setup_socket_realtime_unread_counts: function(force) {
if (force && !this.socket) {
this.socket = this.socket || io.connect('http://' + window.location.hostname + ':8888');
// this.socket.refresh_feeds = _.debounce(_.bind(this.force_feeds_refresh, this), 1000*10);
this.socket.on('connect', _.bind(function() {
this.socket.emit('subscribe:feeds', _.keys(this.model.feeds));
this.socket.on('feed:update', _.bind(function(feed_id, message) {
console.log(['Feed update', feed_id, message]);
this.force_feeds_refresh(false, false, parseInt(feed_id, 10));
}, this));
this.flags.feed_refreshing_in_realtime = true;
this.setup_feed_refresh();
}, this));
}
},
setup_feed_refresh: function(new_feeds) {
var self = this;
var refresh_interval = this.constants.FEED_REFRESH_INTERVAL;
var feed_count = _.size(this.model.feeds);
if (!NEWSBLUR.Globals.is_premium) {
refresh_interval *= 2;
}
// if (_.size(this.model.feeds) > 250) {
// refresh_interval *= 4;
// }
if (feed_count > 250) {
refresh_interval *= 4;
}
if (feed_count > 500) {
refresh_interval *= 1.5;
}
if (this.flags.feed_refreshing_in_realtime) {
refresh_interval *= 20;
}
if (new_feeds) {
if (new_feeds && feed_count < 250) {
refresh_interval = (1000 * 60) * 1/10;
} else if (new_feeds && feed_count < 500) {
refresh_interval = (1000 * 60) * 1/4;
}
clearInterval(this.flags.feed_refresh);
@ -5016,7 +5236,7 @@
for (var s in this.model.stories) {
var story = this.model.stories[s];
var $story = this.find_story_in_story_titles(story.id);
var $feed_story = this.find_story_in_feed_view(story);
var $feed_story = this.find_story_in_feed_view(story.id);
if ($story && $story.length) {
// Just update intelligence
@ -5352,6 +5572,7 @@
$progress.addClass('NB-progress-error');
$('.NB-progress-title', $progress).text('Error importing Google Reader');
$('.NB-progress-link', $progress).html($.make('a', { href: NEWSBLUR.URLs['google-reader-authorize'], className: 'NB-splash-link' }, 'Try importing again'));
$('.left-center-footer').css('height', 'auto');
}
},
@ -5831,7 +6052,7 @@
e.stopPropagation();
var folder_name = $t.parents('.NB-menu-manage').data('folder_name');
var $folder = $t.parents('.NB-menu-manage').data('$folder');
self.manage_menu_rename_folder(folder_name, $folder);
self.manage_menu_move_folder(folder_name, $folder);
});
$.targetIs(e, { tagSelector: '.NB-menu-manage-feed-move-save' }, function($t, $p){
e.preventDefault();
@ -6409,11 +6630,11 @@
});
$document.bind('keydown', 'space', function(e) {
e.preventDefault();
self.page_in_story(0.2, 1);
self.page_in_story(0.4, 1);
});
$document.bind('keydown', 'shift+space', function(e) {
e.preventDefault();
self.page_in_story(0.4, -1);
self.page_in_story(0.6, -1);
});
$document.bind('keydown', 'u', function(e) {
e.preventDefault();
@ -6427,6 +6648,10 @@
e.preventDefault();
self.open_next_unread_story_across_feeds();
});
$document.bind('keydown', 'm', function(e) {
e.preventDefault();
self.show_last_unread_story();
});
$document.bind('keydown', 'b', function(e) {
e.preventDefault();
self.show_previous_story();
@ -6475,6 +6700,10 @@
self.mark_feed_as_read();
}
});
$document.bind('keydown', 'shift+e', function(e) {
e.preventDefault();
self.open_river_stories();
});
}
};

View file

@ -129,6 +129,7 @@ NEWSBLUR.ReaderFeedchooser.prototype = {
var $paypal = $('.NB-feedchooser-paypal', this.$modal);
$.get('/profile/paypal_form', function(response) {
$paypal.html(response);
self.choose_dollar_amount(2);
});
},

View file

@ -255,6 +255,19 @@ _.extend(NEWSBLUR.ReaderPreferences.prototype, {
'Site sidebar order'
])
]),
$.make('div', { className: 'NB-preference NB-preference-showunreadcountsintitle' }, [
$.make('div', { className: 'NB-preference-options' }, [
$.make('div', [
$.make('input', { id: 'NB-preference-showunreadcountsintitle-1', type: 'checkbox', name: 'show_unread_counts_in_title', value: 0 }),
$.make('label', { 'for': 'NB-preference-showunreadcountsintitle-1' }, [
'Show unread counts in the window title'
])
])
]),
$.make('div', { className: 'NB-preference-label'}, [
'Window title'
])
]),
$.make('div', { className: 'NB-preference NB-preference-hidestorychanges' }, [
$.make('div', { className: 'NB-preference-options' }, [
$.make('div', [
@ -400,6 +413,14 @@ _.extend(NEWSBLUR.ReaderPreferences.prototype, {
$.make('input', { type: 'checkbox', id: 'NB-preference-story-share-instapaper', name: 'story_share_instapaper' }),
$.make('label', { 'for': 'NB-preference-story-share-instapaper' })
]),
$.make('div', { className: 'NB-preference-option', title: 'Pinboard.in' }, [
$.make('input', { type: 'checkbox', id: 'NB-preference-story-share-pinboard', name: 'story_share_pinboard' }),
$.make('label', { 'for': 'NB-preference-story-share-pinboard' })
]),
$.make('div', { className: 'NB-preference-option', title: 'Google+' }, [
$.make('input', { type: 'checkbox', id: 'NB-preference-story-share-googleplus', name: 'story_share_googleplus' }),
$.make('label', { 'for': 'NB-preference-story-share-googleplus' })
]),
$.make('div', { className: 'NB-preference-option', title: 'Read It Later' }, [
$.make('input', { type: 'checkbox', id: 'NB-preference-story-share-readitlater', name: 'story_share_readitlater' }),
$.make('label', { 'for': 'NB-preference-story-share-readitlater' })
@ -484,6 +505,12 @@ _.extend(NEWSBLUR.ReaderPreferences.prototype, {
return false;
}
});
$('input[name=show_unread_counts_in_title]', this.$modal).each(function() {
if (NEWSBLUR.Preferences.show_unread_counts_in_title) {
$(this).attr('checked', true);
return false;
}
});
$('input[name=hide_story_changes]', this.$modal).each(function() {
if ($(this).val() == NEWSBLUR.Preferences.hide_story_changes) {
$(this).attr('checked', true);
@ -557,6 +584,7 @@ _.extend(NEWSBLUR.ReaderPreferences.prototype, {
NEWSBLUR.reader.apply_story_styling(true);
NEWSBLUR.reader.apply_tipsy_titles();
NEWSBLUR.reader.show_stories_preference_in_feed_view();
NEWSBLUR.reader.update_header_counts();
if (self.original_preferences['feed_order'] != form['feed_order'] ||
self.original_preferences['folder_counts'] != form['folder_counts']) {
NEWSBLUR.reader.make_feeds();

View file

@ -99,7 +99,7 @@ NEWSBLUR.utils = {
var $option = $.make('option', { value: '' }, "Top Level");
$options.append($option);
$options = this.make_folder_options($options, folders, '-');
$options = this.make_folder_options($options, folders, '&nbsp;&nbsp;&nbsp;');
return $options;
},
@ -112,7 +112,7 @@ NEWSBLUR.utils = {
var folder = item[o];
var $option = $.make('option', { value: o }, depth + ' ' + o);
$options.append($option);
$options = this.make_folder_options($options, folder, depth+'-');
$options = this.make_folder_options($options, folder, depth+'&nbsp;&nbsp;&nbsp;');
}
}
}

File diff suppressed because one or more lines are too long

21
node/unread_counts.cs Normal file
View file

@ -0,0 +1,21 @@
fs = require 'fs'
io = require('socket.io').listen 8888
redis = require 'redis'
client = redis.createClient()
io.sockets.on 'connection', (socket) ->
socket.on 'subscribe:feeds', (feeds) ->
socket.subscribe = redis.createClient()
console.log "Subscribing to #{feeds.length} feeds"
socket.subscribe.subscribe feeds
socket.subscribe.on 'message', (channel, message) ->
console.log "Update on #{channel}: #{message}"
socket.emit 'feed:update', channel
socket.on 'disconnect', () ->
socket.subscribe?.end()
console.log 'Disconnect'

29
node/unread_counts.js Normal file
View file

@ -0,0 +1,29 @@
(function() {
var client, fs, io, redis;
fs = require('fs');
io = require('socket.io').listen(8888);
redis = require('redis');
client = redis.createClient();
io.sockets.on('connection', function(socket) {
socket.on('subscribe:feeds', function(feeds) {
socket.subscribe = redis.createClient();
console.log("Subscribing to " + feeds.length + " feeds");
socket.subscribe.subscribe(feeds);
return socket.subscribe.on('message', function(channel, message) {
console.log("Update on " + channel + ": " + message);
return socket.emit('feed:update', channel);
});
});
return socket.on('disconnect', function() {
var _ref;
if ((_ref = socket.subscribe) != null) _ref.end();
return console.log('Disconnect');
});
});
}).call(this);

View file

@ -2,6 +2,7 @@ import sys
import logging
import os
from mongoengine import connect
import redis
# ===========================
# = Directory Declaractions =
@ -182,6 +183,7 @@ COMPRESS_JS = {
'js/jquery.fieldselection.js',
'js/jquery.flot.js',
'js/jquery.tipsy.js',
# 'js/socket.io-client.0.8.7.js',
'js/underscore.js',
'js/underscore.string.js',
'js/newsblur/reader_utils.js',
@ -420,7 +422,23 @@ class MasterSlaveRouter(object):
def allow_syncdb(self, db, model):
"Explicitly put all models on all databases."
return True
# =========
# = Redis =
# =========
REDIS = {
'host': 'db02',
}
# ===========
# = MongoDB =
# ===========
MONGODB_SLAVE = {
'host': 'db01'
}
# ==================
# = Configurations =
# ==================
@ -451,8 +469,13 @@ DEBUG_TOOLBAR_CONFIG = {
MONGO_DB_DEFAULTS = {
'name': 'newsblur',
'host': 'mongodb://db01,db02/?slaveOk=true',
# 'tz_aware': True,
'host': 'mongodb://db01,db03/?slaveOk=true',
}
MONGO_DB = dict(MONGO_DB_DEFAULTS, **MONGO_DB)
MONGODB = connect(MONGO_DB.pop('name'), **MONGO_DB)
# =========
# = Redis =
# =========
REDIS_POOL = redis.ConnectionPool(host=REDIS['host'], port=6379, db=0)

View file

@ -377,7 +377,7 @@ $(document).ready(function() {
<div class="NB-module-item-title">
<span class="NB-raquo">&raquo;</span>
<!-- <a href="#" class="NB-splash-link">Download NewsBlur on the App Store</a> -->
<span class="NB-module-mobile-freeforpremium">Approved, but not Good Enough. Working on v1.1.</span>
<span class="NB-module-mobile-freeforpremium">Approved, but not Good Enough. Working on v1.2.</span>
</div>
</div>
<div class="NB-module-item NB-last {% if user_profile.hide_mobile %}NB-hidden{% endif %}">

View file

@ -84,6 +84,15 @@
optional: true
default: "false"
example: "true/false"
- key: update_counts
desc: >
Forces recalculation of unread counts on all feeds. The preferred method is
to call this endpoint without updated counts, then call refresh_feeds to get
updated counts. That way you can quickly show the user's feeds, then update
the counts. Turning this option on will lead to a slower load-time.
optional: true
default: "false"
example: "true/false"
- url: /reader/favicons
method: GET
@ -228,6 +237,37 @@
required: true
example: "42"
- url: /reader/mark_feed_stories_as_read
method: POST
short_desc: "Mark stories from multiple feeds as read."
long_desc:
- "Marks multiple stories as read."
- "Multiple story ids can be sent at once."
- "Multiple feeds can be sent."
tips:
- "Throttle requests to this endpoint. You don't need to send one request per story."
- "Queue up to 5 stories or once every 10 seconds before firing, whichever comes first."
params:
- key: feeds_stories
desc: "JSON serialized dictionary of feed_ids to an array of story_ids."
required: true
example: "{<br>12: ['story_id_1', 'story_id_2'],<br>24: ['story_id_3']<br>}"
- url: /reader/mark_story_as_unread
method: POST
short_desc: "Mark a story as unread."
long_desc:
- "Mark a story as unread."
params:
- key: story_id
desc: "Story id to mark unread."
required: true
example: "http://www.ofbrooklyn.com/story-title"
- key: feed_id
desc: "Feed id that the story is from."
required: true
example: "42"
- url: /reader/mark_story_as_starred
method: POST
short_desc: "Mark a story as starred (saved)."
@ -245,17 +285,17 @@
- url: /reader/mark_feed_as_read
method: POST
short_desc: "Mark all stories in a feed as read."
short_desc: "Mark a list of feeds as read."
long_desc:
- "Mark all stories in a feed or list of feeds as read."
- "Mark a list of feeds as read."
params:
- key: feed_id
desc: "List of feed ids to mark as read."
required: true
example: "[12, 24, 36]"
tips:
- "To mark a folder as read, send the ids of each feed inside the folder."
params:
- key: feed_ids
desc: "List of feed ids to mark as read."
optional: true
example: "[12, 24, 36]"
- url: /reader/mark_all_as_read
method: POST
short_desc: "Mark all stories from all feeds as read."
@ -303,6 +343,52 @@
default: "[Top Level]"
example: "All Blogs"
- url: /reader/move_feed_to_folder
method: POST
short_desc: "Move a feed into a different folder."
long_desc:
- "Move a feed into a different folder."
params:
- key: feed_id
desc: "Feed id."
required: true
example: 12
- key: in_folder
desc: >
Current folder the feed is in. Necessary to disambiguate if a feed is in
multiple folders.
required: true
example: "Blogs"
- key: in_folder
desc: "Folder the feed is going into."
required: true
example: "Tumblrs"
tips:
- "Leave folder names blank to specify Top Level."
- url: /reader/move_folder_to_folder
method: POST
short_desc: "Move a folder into a different folder."
long_desc:
- "Move a folder into a different folder."
params:
- key: folder_name
desc: "Name of folder being moved."
required: true
example: "Tumblrs"
- key: in_folder
desc: >
Current folder the folder is in. Necessary to disambiguate if a folder
name is in multiple folders. (Please don't let this happen.)
required: true
example: "Blogs"
- key: in_folder
desc: "New folder the existing folder is going into."
required: true
example: "Daily Blogs"
tips:
- "Leave folder names blank to specify Top Level."
- url: /reader/rename_feed
method: POST
short_desc: "Rename a feed title."
@ -374,17 +460,7 @@
desc: "List of feed ids in the folder that's being deleted. These feeds also get removed."
optional: true
example: "[12, 24, 36]"
- url: /reader/mark_feed_as_read
method: POST
short_desc: "Mark a list of feeds as read."
long_desc:
- "Mark a list of feeds as read."
params:
- key: feed_id
desc: "List of feed ids to mark as read."
required: true
example: "[12, 24, 36]"
- url: /reader/save_feed_order
method: POST

View file

@ -11,12 +11,14 @@ from utils import feedparser
from utils.story_functions import pre_process_story
from utils import log as logging
from utils.feed_functions import timelimit, TimeoutError, mail_feed_error_to_admin, utf8encode
from utils.story_functions import bunch
import time
import datetime
import traceback
import multiprocessing
import urllib2
import xml.sax
import redis
# Refresh feed code adapted from Feedjack.
# http://feedjack.googlecode.com
@ -44,9 +46,10 @@ class FetchFeed:
Uses feedparser to download the feed. Will be parsed later.
"""
identity = self.get_identity()
log_msg = u'%2s ---> [%-30s] Fetching feed (%d)' % (identity,
log_msg = u'%2s ---> [%-30s] Fetching feed (%d), last update: %s' % (identity,
unicode(self.feed)[:30],
self.feed.id)
self.feed.id,
datetime.datetime.now() - self.feed.last_update)
logging.debug(log_msg)
self.feed.set_next_scheduled_update()
@ -57,7 +60,7 @@ class FetchFeed:
modified = None
etag = None
USER_AGENT = 'NewsBlur Feed Fetcher (%s subscriber%s) - %s' % (
USER_AGENT = 'NewsBlur Feed Fetcher (%s subscriber%s) - %s (Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_1) AppleWebKit/534.48.3 (KHTML, like Gecko) Version/5.1 Safari/534.48.3)' % (
self.feed.num_subscribers,
's' if self.feed.num_subscribers != 1 else '',
URL
@ -147,8 +150,8 @@ class ProcessFeed:
return FEED_ERRHTTP, ret_values
if self.fpf.bozo and isinstance(self.fpf.bozo_exception, feedparser.NonXMLContentType):
logging.debug(" ---> [%-30s] Feed is Non-XML. %s entries.%s Checking address..." % (unicode(self.feed)[:30], len(self.fpf.entries), ' Not' if self.fpf.entries else ''))
if not self.fpf.entries:
logging.debug(" ---> [%-30s] Feed is Non-XML. %s entries. Checking address..." % (unicode(self.feed)[:30], len(self.fpf.entries)))
fixed_feed = self.feed.check_feed_address_for_feed_link()
if not fixed_feed:
self.feed.save_feed_history(502, 'Non-xml feed', self.fpf.bozo_exception)
@ -157,7 +160,7 @@ class ProcessFeed:
self.feed.save()
return FEED_ERRPARSE, ret_values
elif self.fpf.bozo and isinstance(self.fpf.bozo_exception, xml.sax._exceptions.SAXException):
logging.debug(" ---> [%-30s] Feed is Bad XML (SAX). %s entries. Checking address..." % (unicode(self.feed)[:30], len(self.fpf.entries)))
logging.debug(" ---> [%-30s] Feed has SAX/XML parsing issues. %s entries.%s Checking address..." % (unicode(self.feed)[:30], len(self.fpf.entries), ' Not' if self.fpf.entries else ''))
if not self.fpf.entries:
fixed_feed = self.feed.check_feed_address_for_feed_link()
if not fixed_feed:
@ -214,11 +217,24 @@ class ProcessFeed:
# if story.get('published') > end_date:
# end_date = story.get('published')
story_guids.append(story.get('guid') or story.get('link'))
existing_stories = list(MStory.objects(
# story_guid__in=story_guids,
story_date__gte=start_date,
story_feed_id=self.feed.pk
).limit(len(story_guids)))
if self.options['slave_db']:
slave_db = self.options['slave_db']
stories_db_orig = slave_db.stories.find({
"story_feed_id": self.feed.pk,
"story_date": {
"$gte": start_date,
},
}).limit(len(story_guids))
existing_stories = []
for story in stories_db_orig:
existing_stories.append(bunch(story))
else:
existing_stories = list(MStory.objects(
# story_guid__in=story_guids,
story_date__gte=start_date,
story_feed_id=self.feed.pk
).limit(len(story_guids)))
# MStory.objects(
# (Q(story_date__gte=start_date) & Q(story_date__lte=end_date))
@ -227,10 +243,9 @@ class ProcessFeed:
# ).order_by('-story_date')
ret_values = self.feed.add_update_stories(self.fpf.entries, existing_stories)
logging.debug(u' ---> [%-30s] Parsed Feed: %s' % (
logging.debug(u' ---> [%-30s] ~FYParsed Feed: new~FG=~FG~SB%s~SN~FY up~FG=~FY~SB%s~SN same~FG=~FY%s err~FG=~FR~SB%s' % (
unicode(self.feed)[:30],
u' '.join(u'%s=%d' % (self.entry_trans[key],
ret_values[key]) for key in self.entry_keys),))
ret_values[ENTRY_NEW], ret_values[ENTRY_UPDATED], ret_values[ENTRY_SAME], ret_values[ENTRY_ERR]))
self.feed.update_all_statistics()
self.feed.trim_feed()
self.feed.save_feed_history(200, "OK")
@ -379,6 +394,9 @@ class Dispatcher:
except IntegrityError:
logging.debug(" ---> [%-30s] IntegrityError on feed: %s" % (unicode(feed)[:30], feed.feed_address,))
if ret_entries[ENTRY_NEW]:
self.publish_to_subscribers(feed)
done_msg = (u'%2s ---> [%-30s] Processed in %s (%s) [%s]' % (
identity, feed.feed_title[:30], unicode(delta),
feed.pk, self.feed_trans[ret_feed],))
@ -390,6 +408,15 @@ class Dispatcher:
# time_taken = datetime.datetime.utcnow() - self.time_start
def publish_to_subscribers(self, feed):
try:
r = redis.Redis(connection_pool=settings.REDIS_POOL)
listeners_count = r.publish(str(feed.pk), 'story:new')
if listeners_count:
logging.debug(" ---> [%-30s] Published to %s subscribers" % (unicode(feed)[:30], listeners_count))
except redis.ConnectionError:
logging.debug(" ***> [%-30s] Redis is unavailable for real-time." % (unicode(feed)[:30],))
@timelimit(20)
def count_unreads_for_subscribers(self, feed):
UNREAD_CUTOFF = datetime.datetime.utcnow() - datetime.timedelta(days=settings.DAYS_OF_UNREAD)
@ -401,8 +428,21 @@ class Dispatcher:
unicode(feed)[:30], user_subs.count(),
feed.num_subscribers, feed.active_subscribers, feed.premium_subscribers))
stories_db = MStory.objects(story_feed_id=feed.pk,
story_date__gte=UNREAD_CUTOFF)
if self.options['slave_db']:
slave_db = self.options['slave_db']
stories_db_orig = slave_db.stories.find({
"story_feed_id": feed.pk,
"story_date": {
"$gte": UNREAD_CUTOFF,
},
})
stories_db = []
for story in stories_db_orig:
stories_db.append(bunch(story))
else:
stories_db = MStory.objects(story_feed_id=feed.pk,
story_date__gte=UNREAD_CUTOFF)
for sub in user_subs:
cache.delete('usersub:%s' % sub.user_id)
sub.needs_unread_recalc = True

View file

@ -73,7 +73,7 @@ class URLGatekeeper:
def __init__(self):
self.rpcache = {} # a dictionary of RobotFileParser objects, by domain
self.urlopener = urllib.FancyURLopener()
self.urlopener.version = "NewsBlur Feed Finder"
self.urlopener.version = "NewsBlur Feed Finder (Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_1) AppleWebKit/534.48.3 (KHTML, like Gecko) Version/5.1 Safari/534.48.3)"
_debuglog(self.urlopener.version)
self.urlopener.addheaders = [('User-agent', self.urlopener.version)]
robotparser.URLopener.version = self.urlopener.version
@ -314,7 +314,7 @@ def feed(uri):
#todo: give preference to certain feed formats
feedlist = feeds(uri)
if feedlist:
feeds_no_comments = filter(lambda f: not 'comments' in f, feedlist)
feeds_no_comments = filter(lambda f: 'comments' not in f.lower(), feedlist)
if feeds_no_comments:
return feeds_no_comments[0]
return feedlist[0]

View file

@ -2563,7 +2563,8 @@ class _HTMLSanitizer(_BaseHTMLProcessor):
'p', 'pre', 'progress', 'q', 's', 'samp', 'section', 'select',
'small', 'sound', 'source', 'spacer', 'span', 'strike', 'strong',
'sub', 'sup', 'table', 'tbody', 'td', 'textarea', 'time', 'tfoot',
'th', 'thead', 'tr', 'tt', 'u', 'ul', 'var', 'video', 'noscript']
'th', 'thead', 'tr', 'tt', 'u', 'ul', 'var', 'video', 'noscript',
'object', 'embed', 'iframe', 'param']
acceptable_attributes = ['abbr', 'accept', 'accept-charset', 'accesskey',
'action', 'align', 'alt', 'autocomplete', 'autofocus', 'axis',

View file

@ -6,23 +6,19 @@ graph_config = {
'graph_category' : 'NewsBlur',
'graph_title' : 'NewsBlur Fetching History',
'graph_vlabel' : 'errors',
'feed_errors.label': 'Feed Errors',
# 'feed_errors.label': 'Feed Errors',
'feed_success.label': 'Feed Success',
'page_errors.label': 'Page Errors',
# 'page_errors.label': 'Page Errors',
'page_success.label': 'Page Success',
}
def calculate_metrics():
import datetime
from apps.rss_feeds.models import MFeedFetchHistory, MPageFetchHistory
last_day = datetime.datetime.utcnow() - datetime.timedelta(days=1)
from apps.statistics.models import MStatistics
statistics = MStatistics.all()
return {
'feed_errors': MFeedFetchHistory.objects(fetch_date__gte=last_day, status_code__nin=[200, 304]).count(),
'feed_success': MFeedFetchHistory.objects(fetch_date__gte=last_day, status_code__in=[200, 304]).count(),
'page_errors': MPageFetchHistory.objects(fetch_date__gte=last_day, status_code__nin=[200, 304]).count(),
'page_success': MPageFetchHistory.objects(fetch_date__gte=last_day, status_code__in=[200, 304]).count(),
'feed_success': statistics['feeds_fetched'],
'page_success': statistics['pages_fetched'],
}
if __name__ == '__main__':

106
utils/ratelimit.py Normal file
View file

@ -0,0 +1,106 @@
from django.http import HttpResponseForbidden
from django.core.cache import cache
from datetime import datetime, timedelta
import functools, sha
class ratelimit(object):
"Instances of this class can be used as decorators"
# This class is designed to be sub-classed
minutes = 1 # The time period
requests = 4 # Number of allowed requests in that time period
prefix = 'rl-' # Prefix for memcache key
def __init__(self, **options):
for key, value in options.items():
setattr(self, key, value)
def __call__(self, fn):
def wrapper(request, *args, **kwargs):
return self.view_wrapper(request, fn, *args, **kwargs)
functools.update_wrapper(wrapper, fn)
return wrapper
def view_wrapper(self, request, fn, *args, **kwargs):
if not self.should_ratelimit(request):
return fn(request, *args, **kwargs)
counts = self.get_counters(request).values()
# Increment rate limiting counter
self.cache_incr(self.current_key(request))
# Have they failed?
if sum(counts) >= self.requests:
return self.disallowed(request)
return fn(request, *args, **kwargs)
def cache_get_many(self, keys):
return cache.get_many(keys)
def cache_incr(self, key):
# memcache is only backend that can increment atomically
try:
# add first, to ensure the key exists
cache.add(key, 0, self.expire_after())
cache.incr(key)
except AttributeError:
cache.set(key, cache.get(key, 0) + 1, self.expire_after())
def should_ratelimit(self, request):
return True
def get_counters(self, request):
return self.cache_get_many(self.keys_to_check(request))
def keys_to_check(self, request):
extra = self.key_extra(request)
now = datetime.now()
return [
'%s%s-%s' % (
self.prefix,
extra,
(now - timedelta(minutes = minute)).strftime('%Y%m%d%H%M')
) for minute in range(self.minutes + 1)
]
def current_key(self, request):
return '%s%s-%s' % (
self.prefix,
self.key_extra(request),
datetime.now().strftime('%Y%m%d%H%M')
)
def key_extra(self, request):
key = getattr(request.session, 'session_key', '')
if not key:
key = request.META.get('HTTP_X_FORWARDED_FOR', '').split(',')[0]
if not key:
key = request.COOKIES.get('newsblur_sessionid', '')
if not key:
key = request.META.get('HTTP_USER_AGENT', '')
return key
def disallowed(self, request):
"Over-ride this method if you want to log incidents"
return HttpResponseForbidden('Rate limit exceeded')
def expire_after(self):
"Used for setting the memcached cache expiry"
return (self.minutes + 1) * 60
class ratelimit_post(ratelimit):
"Rate limit POSTs - can be used to protect a login form"
key_field = None # If provided, this POST var will affect the rate limit
def should_ratelimit(self, request):
return request.method == 'POST'
def key_extra(self, request):
# IP address and key_field (if it is set)
extra = super(ratelimit_post, self).key_extra(request)
if self.key_field:
value = sha.new(request.POST.get(self.key_field, '')).hexdigest()
extra += '-' + value
return extra