Ejemplo n.º 1
0
Archivo: views.py Proyecto: fk-lx/mygpo
    def post(self, request):

        username = request.POST.get('username')
        email = request.POST.get('email')

        if not (username or email):
            messages.error(request,
                           _('Provide either username or email address'))
            return HttpResponseRedirect(reverse('admin-activate-user'))

        user = None

        if username:
            user = User.get_user(username, is_active=None)

        if email and not user:
            user = User.get_user_by_email(email, is_active=None)

        if not user:
            messages.error(request, _('No user found'))
            return HttpResponseRedirect(reverse('admin-activate-user'))

        activate_user(user)
        messages.success(request,
                         _('User {username} ({email}) activated'.format(
                            username=user.username, email=user.email)))
        return HttpResponseRedirect(reverse('admin-activate-user'))
Ejemplo n.º 2
0
Archivo: users.py Proyecto: fk-lx/mygpo
def get_user(username, email, is_active=None):
    if username:
        return User.get_user(username, is_active=None)

    elif email:
        return User.get_user_by_email(email, is_active=None)

    return None
Ejemplo n.º 3
0
    def get(self, request, username):

        user = User.get_user(username)
        month_ago = datetime.today() - timedelta(days=31)
        site = RequestSite(request)

        context_funs = {
            'lists': partial(self.get_podcast_lists, user),
            'subscriptions': partial(self.get_subscriptions, user),
            'recent_episodes': partial(self.get_recent_episodes, user),
            'seconds_played_total': partial(self.get_seconds_played_total, user),
            'seconds_played_month': partial(self.get_seconds_played_since, user, month_ago),
            'favorite_episodes': partial(self.get_favorite_episodes, user),
            'num_played_episodes_total': partial(self.get_played_episodes_total, user),
            'num_played_episodes_month': partial(self.get_played_episodes_since, user, month_ago),
        }

        context = {
            'page_user': user,
            'flattr_username': user.get_wksetting(FLATTR_USERNAME),
            'site': site.domain,
            'subscriptions_token': user.get_token('subscriptions_token'),
            'favorite_feeds_token': user.get_token('favorite_feeds_token'),
        }
        context.update(self.get_context(context_funs))

        return render(request, 'userpage.html', context)
Ejemplo n.º 4
0
Archivo: sync.py Proyecto: Mic92/mygpo
def main(request, username):
    """ API Endpoint for Device Synchronisation """

    if request.method == 'GET':
        return JsonResponse(get_sync_status(request.user))

    else:
        try:
            actions = json.loads(request.raw_post_data)
        except Exception as e:
            return HttpResponseBadRequest(str(e))

        synclist = actions.get('synchronize', [])
        stopsync = actions.get('stop-synchronize', [])

        try:
            update_sync_status(request.user, synclist, stopsync)
        except ValueError as e:
            return HttpResponseBadRequest(str(e))
        except DeviceDoesNotExist as e:
            return HttpResponseNotFound(str(e))

        # reload user to get current sync status
        user = User.get(request.user._id)
        return JsonResponse(get_sync_status(user))
Ejemplo n.º 5
0
    def handle(self, *args, **options):

        docs = set()
        progress(0, len(docs), '', stream=sys.stderr)

        for username in options.get('users', []):
            user = User.get_user(username)
            self.add_user_recursive(user, docs)

        if options.get('toplist', False):
            toplist = PodcastToplist()
            for n, podcast in toplist[:25]:
                self.add_podcast_recursive(podcast, docs)

        for podcast_url in options.get('podcasts'):
            podcast = podcast_for_url(podcast_url, docs)
            if not podcast:
                logger.warn('podcast not found for URL "%s"', podcast_url)

            else:
                self.add_podcast_recursive(podcast, docs)

        db = get_main_database()
        docs = sorted(docs)
        self.dump(docs, db)
Ejemplo n.º 6
0
Archivo: user.py Proyecto: fk-lx/mygpo
def deleted_users():
    from mygpo.users.models import User
    users = User.view('users/deleted',
            include_docs = True,
            reduce       = False,
        )
    return list(users)
