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'))
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
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)
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))
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)
def deleted_users(): from mygpo.users.models import User users = User.view('users/deleted', include_docs = True, reduce = False, ) return list(users)
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()
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 } ]
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')
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
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
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)
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})
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))
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
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, })
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
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', '')
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()
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, })
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)
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()
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)
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
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)
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')
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)
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
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)
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)