Ejemplo n.º 7
0
Archivo: tests.py Proyecto: fk-lx/mygpo
    def setUp(self):
        self.podcast1 = Podcast(urls=['http://example.com/feed.rss'])
        self.podcast2 = Podcast(urls=['http://test.org/podcast/'])
        self.podcast3 = Podcast(urls=['http://test.org/feed/'])
        self.podcast1.save()
        self.podcast2.save()
        self.podcast3.save()

        self.episode1 = Episode(podcast=self.podcast1.get_id(),
                urls = ['http://example.com/episode1.mp3'])
        self.episode2 = Episode(podcast=self.podcast2.get_id(),
                urls = ['http://example.com/episode1.mp3'])
        self.episode3 = Episode(podcast=self.podcast3.get_id(),
                urls = ['http://example.com/media.mp3'])


        self.episode1.save()
        self.episode2.save()
        self.episode3.save()

        self.podcast2.group_with(self.podcast3, 'My Group', 'Feed1', 'Feed2')

        self.user = User(username='******')
        self.user.email = '*****@*****.**'
        self.user.set_password('secret!')
        self.user.save()
Ejemplo n.º 8
0
Archivo: tests.py Proyecto: fk-lx/mygpo
    def setUp(self):
        self.password = '******'
        self.username = '******'
        self.user = User(username=self.username, email='*****@*****.**')
        self.user.set_password(self.password)
        self.user.save()
        self.user.is_active = True
        self.client = Client()

        self.extra = {
            'HTTP_AUTHORIZATION': create_auth_string(self.username, self.password)
        }

        self.action_data = [
          {
           "podcast": "http://example.com/feed.rss",
           "episode": "http://example.com/files/s01e20.mp3",
           "device": "gpodder_abcdef123",
           "action": "download",
           "timestamp": "2009-12-12T09:00:00"
          },
          {
           "podcast": "http://example.org/podcast.php",
           "episode": "http://ftp.example.org/foo.ogg",
           "action": "play",
           "started": 15,
           "position": 120,
           "total":  500
          }
        ]
Ejemplo n.º 9
0
Archivo: views.py Proyecto: fk-lx/mygpo
def update_published_podcasts(request, username):
    user = User.get_user(username)
    if not user:
        raise Http404

    published_podcasts = podcasts_by_id(user.published_objects)
    update_podcasts.delay([podcast.url for podcast in published_podcasts])
    return HttpResponse('Updated:\n' + '\n'.join([p.url for p in published_podcasts]), mimetype='text/plain')
Ejemplo n.º 10
0
Archivo: auth.py Proyecto: Mic92/mygpo
    def authenticate(self, username=None, password=None):
        if email_re.search(username):
            user = User.get_user_by_email(username)
            if not user:
                return None

            return user if user.check_password(password) else None
        return None
Ejemplo n.º 11
0
 def _prepare_list(self, l):
     podcasts = Podcast.get_multi(l.podcasts[:self.podcasts_per_topic])
     user = User.get(l.user)
     l = proxy_object(l)
     l.podcasts = podcasts
     l.username = user.username
     l.cls = "PodcastList"
     return l
Ejemplo n.º 12
0
    def handle(self, *args, **options):

        users = User.view("users/deleted", include_docs=True, reduce=False)

        total = User.view("users/deleted", reduce=True)

        total = list(total)[0]["value"] if total else 0

        for n, user in enumerate(users):

            if user.is_active or not user.deleted:
                print "skipping", user.username

            print "deleting", user.username,
            user.delete()

            progress(n + 1, total)
Ejemplo n.º 13
0
Archivo: views.py Proyecto: Mic92/mygpo
def lists_user(request, username):

    user = User.get_user(username)
    if not user:
        raise Http404

    lists = PodcastList.for_user(user._id)

    return render(request, "lists_user.html", {"lists": lists, "user": user})
Ejemplo n.º 14
0
Archivo: user.py Proyecto: fk-lx/mygpo
def user_agent_stats():
    from mygpo.users.models import User
    res = User.view('clients/by_ua_string',
        wrap_doc    = False,
        group_level = 1,
        stale       = 'update_after',
    )

    return Counter(dict((r['key'], r['value']) for r in res))
Ejemplo n.º 15
0
    def get_entries(self):
        if self._useragents is None:
            res = User.view('clients/by_ua_string',
                wrap_doc    = False,
                group_level = 1,
                stale       = 'update_after',
            )

            self._useragents = Counter(dict((r['key'], r['value']) for r in res))

        return self._useragents
Ejemplo n.º 16
0
Archivo: views.py Proyecto: fk-lx/mygpo
def lists_user(request, username):

    user = User.get_user(username)
    if not user:
        raise Http404

    lists = podcastlists_for_user(user._id)

    return render(request, 'lists_user.html', {
            'lists': lists,
            'user': user,
        })
Ejemplo n.º 17
0
Archivo: auth.py Proyecto: fk-lx/mygpo
    def authenticate(self, username=None, password=None):
        try:
            validate_email(username)

            user = User.get_user_by_email(username)
            if not user:
                return None

            return user if user.check_password(password) else None

        except ValidationError:
            return None
Ejemplo n.º 18
0
Archivo: tests.py Proyecto: fk-lx/mygpo
    def setUp(self):
        self.podcast1 = Podcast(urls=['http://example.com/feed.rss'])
        self.podcast2 = Podcast(urls=[self.P2_URL])
        self.podcast1.save()
        self.podcast2.save()

        self.user = User(username='******')
        self.user.email = '*****@*****.**'
        self.user.set_password('secret!')
        self.user.save()

        self.device = get_device(self.user, 'dev', '')
Ejemplo n.º 19
0
Archivo: user.py Proyecto: fk-lx/mygpo
def user_by_google_email(email):
    """ Get a user by its connected Google account """

    from mygpo.users.models import User
    users = User.view('users/by_google_email',
            key          = email,
            include_docs = True,
        )

    if not users:
        return None

    return users.one()
Ejemplo n.º 20
0
def for_user(request, username):
    user = User.get_user(username)
    if not user:
        raise Http404

    subscriptions = user.get_subscribed_podcasts(public=True)
    token = user.get_token('subscriptions_token')

    return render(request, 'user_subscriptions.html', {
        'subscriptions': subscriptions,
        'other_user': user,
        'token': token,
        })
Ejemplo n.º 21
0
    def handle(self, *args, **options):

        max_suggestions = options.get('max')

        if options.get('username'):
            users = [User.get_user(options.get('username'))]

        else:
            users = User.all_users()
            users = filter(lambda u: u.is_active, users)

            if options.get('outdated'):
                users = filter(lambda u: not u.suggestions_up_to_date, users)

        if options.get('max_users'):
            users = users[:int(options.get('max_users'))]

        total = len(users)

        for n, user in enumerate(users):
            suggestion = Suggestions.for_user(user)

            subscribed_podcasts = list(set(user.get_subscribed_podcasts()))
            subscribed_podcasts = filter(None, subscribed_podcasts)

            subscribed_podcasts = filter(None, subscribed_podcasts)
            related = chain.from_iterable([p.related_podcasts for p in subscribed_podcasts])
            related = filter(lambda pid: not pid in suggestion.blacklist, related)

            counter = Counter(related)
            get_podcast_id = itemgetter(0)
            suggested = map(get_podcast_id, counter.most_common(max_suggestions))
            suggestion.podcasts = suggested

            suggestion.save()

            _update_user(user=user)

            progress(n+1, total)
Ejemplo n.º 22
0
Archivo: tests.py Proyecto: Mic92/mygpo
class MergeTests(TestCase):

    def setUp(self):
        self.podcast1 = Podcast(urls=['http://example.com/feed.rss'])
        self.podcast2 = Podcast(urls=['http://test.org/podcast/'])
        self.podcast1.save()
        self.podcast2.save()

        self.episode1 = Episode(podcast=self.podcast1.get_id(),
                urls = ['http://example.com/episode1.mp3'])
        self.episode2 = Episode(podcast=self.podcast2.get_id(),
                urls = ['http://example.com/episode1.mp3'])

        self.episode1.save()
        self.episode2.save()

        self.user = User(username='******')
        self.user.email = '*****@*****.**'
        self.user.set_password('secret!')
        self.user.save()


    def test_merge_podcasts(self):

        state1 = self.episode1.get_user_state(self.user)
        state2 = self.episode2.get_user_state(self.user)

        action1 = EpisodeAction(action='play', timestamp=datetime.utcnow())
        action2 = EpisodeAction(action='download', timestamp=datetime.utcnow())

        state1.add_actions([action1])
        state2.add_actions([action2])

        state1.save()
        state2.save()

        pm = PodcastMerger([self.podcast1, self.podcast2])
        pm.merge()

        state1 = self.episode1.get_user_state(self.user)
        state2 = self.episode2.get_user_state(self.user)

        self.assertIn(action1, state1.actions)
        self.assertIn(action2, state1.actions)



    def tearDown(self):
        self.podcast1.delete()
        self.episode1.delete()

        try:
            self.podcast2.delete()
            self.episode2.delete()
        except:
            pass

        self.user.delete()
Ejemplo n.º 23
0
Archivo: tests.py Proyecto: fk-lx/mygpo
class DeviceSyncTests(unittest.TestCase):

    def setUp(self):
        self.user = User(username='******')
        self.user.email = '*****@*****.**'
        self.user.set_password('secret!')
        self.user.save()


    def test_group(self):
        dev1 = Device(uid='d1')
        self.user.devices.append(dev1)

        dev2 = Device(uid='d2')
        self.user.devices.append(dev2)

        group = self.user.get_grouped_devices().next()
        self.assertEquals(group.is_synced, False)
        self.assertIn(dev1, group.devices)
        self.assertIn(dev2, group.devices)


        dev3 = Device(uid='d3')
        self.user.devices.append(dev3)

        self.user.sync_devices(dev1, dev3)

        groups = self.user.get_grouped_devices()
        g1 = groups.next()

        self.assertEquals(g1.is_synced, True)
        self.assertIn(dev1, g1.devices)
        self.assertIn(dev3, g1.devices)

        g2 = groups.next()
        self.assertEquals(g2.is_synced, False)
        self.assertIn(dev2, g2.devices)


        targets = self.user.get_sync_targets(dev1)
        target = targets.next()
        self.assertEquals(target, dev2)
Ejemplo n.º 24
0
def auth(emailaddr, password):
    if emailaddr is None or password is None:
        return None

    user = User.get_user_by_email(emailaddr)
    if not user:
        return None

    if not user.check_password(password):
        return None

    if not user.is_active:
        return None

    return user
Ejemplo n.º 25
0
Archivo: views.py Proyecto: Mic92/mygpo
        def _decorator(request, username, listname, *args, **kwargs):

            user = User.get_user(username)
            if not user:
                raise Http404

            if must_own and request.user != user:
                return HttpResponseForbidden()

            plist = PodcastList.for_user_slug(user._id, listname)

            if plist is None:
                raise Http404

            return f(request, plist, user, *args, **kwargs)
Ejemplo n.º 26
0
Archivo: views.py Proyecto: Mic92/mygpo
def favorite_feed(request, username):

    site = RequestSite(request)

    user = User.get_user(username)
    if not user:
        raise Http404

    feed = FavoriteFeed(user)

    return render(request, 'userfeed.xml', {
        'site': site,
        'feed_user': user,
        'feed': feed,
        }, content_type='text/xml')
Ejemplo n.º 27
0
Archivo: lists.py Proyecto: Mic92/mygpo
def get_lists(request, username):
    """ Returns a list of all podcast lists by the given user """

    user = User.get_user(username)
    if not user:
        raise Http404

    lists = PodcastList.for_user(user._id)

    site = RequestSite(request)

    get_data = partial(_get_list_data, username=user.username,
                domain=site.domain)
    lists_data = map(get_data, lists)

    return JsonResponse(lists_data)
Ejemplo n.º 28
0
def for_user_opml(request, username):
    user = User.get_user(username)
    if not user:
        raise Http404

    subscriptions = user.get_subscribed_podcasts(public=True)

    if parse_bool(request.GET.get('symbian', False)):
        subscriptions = map(symbian_opml_changes, subscriptions)

    response = render(request, 'user_subscriptions.opml', {
        'subscriptions': subscriptions,
        'other_user': user
        })
    response['Content-Disposition'] = 'attachment; filename=%s-subscriptions.opml' % username
    return response
Ejemplo n.º 29
0
    def handle(self, *args, **options):

        if len(args) < 2:
            print >>sys.stderr, "Usage: ./manage.py make-publisher <username> <podcast-url-1> [<podcast-url-2> ...]"
            return

        username = args[0]

        user = User.get_user(username)
        if not user:
            print >>sys.stderr, "User %s does not exist" % username
            return

        urls = args[1:]
        podcasts = map(podcast_for_url, urls)
        ids = map(Podcast.get_id, podcasts)
        add_published_objs(user, ids)
Ejemplo n.º 30
0
    def handle(self, *args, **options):

        docs = set()

        for username in options.get('users', []):
            user = User.get_user(username)

            # User
            docs.add(user._id)

            # Suggestions
            suggestions = Suggestions.for_user(user)
            docs.add(suggestions._id)

            # Podcast States
            for p_state in PodcastUserState.for_user(user):
                docs.add(p_state._id)

                # Categories
                for tag in p_state.tags:
                    c = Category.for_tag(tag)
                    if c: docs.add(c._id)

                # Podcast
                podcast = Podcast.get(p_state.podcast)
                docs.add(podcast._id)

                # Categories
                for s in podcast.tags:
                    for tag in podcast.tags[s]:
                        c = Category.for_tag(tag)
                        if c: docs.add(c._id)

                # Episodes
                for episode in podcast.get_episodes():
                    docs.add(episode._id)

                    # Episode States
                    e_state = episode.get_user_state(user)
                    if e_state._id:
                        docs.add(e_state._id)


        db = get_main_database()
        docs = sorted(docs)
        self.dump(docs, db)