Beispiel #1
0
def follow_handler(sender, **kwargs):
    rel = kwargs.get('instance', None)
    created = kwargs.get('created', False)
    if not created or not isinstance(rel, Relationship) or rel.deleted:
        return
    activity = Activity(actor=rel.source,
                        verb=verbs['follow'],
                        target_object=rel)
    recipients = []
    if rel.target_user:
        recipients.append(rel.target_user)
    else:
        activity.scope_object = rel.target_project
        for organizer in rel.target_project.organizers():
            if organizer.user != rel.source:
                recipients.append(organizer.user)
    activity.save()
    subject_template = 'relationships/emails/new_follower_subject.txt'
    body_template = 'relationships/emails/new_follower.txt'
    context = {
        'user': rel.source,
        'project': rel.target_project,
        'domain': Site.objects.get_current().domain
    }
    send_notifications_i18n(recipients,
                            subject_template,
                            body_template,
                            context,
                            notification_category='new-follower')
Beispiel #2
0
def follow_handler(sender, **kwargs):
    rel = kwargs.get('instance', None)
    created = kwargs.get('created', False)
    if not created or not isinstance(rel, Relationship) or rel.deleted:
        return
    activity = Activity(actor=rel.source,
                        verb=verbs['follow'],
                        target_object=rel)
    recipients = []
    if rel.target_user:
        recipients.append(rel.target_user)
    else:
        activity.scope_object = rel.target_project
        for organizer in rel.target_project.organizers():
            if organizer.user != rel.source:
                recipients.append(organizer.user)
    activity.save()
    subject_template = 'relationships/emails/new_follower_subject.txt'
    body_template = 'relationships/emails/new_follower.txt'
    context = {
        'user': rel.source,
        'project': rel.target_project,
        'domain': Site.objects.get_current().domain
    }
    send_notifications_i18n(recipients, subject_template, body_template,
        context, notification_category='new-follower'
    )
Beispiel #3
0
def follow_handler(sender, **kwargs):
    rel = kwargs.get("instance", None)
    if not isinstance(rel, Relationship):
        return
    user_subject = _("%(name)s is following you on Drumbeat!" % {"name": rel.source.name})
    project_subject = _("%(name)s is following your project on Drumbeat!" % {"name": rel.source.name})
    activity = Activity(actor=rel.source, verb="http://activitystrea.ms/schema/1.0/follow")
    subject = _(u"%(name)s is now following")
    if rel.target_user:
        activity.target_user = rel.target_user
        user = rel.target_user
        pref_key = "no_email_new_follower"
        subject = user_subject
    else:
        activity.project = rel.target_project
        user = rel.target_project.created_by
        pref_key = "no_email_new_project_follower"
        subject = project_subject
    activity.save()

    preferences = AccountPreferences.objects.filter(user=user)
    for pref in preferences:
        if pref.value and pref.key == pref_key:
            return

    body = render_to_string(
        "relationships/emails/new_follower.txt", {"user": rel.source, "project": rel.target_project}
    )
    SendUserEmail.apply_async((user, subject, body))
Beispiel #4
0
 def create_activity_entry(self, entry, sender, activity_prefix=None):
     """Create activity feed entries for the provided feed entry."""
     object_type = None
     if activity_prefix:
         object_type = self.get_namespaced_attr(entry, activity_prefix,
                                                'object-type')
     if not object_type:
         object_type = object_types['article']
     title = getattr(entry, 'title', None)
     uri = getattr(entry, 'link', None)
     if not title:
         title = entry.get('title')
     if not uri:
         uris = entry.get('links')
         if uris:
             uri = uris[0].get('href')
     if not (title and uri):
         return
     for link in sender.link_set.all():
         remote_obj = RemoteObject(link=link,
                                   title=title,
                                   uri=uri,
                                   object_type=object_type)
         remote_obj.save()
         activity = Activity(actor=link.user,
                             verb=verbs['share'],
                             target_object=remote_obj)
         if link.project:
             activity.scope_object = link.project
         activity.save()
Beispiel #5
0
def clone(request):
    user = request.user.get_profile()
    if request.method == "POST":
        form = project_forms.CloneProjectForm(request.POST)
        if form.is_valid():
            base_project = form.cleaned_data["project"]
            project = Project(
                name=base_project.name,
                category=base_project.category,
                other=base_project.other,
                other_description=base_project.other_description,
                short_description=base_project.short_description,
                long_description=base_project.long_description,
                clone_of=base_project,
            )
            project.save()
            act = Activity(actor=user, verb=verbs["post"], scope_object=project, target_object=project)
            act.save()
            participation = Participation(project=project, user=user, organizing=True)
            participation.save()
            new_rel, created = Relationship.objects.get_or_create(source=user, target_project=project)
            new_rel.deleted = False
            new_rel.save()
            detailed_description = Page(
                title=_("Full Description"),
                slug="full-description",
                content=base_project.detailed_description.content,
                listed=False,
                author_id=user.id,
                project_id=project.id,
            )
            detailed_description.save()
            project.detailed_description_id = detailed_description.id
            base_sign_up = base_project.sign_up.get()
            sign_up = Signup(
                public=base_sign_up.public,
                between_participants=base_sign_up.between_participants,
                author_id=user.id,
                project_id=project.id,
            )
            sign_up.save()
            project.save()
            tasks = Page.objects.filter(project=base_project, listed=True, deleted=False).order_by("index")
            for task in tasks:
                new_task = Page(title=task.title, content=task.content, author=user, project=project)
                new_task.save()
            links = Link.objects.filter(project=base_project).order_by("index")
            for link in links:
                new_link = Link(name=link.name, url=link.url, user=user, project=project)
                new_link.save()
            project.create()
            messages.success(request, _("The %s has been cloned.") % project.kind.lower())
            return http.HttpResponseRedirect(reverse("projects_show", kwargs={"slug": project.slug}))
        else:
            messages.error(request, _("There was a problem cloning the study group, course, ..."))
    else:
        form = project_forms.CloneProjectForm()
    return render_to_response(
        "projects/project_clone.html", {"form": form, "clone_tab": True}, context_instance=RequestContext(request)
    )
Beispiel #6
0
def clone(request):
    user = request.user.get_profile()
    if request.method == 'POST':
        form = project_forms.CloneProjectForm(request.POST)
        if form.is_valid():
            base_project = form.cleaned_data['project']
            project = Project(name=base_project.name, kind=base_project.kind,
                short_description=base_project.short_description,
                long_description=base_project.long_description,
                clone_of=base_project)
            project.save()
            act = Activity(actor=user,
                verb=verbs['post'],
                scope_object=project,
                target_object=project)
            act.save()
            participation = Participation(project=project, user=user,
                organizing=True)
            participation.save()
            new_rel, created = Relationship.objects.get_or_create(source=user,
                target_project=project)
            new_rel.deleted = False
            new_rel.save()
            detailed_description = Page(title=_('Full Description'),
                slug='full-description',
                content=base_project.detailed_description.content,
                listed=False, author_id=user.id, project_id=project.id)
            detailed_description.save()
            project.detailed_description_id = detailed_description.id
            sign_up = Page(title=_('Sign-Up'), slug='sign-up',
                content=base_project.sign_up.content, listed=False,
                editable=False, author_id=user.id, project_id=project.id)
            sign_up.save()
            project.sign_up_id = sign_up.id
            project.save()
            tasks = Page.objects.filter(project=base_project, listed=True,
                deleted=False).order_by('index')
            for task in tasks:
                new_task = Page(title=task.title, content=task.content,
                    author=user, project=project)
                new_task.save()
            links = Link.objects.filter(project=base_project).order_by('index')
            for link in links:
                new_link = Link(name=link.name, url=link.url, user=user,
                    project=project)
                new_link.save()
            project.create()
            messages.success(request,
                _('The %s has been cloned.') % project.kind.lower())
            return http.HttpResponseRedirect(reverse('projects_show', kwargs={
                'slug': project.slug,
            }))
        else:
            messages.error(request,
                _("There was a problem cloning the study group, course, ..."))
    else:
        form = project_forms.CloneProjectForm()
    return render_to_response('projects/project_clone.html', {
        'form': form, 'clone_tab': True,
    }, context_instance=RequestContext(request))
Beispiel #7
0
def status_creation_handler(sender, **kwargs):
    status = kwargs.get('instance', None)
    created = kwargs.get('created', False)

    if not created or not isinstance(status, Status):
        return

    # clean html
    status.status = bleach.clean(status.status, tags=settings.REDUCED_ALLOWED_TAGS, attributes=settings.REDUCED_ALLOWED_ATTRIBUTES, strip=True)
    status.save()

    # fire activity
    activity = Activity(
        actor=status.author,
        verb='http://activitystrea.ms/schema/1.0/post',
        status=status,
    )
    if status.project:
        activity.target_project = status.project
    if status.in_reply_to:
        activity.parent = status.in_reply_to
    activity.save()
    # Send notifications.
    if status.project:
        status.send_wall_notification()
Beispiel #8
0
 def setUp(self):
     self.activities_data = []
     self.activities = []
     self.students_data = []
     self.students = []
     # 生成三个活动
     for i in range(0, 3):
         activity_data = get_activity_data()
         activity = Activity(**activity_data)
         activity.save()
         self.activities_data.append(activity_data)
         self.activities.append(activity)
     # 生成8个学生
     company_data = get_company_data()
     company = Company(**company_data)
     company.save()
     for i in range(0, 8):
         # make pylint happy
         if i == -1:
             pass
         student_data = get_student_data()
         student = Student(company=company, **student_data)
         student.save()
         self.students_data.append(student_data)
         self.students.append(student)
Beispiel #9
0
 def create_activity_entry(self, entry, sender, activity_prefix=None):
     """Create activity feed entries for the provided feed entry."""
     object_type = None
     if activity_prefix:
         object_type = self.get_namespaced_attr(
             entry, activity_prefix, 'object-type')
     if not object_type:
         object_type = object_types['article']
     title = getattr(entry, 'title', None)
     uri = getattr(entry, 'link', None)
     if not title:
         title = entry.get('title')
     if not uri:
         uris = entry.get('links')
         if uris:
             uri = uris[0].get('href')
     if not (title and uri):
         return
     for link in sender.link_set.all():
         remote_obj = RemoteObject(
             link=link, title=title, uri=uri, object_type=object_type)
         remote_obj.save()
         activity = Activity(
             actor=link.user, verb=verbs['share'], target_object=remote_obj)
         if link.project:
             activity.scope_object = link.project
         activity.save()
Beispiel #10
0
def follow_handler(sender, **kwargs):
    rel = kwargs.get("instance", None)
    created = kwargs.get("created", False)
    if not created or not isinstance(rel, Relationship) or rel.deleted:
        return
    activity = Activity(actor=rel.source, verb=verbs["follow"], target_object=rel)
    recipients = []
    if rel.target_user:
        preferences = AccountPreferences.objects.filter(user=rel.target_user, key="no_email_new_follower")
        for pref in preferences:
            if pref.value:
                break
        else:
            recipients.append(rel.target_user)
    else:
        activity.scope_object = rel.target_project
        for organizer in rel.target_project.organizers():
            if organizer.user != rel.source:
                preferences = AccountPreferences.objects.filter(
                    user=organizer.user, key="no_email_new_project_follower"
                )
                for pref in preferences:
                    if pref.value:
                        break
                else:
                    recipients.append(organizer.user)
    activity.save()
    subject_template = "relationships/emails/new_follower_subject.txt"
    body_template = "relationships/emails/new_follower.txt"
    context = {"user": rel.source, "project": rel.target_project, "domain": Site.objects.get_current().domain}
    send_notifications_i18n(recipients, subject_template, body_template, context)
Beispiel #11
0
 def create_activity_entry(self, entry, sender, activity_prefix=None):
     """Create activity feed entries for the provided feed entry."""
     verb, object_type = None, None
     if activity_prefix:
         verb = self.get_namespaced_attr(
             entry, activity_prefix, 'verb')
         object_type = self.get_namespaced_attr(
             entry, activity_prefix, 'object-type')
     if not verb:
         verb = 'http://activitystrea.ms/schema/1.0/post'
     if not object_type:
         object_type = 'http://activitystrea.ms/schema/1.0/article'
     title = getattr(entry, 'title', None)
     uri = getattr(entry, 'link', None)
     if not (title and uri):
         return
     for link in sender.link_set.all():
         remote_obj = RemoteObject(
             link=link, title=title, uri=uri, object_type=object_type)
         remote_obj.save()
         activity = Activity(
             actor=link.user, verb=verb, remote_object=remote_obj)
         if link.project:
             activity.target_project = link.project
         activity.save()
    def test_can_crate_activity_with_complete_set_of_data(self):
        """
        tests if activity can have sections containing exercises and sets 
        """
        start_date = time = timezone.now()
        activity_type = Activity.STRENGTH
        name = 'Test Training'
        new_activity = Activity(
            start_date=start_date,
            activity_type=activity_type,
            name=name,
            posted_by=self.user1,
        )
        new_activity.save()

        section_data = StrengthSections(section_name='MAIN',
                                        activity=new_activity)

        section_data.save()

        exercise = Exercise(exercise_name="PUSH UP", section=section_data)

        exercise.save()

        ex_set = ExerciseSet(exercise=exercise,
                             weights=10,
                             reps=10,
                             notes='Notes')
        ex_set.save()

        self.assertEqual(new_activity.get_sections().count(), 1)
        self.assertEqual(section_data.get_exercises().count(), 1)
        self.assertEqual(exercise.get_sets().count(), 1)
        self.assertEqual(ex_set.exercise.pk, exercise.pk)
Beispiel #13
0
def save_profile(backend, user, response, *args, **kwargs):

    if backend.name == 'facebook':

        try:
            customer = user.get_customer()
        except:
            customer = None
        if customer is None:
            user.is_customer = True
            user.save()
            customer = Customer(user_id=user.id)
            try:
                customer.birthday = datetime.datetime.strptime(
                    response['birthday'], '%m/%d/%Y').strftime('%Y-%m-%d')
            except:
                pass
            try:
                url = "http://graph.facebook.com/%s/picture?type=large" \
                    % response["id"]
                if url:
                    from urllib.request import urlopen, HTTPError
                    from django.template.defaultfilters import slugify
                    from django.core.files.base import ContentFile
                    avatar = urlopen(url)
                    customer.profile_picture.save(
                        slugify(user.username + " social") + '.jpg',
                        ContentFile(avatar.read()))
            except HTTPError:
                pass
            customer.save()
            Activity.push(user, 201,
                          user.username + ' is register with facebook')
        Activity.push(user, 101,
                      user.username + ' log in as customer with facebook.')
Beispiel #14
0
def import_from_old_site(request):
    user = request.user.get_profile()
    if request.method == 'POST':
        form = project_forms.ImportProjectForm(request.POST)
        if form.is_valid():
            course = form.cleaned_data['course']
            #CS - too much logic in view
            project = Project(name=course['name'], kind=course['kind'],
                short_description=course['short_description'],
                long_description=course['long_description'],
                imported_from=course['slug'])
            project.save()
            act = Activity(actor=user,
                verb=verbs['post'],
                scope_object=project,
                target_object=project)
            act.save()
            participation = Participation(project=project, user=user,
                organizing=True)
            participation.save()
            new_rel, created = Relationship.objects.get_or_create(source=user,
                target_project=project)
            new_rel.deleted = False
            new_rel.save()
            if course['detailed_description']:
                detailed_description_content = course['detailed_description']
            else:
                detailed_description_content = render_to_string(
                    "projects/detailed_description_initial_content.html",
                    {'project': project})
            detailed_description = Page(title=_('Full Description'),
                slug='full-description', content=detailed_description_content,
                listed=False, author_id=user.id, project_id=project.id)
            detailed_description.save()
            project.detailed_description_id = detailed_description.id
            sign_up = Signup(between_participants=course['sign_up'],
                author_id=user.id, project_id=project.id)
            sign_up.save()
            project.save()
            for title, content in course['tasks']:
                new_task = Page(title=title, content=content, author=user,
                    project=project)
                new_task.save()
            for name, url in course['links']:
                new_link = Link(name=name, url=url, user=user, project=project)
                new_link.save()
            project.create()
            messages.success(request,
                _('The %s has been imported.') % project.kind.lower())
            return http.HttpResponseRedirect(reverse('projects_show', kwargs={
                'slug': project.slug,
            }))
        else:
            msg = _("Problem importing the study group, course, ...")
            messages.error(request, msg)
    else:
        form = project_forms.ImportProjectForm()
    return render_to_response('projects/project_import.html', {
        'form': form, 'import_tab': True},
        context_instance=RequestContext(request))
Beispiel #15
0
def fire_activity(sender, **kwargs):
    instance = kwargs.get('instance', None)
    created = kwargs.get('created', False)
    
    is_page = isinstance(instance, Page)
    is_comment = isinstance(instance, PageComment)
    if created and (is_page or is_comment):
        # Send notification.
        if is_comment and instance.page.slug == 'sign-up':
            instance.send_sign_up_notification()
            return
        else:
            send_content_notification(instance, is_comment)
        # Fire activity.
        activity = Activity(
            actor=instance.author,
            verb='http://activitystrea.ms/schema/1.0/post',
            target_object=instance,
        )
        activity.target_project = instance.project
        activity.save()
    elif not created and is_page and instance.publish:
        if instance.deleted:
            verb = 'http://activitystrea.ms/schema/1.0/delete'
        else:
            verb = 'http://activitystrea.ms/schema/1.0/update'
        activity = Activity(
            actor=instance.author,
            verb=verb,
            target_object=instance,
        )
        activity.target_project = instance.project
        activity.save()
Beispiel #16
0
def status_creation_handler(sender, **kwargs):
    status = kwargs.get('instance', None)
    created = kwargs.get('created', False)

    if not created or not isinstance(status, Status):
        return

    # convert status body to markdown and bleachify
    bl = Bleach()
    status.status = urlize(status.status)
    status.status = bl.clean(markdown(status.status), tags=TAGS)
    status.save()

    # fire activity
    activity = Activity(
        actor=status.author,
        verb='http://activitystrea.ms/schema/1.0/post',
        status=status,
    )
    if status.project:
        activity.target_project = status.project
    activity.save()
    # Send notifications.
    if activity.target_project:
        activity.target_project.send_update_notification(activity)
Beispiel #17
0
def import_from_old_site(request):
    user = request.user.get_profile()
    if request.method == 'POST':
        form = project_forms.ImportProjectForm(request.POST)
        if form.is_valid():
            course = form.cleaned_data['course']
            #CS - too much logic in view
            project = Project(name=course['name'], kind=course['kind'],
                short_description=course['short_description'],
                long_description=course['long_description'],
                imported_from=course['slug'])
            project.save()
            act = Activity(actor=user,
                verb=verbs['post'],
                scope_object=project,
                target_object=project)
            act.save()
            participation = Participation(project=project, user=user,
                organizing=True)
            participation.save()
            new_rel, created = Relationship.objects.get_or_create(source=user,
                target_project=project)
            new_rel.deleted = False
            new_rel.save()
            if course['detailed_description']:
                detailed_description_content = course['detailed_description']
            else:
                detailed_description_content = render_to_string(
                    "projects/detailed_description_initial_content.html",
                    {'project': project})
            detailed_description = Page(title=_('Full Description'),
                slug='full-description', content=detailed_description_content,
                listed=False, author_id=user.id, project_id=project.id)
            detailed_description.save()
            project.detailed_description_id = detailed_description.id
            sign_up = Signup(between_participants=course['sign_up'],
                author_id=user.id, project_id=project.id)
            sign_up.save()
            project.save()
            for title, content in course['tasks']:
                new_task = Page(title=title, content=content, author=user,
                    project=project)
                new_task.save()
            for name, url in course['links']:
                new_link = Link(name=name, url=url, user=user, project=project)
                new_link.save()
            project.create()
            messages.success(request,
                _('The %s has been imported.') % project.kind.lower())
            return http.HttpResponseRedirect(reverse('projects_show', kwargs={
                'slug': project.slug,
            }))
        else:
            msg = _("Problem importing the study group, course, ...")
            messages.error(request, msg)
    else:
        form = project_forms.ImportProjectForm()
    return render_to_response('projects/project_import.html', {
        'form': form, 'import_tab': True},
        context_instance=RequestContext(request))
Beispiel #18
0
 def create_activity_entry(self, entry, sender, activity_prefix=None):
     """Create activity feed entries for the provided feed entry."""
     verb, object_type = None, None
     if activity_prefix:
         verb = self.get_namespaced_attr(entry, activity_prefix, 'verb')
         object_type = self.get_namespaced_attr(entry, activity_prefix,
                                                'object-type')
     if not verb:
         verb = 'http://activitystrea.ms/schema/1.0/post'
     if not object_type:
         object_type = 'http://activitystrea.ms/schema/1.0/article'
     title = getattr(entry, 'title', None)
     uri = getattr(entry, 'link', None)
     if not (title and uri):
         self.log.warn("Received pubsub update with no title or uri")
         return
     for link in sender.link_set.all():
         self.log.info("Creating activity entry for link: %d" % (link.id, ))
         remote_obj = RemoteObject(link=link,
                                   title=title,
                                   uri=uri,
                                   object_type=object_type)
         remote_obj.save()
         activity = Activity(actor=link.user,
                             verb=verb,
                             remote_object=remote_obj)
         if link.project:
             activity.target_project = link.project
         activity.save()
Beispiel #19
0
 def create_activity_entry(self, entry, sender, activity_prefix=None):
     """Create activity feed entries for the provided feed entry."""
     verb, object_type = None, None
     if activity_prefix:
         verb = self.get_namespaced_attr(
             entry, activity_prefix, 'verb')
         object_type = self.get_namespaced_attr(
             entry, activity_prefix, 'object-type')
     if not verb:
         verb = 'http://activitystrea.ms/schema/1.0/post'
     if not object_type:
         object_type = 'http://activitystrea.ms/schema/1.0/article'
     title = getattr(entry, 'title', None)
     uri = getattr(entry, 'link', None)
     if not title:
         title = entry.get('title')
     if not uri:
         uris = entry.get('links')
         if uris:
             uri = uris[0].get('href')
     if not (title and uri):
         return
     for link in sender.link_set.all():
         remote_obj = RemoteObject(
             link=link, title=title, uri=uri, object_type=object_type)
         remote_obj.save()
         activity = Activity(
             actor=link.user, verb=verb, remote_object=remote_obj)
         if link.project:
             activity.target_project = link.project
         activity.save()
Beispiel #20
0
 def create(self, validated_data):
     user_data = validated_data.pop('user')
     user = User.objects.create_user(**user_data)
     user.is_customer = True
     user.save()
     Activity.push(user, 200, user.username + ' is register.')
     customer = Customer.objects.create(user=user, **validated_data)
     return Response(status=status.HTTP_200_OK)
Beispiel #21
0
def create(request):
    user = request.user.get_profile()
    if request.method == 'POST':
        form = project_forms.CreateProjectForm(request.POST)
        if form.is_valid():
            project = form.save()
            act = Activity(actor=user,
                           verb=verbs['post'],
                           scope_object=project,
                           target_object=project)
            act.save()
            participation = Participation(project=project,
                                          user=user,
                                          organizing=True)
            participation.save()
            new_rel, created = Relationship.objects.get_or_create(
                source=user, target_project=project)
            new_rel.deleted = False
            new_rel.save()
            detailed_description_content = render_to_string(
                "projects/detailed_description_initial_content.html", {})
            detailed_description = Page(title=_('Full Description'),
                                        slug='full-description',
                                        content=detailed_description_content,
                                        listed=False,
                                        author_id=user.id,
                                        project_id=project.id)
            detailed_description.save()
            project.detailed_description_id = detailed_description.id
            sign_up_content = render_to_string(
                "projects/sign_up_initial_content.html", {})
            sign_up = Page(title=_('Sign-Up'),
                           slug='sign-up',
                           content=sign_up_content,
                           listed=False,
                           editable=False,
                           author_id=user.id,
                           project_id=project.id)
            sign_up.save()
            project.sign_up_id = sign_up.id
            project.create()
            messages.success(
                request,
                _('The %s has been created.') % project.kind.lower())
            return http.HttpResponseRedirect(
                reverse('projects_show', kwargs={
                    'slug': project.slug,
                }))
        else:
            msg = _("Problem creating the study group, course, ...")
            messages.error(request, msg)
    else:
        form = project_forms.CreateProjectForm()
    return render_to_response('projects/project_edit_summary.html', {
        'form': form,
        'new_tab': True,
    },
                              context_instance=RequestContext(request))
Beispiel #22
0
def create(request, category=None):
    user = request.user.get_profile()
    if request.method == 'POST':
        form = project_forms.ProjectForm(category, request.POST)
        image_form = None
        if form.is_valid():
            project = form.save()
            if category:
                project.category = category
            image_form = project_forms.ProjectImageForm(request.POST,
                request.FILES, instance=project)
            if image_form.is_valid():
                image_form.save()
            project.set_duration(form.cleaned_data['duration'] or 0)
            #CS - too much logic in view
            act = Activity(actor=user,
                verb=verbs['post'],
                scope_object=project,
                target_object=project)
            act.save()
            participation = Participation(project=project, user=user,
                organizing=True)
            participation.save()
            new_rel, created = Relationship.objects.get_or_create(source=user,
                target_project=project)
            new_rel.deleted = False
            new_rel.save()
            detailed_description_content = render_to_string(
                "projects/detailed_description_initial_content.html",
                {'project': project})
            detailed_description = Page(title=_('Full Description'),
                slug='full-description', content=detailed_description_content,
                listed=False, author_id=user.id, project_id=project.id)
            if project.category != Project.STUDY_GROUP:
                detailed_description.collaborative = False
            detailed_description.save()
            project.detailed_description_id = detailed_description.id
            sign_up = Signup(author_id=user.id, project_id=project.id)
            sign_up.save()
            project.create()
            messages.success(request,
                _('The %s has been created.') % project.kind.lower())
            return http.HttpResponseRedirect(reverse('projects_create_tasks',
                kwargs={'slug': project.slug,}))
        else:
            msg = _("Problem creating the course")
            messages.error(request, msg)
    else:
        form = project_forms.ProjectForm(category, initial={'test':True})
        image_form = project_forms.ProjectImageForm()
    context = {
        'form': form,
        'image_form': image_form,
        'category': category,
        'is_challenge': (category == Project.CHALLENGE),
    }
    return render_to_response('projects/project_create_overview.html',
        context, context_instance=RequestContext(request))
Beispiel #23
0
def create(request, category=None):
    user = request.user.get_profile()
    if request.method == 'POST':
        form = project_forms.ProjectForm(category, request.POST)
        image_form = None
        if form.is_valid():
            project = form.save()
            if category:
                project.category = category
            image_form = project_forms.ProjectImageForm(request.POST,
                request.FILES, instance=project)
            if image_form.is_valid():
                image_form.save()
            project.set_duration(form.cleaned_data['duration'] or 0)
            #CS - too much logic in view
            act = Activity(actor=user,
                verb=verbs['post'],
                scope_object=project,
                target_object=project)
            act.save()
            participation = Participation(project=project, user=user,
                organizing=True)
            participation.save()
            new_rel, created = Relationship.objects.get_or_create(source=user,
                target_project=project)
            new_rel.deleted = False
            new_rel.save()
            detailed_description_content = render_to_string(
                "projects/detailed_description_initial_content.html",
                {'project': project})
            detailed_description = Page(title=_('Full Description'),
                slug='full-description', content=detailed_description_content,
                listed=False, author_id=user.id, project_id=project.id)
            if project.category != Project.STUDY_GROUP:
                detailed_description.collaborative = False
            detailed_description.save()
            project.detailed_description_id = detailed_description.id
            sign_up = Signup(author_id=user.id, project_id=project.id)
            sign_up.save()
            project.create()
            messages.success(request,
                _('The %s has been created.') % project.kind.lower())
            return http.HttpResponseRedirect(reverse('projects_create_tasks',
                kwargs={'slug': project.slug,}))
        else:
            msg = _("Problem creating the course")
            messages.error(request, msg)
    else:
        form = project_forms.ProjectForm(category, initial={'test':True})
        image_form = project_forms.ProjectImageForm()
    context = {
        'form': form,
        'image_form': image_form,
        'category': category,
        'is_challenge': (category == Project.CHALLENGE),
    }
    return render_to_response('projects/project_create_overview.html',
        context, context_instance=RequestContext(request))
Beispiel #24
0
def import_from_old_site(request):
    user = request.user.get_profile()
    if request.method == "POST":
        form = project_forms.ImportProjectForm(request.POST)
        if form.is_valid():
            course = form.cleaned_data["course"]
            project = Project(
                name=course["name"],
                kind=course["kind"],
                short_description=course["short_description"],
                long_description=course["long_description"],
                imported_from=course["slug"],
            )
            project.save()
            act = Activity(actor=user, verb=verbs["post"], scope_object=project, target_object=project)
            act.save()
            participation = Participation(project=project, user=user, organizing=True)
            participation.save()
            new_rel, created = Relationship.objects.get_or_create(source=user, target_project=project)
            new_rel.deleted = False
            new_rel.save()
            if course["detailed_description"]:
                detailed_description_content = course["detailed_description"]
            else:
                detailed_description_content = render_to_string(
                    "projects/detailed_description_initial_content.html", {}
                )
            detailed_description = Page(
                title=_("Full Description"),
                slug="full-description",
                content=detailed_description_content,
                listed=False,
                author_id=user.id,
                project_id=project.id,
            )
            detailed_description.save()
            project.detailed_description_id = detailed_description.id
            sign_up = Signup(between_participants=course["sign_up"], author_id=user.id, project_id=project.id)
            sign_up.save()
            project.save()
            for title, content in course["tasks"]:
                new_task = Page(title=title, content=content, author=user, project=project)
                new_task.save()
            for name, url in course["links"]:
                new_link = Link(name=name, url=url, user=user, project=project)
                new_link.save()
            project.create()
            messages.success(request, _("The %s has been imported.") % project.kind.lower())
            return http.HttpResponseRedirect(reverse("projects_show", kwargs={"slug": project.slug}))
        else:
            msg = _("Problem importing the study group, course, ...")
            messages.error(request, msg)
    else:
        form = project_forms.ImportProjectForm()
    return render_to_response(
        "projects/project_import.html", {"form": form, "import_tab": True}, context_instance=RequestContext(request)
    )
Beispiel #25
0
def plan(request):
    act = Activity()
    act.participants = selectUser(request.user)
    act.num_participants = 2
    act.save()
    for u in act.participants:
        feed = Feed(user=u, content=act)
        feed.save()
    return HttpResponse("ok")
Beispiel #26
0
def activity_manage(request):
    context = {
        'select': 'activity_manage',
    }
    if request.method == 'GET':
        results = Activity.objects.all()
        context['results'] = results
        return render(request,
                      "activity/activity_manage.html",
                      context=context)
    else:
        if request.POST['type'] == "delete":
            existing_activity = Activity.objects.select_for_update().get(
                id=request.POST['id'])
            existing_activity_records = ActivityRecord.objects.select_for_update(
            ).filter(activity_name=existing_activity.activity_name)
            with transaction.atomic():
                existing_activity.delete()
                existing_activity_records.delete()
        else:
            if request.POST['id'] is not "":
                existing_activity = Activity.objects.select_for_update().get(
                    id=request.POST['id'])
                existing_activity_records = ActivityRecord.objects.select_for_update(
                ).filter(activity_name=existing_activity.activity_name)
                with transaction.atomic():
                    existing_activity.activity_name = request.POST[
                        'activity_name']
                    existing_activity.time_length = request.POST['time_length']
                    existing_activity.max_person = request.POST['max_person']
                    existing_activity.activity_time = request.POST[
                        'activity_time']
                    existing_activity.close_time = request.POST['close_time']
                    existing_activity.person_in_charge = request.POST[
                        'person_in_charge']
                    existing_activity.content = request.POST['content']
                    for record in existing_activity_records:
                        record.activity_name = request.POST['activity_name']
                        record.time_length = request.POST['time_length']
                        record.activity_time = request.POST['activity_time']
                        record.close_time = request.POST['close_time']
                        record.save()
                    existing_activity.save()
            else:
                new_record = Activity(
                    activity_name=request.POST['activity_name'],
                    time_length=request.POST['time_length'],
                    close_time=request.POST['close_time'],
                    activity_time=request.POST['activity_time'],
                    max_person=request.POST['max_person'],
                    content=request.POST['content'],
                    publisher=request.POST['publisher'],
                    person_in_charge=request.POST['person_in_charge'],
                )
                new_record.save()
        return HttpResponse("success")
Beispiel #27
0
def follow_handler(sender, **kwargs):
    rel = kwargs.get('instance', None)
    created = kwargs.get('created', False)
    if not created or not isinstance(rel, Relationship) or rel.deleted:
        return
    activity = Activity(actor=rel.source,
                        verb=verbs['follow'],
                        target_object=rel)
    receipts = []
    ulang = get_language()
    subject = {}
    body = {}
    if rel.target_user:
        for l in settings.SUPPORTED_LANGUAGES:
            activate(l[0])
            subject[l[0]] = ugettext('%(user)s is following you on P2PU!') % {
                'user': rel.source
            }
        preferences = AccountPreferences.objects.filter(user=rel.target_user)
        for pref in preferences:
            if pref.value and pref.key == 'no_email_new_follower':
                break
        else:
            receipts.append(rel.target_user)
    else:
        activity.scope_object = rel.target_project
        for l in settings.SUPPORTED_LANGUAGES:
            activate(l[0])
            msg = ugettext('%(user)s is following %(project)s on P2PU!')
            subject[l[0]] = msg % {
                'user': rel.source,
                'project': rel.target_project
            }
        for organizer in rel.target_project.organizers():
            if organizer.user != rel.source:
                preferences = AccountPreferences.objects.filter(
                    user=organizer.user, key='no_email_new_project_follower')
                for pref in preferences:
                    if pref.value:
                        break
                else:
                    receipts.append(organizer.user)
    activity.save()

    for l in settings.SUPPORTED_LANGUAGES:
        activate(l[0])
        body[l[0]] = render_to_string(
            "relationships/emails/new_follower.txt", {
                'user': rel.source,
                'project': rel.target_project,
                'domain': Site.objects.get_current().domain
            })
    activate(ulang)
    for user in receipts:
        pl = user.preflang or settings.LANGUAGE_CODE
        SendUserEmail.apply_async((user, subject[pl], body[pl]))
Beispiel #28
0
    def ready(self):
        if "runserver" not in sys.argv:
            return

        from activity.models import Activity
        from member.models import Member

        # from paper.models import Paper

        Activity.pull_sheet()
        Member.pull_sheet()
Beispiel #29
0
def create(request):
    user = request.user.get_profile()
    school = None
    if request.method == 'POST':
        form = project_forms.CreateProjectForm(request.POST)
        if form.is_valid():
            project = form.save()
            act = Activity(actor=user,
                verb='http://activitystrea.ms/schema/1.0/post',
                project=project,
                target_project=project)
            act.save()
            participation = Participation(project= project, user=user, organizing=True)
            participation.save()
            new_rel = Relationship(source=user, target_project=project)
            try:
                new_rel.save()
            except IntegrityError:
                pass
            detailed_description_content = render_to_string(
                "projects/detailed_description_initial_content.html",
                {})
            detailed_description = Page(title=_('Full Description'), slug='full-description',
                content=detailed_description_content, listed=False,
                author_id=user.id, project_id=project.id)
            detailed_description.save()
            project.detailed_description_id = detailed_description.id
            sign_up_content = render_to_string("projects/sign_up_initial_content.html",
                {})
            sign_up = Page(title=_('Sign-Up'), slug='sign-up',
                content=sign_up_content, listed=False, editable=False,
                author_id=user.id, project_id=project.id)
            sign_up.save()
            project.sign_up_id = sign_up.id
            project.save()
            messages.success(request, _('The study group has been created.'))
            return http.HttpResponseRedirect(reverse('projects_show', kwargs={
                'slug': project.slug,
            }))
        else:
            messages.error(request,
                _("There was a problem creating the study group."))
    else:
        if 'school' in request.GET:
            try:
                school = School.objects.get(slug=request.GET['school'])
                form = project_forms.CreateProjectForm(initial={'school': school})
            except School.DoesNotExist:
                return http.HttpResponseRedirect(reverse('projects_create'))
        else:
            form = project_forms.CreateProjectForm()
    return render_to_response('projects/project_edit_summary.html', {
        'form': form, 'new_tab': True, 'school': school,
    }, context_instance=RequestContext(request))
Beispiel #30
0
def fire_activity(sender, **kwargs):
    instance = kwargs.get('instance', None)
    created = kwargs.get('created', False)
    is_comment = isinstance(instance, PageComment)
    if created and is_comment:
        instance.send_comment_notification()
        if instance.page_object.comments_fire_activity():
            from activity.models import Activity
            activity = Activity(actor=instance.author, verb=verbs['post'],
                target_object=instance, scope_object=instance.scope_object)
            activity.save()
Beispiel #31
0
def create(request):
    user = request.user.get_profile()
    school = None
    if request.method == 'POST':
        form = project_forms.CreateProjectForm(request.POST)
        if form.is_valid():
            project = form.save()
            act = Activity(actor=user,
                verb='http://activitystrea.ms/schema/1.0/post',
                project=project,
                target_project=project)
            act.save()
            participation = Participation(project= project, user=user, organizing=True)
            participation.save()
            new_rel = Relationship(source=user, target_project=project)
            try:
                new_rel.save()
            except IntegrityError:
                pass
            detailed_description_content = render_to_string(
                "projects/detailed_description_initial_content.html",
                {})
            detailed_description = Page(title=_('Full Description'), slug='full-description',
                content=detailed_description_content, listed=False,
                author_id=user.id, project_id=project.id)
            detailed_description.save()
            project.detailed_description_id = detailed_description.id
            sign_up_content = render_to_string("projects/sign_up_initial_content.html",
                {})
            sign_up = Page(title=_('Sign-Up'), slug='sign-up',
                content=sign_up_content, listed=False, editable=False,
                author_id=user.id, project_id=project.id)
            sign_up.save()
            project.sign_up_id = sign_up.id
            project.save()
            messages.success(request, _('The study group has been created.'))
            return http.HttpResponseRedirect(reverse('projects_show', kwargs={
                'slug': project.slug,
            }))
        else:
            messages.error(request,
                _("There was a problem creating the study group."))
    else:
        if 'school' in request.GET:
            try:
                school = School.objects.get(slug=request.GET['school'])
                form = project_forms.CreateProjectForm(initial={'school': school})
            except School.DoesNotExist:
                return http.HttpResponseRedirect(reverse('projects_create'))
        else:
            form = project_forms.CreateProjectForm()
    return render_to_response('projects/project_edit_summary.html', {
        'form': form, 'new_tab': True, 'school': school,
    }, context_instance=RequestContext(request))
Beispiel #32
0
def vote(request):
    answer_id = request.POST['answer']
    answer = Answer.objects.get(pk=answer_id)
    vote = request.POST['vote']
    user = request.user
    activity = Activity.objects.filter(Q(activity_type=Activity.UP_VOTE) | Q(activity_type=Activity.DOWN_VOTE), user=user, answer=answer_id)
    if activity:
        activity.delete()
    if vote in [Activity.UP_VOTE, Activity.DOWN_VOTE]:
        activity = Activity(activity_type=vote, user=user, answer=answer_id)
        activity.save()
    return HttpResponse(answer.calculate_votes())
Beispiel #33
0
def follow_handler(sender, **kwargs):
    rel = kwargs.get('instance', None)
    created = kwargs.get('created', False)
    if not created or not isinstance(rel, Relationship) or rel.deleted:
        return
    activity = Activity(actor=rel.source,
                        verb=verbs['follow'],
                        target_object=rel)
    receipts = []
    ulang = get_language()
    subject = {}
    body = {}
    if rel.target_user:
        for l in settings.SUPPORTED_LANGUAGES:
            activate(l[0])
            subject[l[0]] = ugettext(
                '%(user)s is following you on P2PU!') % {
                'user': rel.source}
        preferences = AccountPreferences.objects.filter(user=rel.target_user)
        for pref in preferences:
            if pref.value and pref.key == 'no_email_new_follower':
                break
        else:
            receipts.append(rel.target_user)
    else:
        activity.scope_object = rel.target_project
        for l in settings.SUPPORTED_LANGUAGES:
            activate(l[0])
            msg = ugettext(
                '%(user)s is following %(project)s on P2PU!')
            subject[l[0]] = msg % {'user': rel.source,
                'project': rel.target_project}
        for organizer in rel.target_project.organizers():
            if organizer.user != rel.source:
                preferences = AccountPreferences.objects.filter(
                    user=organizer.user, key='no_email_new_project_follower')
                for pref in preferences:
                    if pref.value:
                        break
                else:
                    receipts.append(organizer.user)
    activity.save()

    for l in settings.SUPPORTED_LANGUAGES:
        activate(l[0])
        body[l[0]] = render_to_string(
            "relationships/emails/new_follower.txt", {'user': rel.source,
                'project': rel.target_project,
                'domain': Site.objects.get_current().domain})
    activate(ulang)
    for user in receipts:
        pl = user.preflang or settings.LANGUAGE_CODE
        SendUserEmail.apply_async((user, subject[pl], body[pl]))
Beispiel #34
0
def fire_activity(sender, **kwargs):
    instance = kwargs.get('instance', None)
    created = kwargs.get('created', False)
    is_comment = isinstance(instance, PageComment)
    if created and is_comment:
        instance.send_comment_notification()
        if instance.page_object.comments_fire_activity():
            from activity.models import Activity
            activity = Activity(actor=instance.author,
                                verb=verbs['post'],
                                target_object=instance,
                                scope_object=instance.scope_object)
            activity.save()
Beispiel #35
0
def fire_activity(sender, **kwargs):
    instance = kwargs.get('instance', None)
    created = kwargs.get('created', False)
    is_comment = isinstance(instance, PageComment)
    if created and is_comment:
        from signups.models import SignupAnswer
        ct = ContentType.objects.get_for_model(SignupAnswer)
        if instance.page_content_type != ct:
            statsd.Statsd.increment('comments')
        if instance.page_object and instance.page_object.comments_fire_activity():
            from activity.models import Activity
            activity = Activity(actor=instance.author, verb=verbs['post'],
                target_object=instance, scope_object=instance.scope_object)
            activity.save()
Beispiel #36
0
def add_activity(request):
	if request.POST:
		act_content = request.POST.get('act_content')
		user_id = request.POST.get('user_id')
		print(act_content)
		try:
			act_obj = Activity(act_content=act_content, user_id=user_id)
			act_obj.save()
			return render(request, 'activity/add.html', {'message': '活动表添加成功'})
		except:
			print('fail to add')
			return render(request, 'activity/add.html', {'message': '活动表添加失败'})
	else:
		return render(request, 'activity/add.html')
 def test_can_crate_basic_activity_with_no_sections(self):
     """
     tests if activity can be crated with no additional data
     """
     start_date = time = timezone.now()
     activity_type = Activity.STRENGTH
     name = 'Test Training'
     new_activity = Activity(
         start_date=start_date,
         activity_type=activity_type,
         name=name,
         posted_by=self.user1,
     )
     new_activity.save()
     self.assertEqual(new_activity.name, name)
Beispiel #38
0
def like(request):
    feed_id = request.POST['feed']
    feed = Feed.objects.get(pk=feed_id)
    user = request.user
    like = Activity.objects.filter(activity_type=Activity.LIKE,
                                   feed=feed_id,
                                   user=user)
    if like:
        user.profile.unotify_liked(feed)
        like.delete()
    else:
        like = Activity(activity_type=Activity.LIKE, feed=feed_id, user=user)
        like.save()
        user.profile.notify_liked(feed)
    return HttpResponse(feed.calculate_likes())
Beispiel #39
0
def status_creation_handler(sender, **kwargs):
    status = kwargs.get('instance', None)
    created = kwargs.get('created', False)

    if not created or not isinstance(status, Status):
        return

    # fire activity
    activity = Activity(
        actor=status.author,
        verb=verbs['post'],
        target_object=status,
    )
    if status.project:
        activity.scope_object = status.project
    activity.save()
Beispiel #40
0
def status_creation_handler(sender, **kwargs):
    status = kwargs.get('instance', None)
    created = kwargs.get('created', False)

    if not created or not isinstance(status, Status):
        return

    # fire activity
    activity = Activity(
        actor=status.author,
        verb=verbs['post'],
        target_object=status,
    )
    if status.project:
        activity.scope_object = status.project
    activity.save()
Beispiel #41
0
def showactivity(request, gurl_number, turl_number):
    corporation = Corporation.objects(url_number=gurl_number).get()
    activity = Activity.objects(url_number=turl_number).get()
    if request.method == 'POST':
        if "reply" in request.POST:
            reply_form = NewReplyForm(request.POST)
            if reply_form.is_valid():
                content = reply_form.cleaned_data['content']
                reply = Reply(content=content)
                sccard = S_C_Card.objects(user=request.user,
                                          corporation=corporation).get()
                reply.creator = sccard
                reply.creat_time = datetime.datetime.now()
                reply.target = activity
                reply.is_active = True
                reply.save()
                activity.clicks = topic.clicks - 1
                activity.save()
                return HttpResponseRedirect('/corporation/' +
                                            str(gurl_number) + '/activity/' +
                                            str(turl_number) + '/')

    else:
        reply_form = NewReplyForm()
        activity.clicks = activity.clicks + 1
        activity.save()
        return render_to_response('corporation/activity_corporation.html', {
            'corporation': corporation,
            'current_user': request.user,
            'reply_form': reply_form,
            'activity': activity,
            'STATIC_URL': STATIC_URL
        },
                                  context_instance=RequestContext(request))
Beispiel #42
0
def fire_activity(sender, **kwargs):
    instance = kwargs.get('instance', None)
    created = kwargs.get('created', False)
    is_comment = isinstance(instance, PageComment)
    if created and is_comment:
        from signups.models import SignupAnswer
        ct = ContentType.objects.get_for_model(SignupAnswer)
        if instance.page_content_type != ct:
            statsd.Statsd.increment('comments')
        if instance.page_object.comments_fire_activity():
            from activity.models import Activity
            activity = Activity(actor=instance.author,
                                verb=verbs['post'],
                                target_object=instance,
                                scope_object=instance.scope_object)
            activity.save()
Beispiel #43
0
    def handle(self, *args, **options):
        """
        This function generates dummy data for our User and Activity model.
        """

        records = []
        for _ in range(10):
            kwargs = {
                'real_name': names.get_full_name(),
                'tz': self.random_timezone(),
            }
            record = User(**kwargs)
            records.append(record)
        User.objects.bulk_create(records)

        total_objects = len(User.objects.all())
        records = []
        for _ in range(30):
            kwargs1 = {
                'start_time': self.random_datetime(),
                'end_time': self.random_datetime(),
                'userid_id': random.randint(1, total_objects)
            }
            record = Activity(**kwargs1)
            records.append(record)
        Activity.objects.bulk_create(records)

        self.stdout.write(self.style.SUCCESS('Records saved successfully.'))
Beispiel #44
0
def showactivity(request, gurl_number, turl_number):
    corporation = Corporation.objects(url_number=gurl_number).get()
    activity = Activity.objects(url_number=turl_number).get()
    if request.method == 'POST':
        if "reply" in request.POST:
            reply_form = NewReplyForm(request.POST)
            if reply_form.is_valid():
                content = reply_form.cleaned_data['content']
                reply = Reply(content=content)
                sccard = S_C_Card.objects(user=request.user, corporation=corporation).get()
                reply.creator = sccard
                reply.creat_time = datetime.datetime.now()
                reply.target = activity
                reply.is_active = True
                reply.save()
                activity.clicks = topic.clicks - 1
                activity.save()
                return HttpResponseRedirect('/corporation/' + str(gurl_number) + '/activity/' + str(turl_number) + '/')
            
        
    else:
        reply_form = NewReplyForm()
        activity.clicks = activity.clicks + 1
        activity.save()
        return render_to_response('corporation/activity_corporation.html', {'corporation':corporation, 'current_user':request.user, 'reply_form':reply_form, 'activity':activity, 'STATIC_URL':STATIC_URL}, context_instance=RequestContext(request))
Beispiel #45
0
def create(request):
    user = request.user.get_profile()
    if request.method == 'POST':
        form = project_forms.CreateProjectForm(request.POST)
        if form.is_valid():
            project = form.save()
            act = Activity(actor=user,
                verb=verbs['post'],
                scope_object=project,
                target_object=project)
            act.save()
            participation = Participation(project=project, user=user,
                organizing=True)
            participation.save()
            new_rel, created = Relationship.objects.get_or_create(source=user,
                target_project=project)
            new_rel.deleted = False
            new_rel.save()
            detailed_description_content = render_to_string(
                "projects/detailed_description_initial_content.html",
                {})
            detailed_description = Page(title=_('Full Description'),
                slug='full-description', content=detailed_description_content,
                listed=False, author_id=user.id, project_id=project.id)
            detailed_description.save()
            project.detailed_description_id = detailed_description.id
            sign_up_content = render_to_string(
                "projects/sign_up_initial_content.html", {})
            sign_up = Page(title=_('Sign-Up'), slug='sign-up',
                content=sign_up_content, listed=False, editable=False,
                author_id=user.id, project_id=project.id)
            sign_up.save()
            project.sign_up_id = sign_up.id
            project.create()
            messages.success(request,
                _('The %s has been created.') % project.kind.lower())
            return http.HttpResponseRedirect(reverse('projects_show', kwargs={
                'slug': project.slug,
            }))
        else:
            msg = _("Problem creating the study group, course, ...")
            messages.error(request, msg)
    else:
        form = project_forms.CreateProjectForm()
    return render_to_response('projects/project_edit_summary.html', {
        'form': form, 'new_tab': True,
    }, context_instance=RequestContext(request))
Beispiel #46
0
def project_creation_handler(sender, **kwargs):
    project = kwargs.get('instance', None)
    created = kwargs.get('created', False)

    if not created or not isinstance(project, Project):
        return

    Relationship(source=project.created_by, target_project=project).save()

    try:
        from activity.models import Activity
        act = Activity(actor=project.created_by,
                       verb='http://activitystrea.ms/schema/1.0/post',
                       project=project,
                       target_project=project)
        act.save()
    except ImportError:
        return
Beispiel #47
0
def project_creation_handler(sender, **kwargs):
    project = kwargs.get('instance', None)
    created = kwargs.get('created', False)

    if not created or not isinstance(project, Project):
        return

    Relationship(source=project.created_by,
                 target_project=project).save()

    try:
        from activity.models import Activity
        act = Activity(actor=project.created_by,
                       verb='http://activitystrea.ms/schema/1.0/post',
                       project=project,
                       target_project=project)
        act.save()
    except ImportError:
        return
Beispiel #48
0
def activity(request):
    if request.method == 'POST':
        user = request.user
        post_slug = request.POST.get('post_slug')
        post = Post.objects.get(slug=post_slug)
        actype = request.POST.get('atype')
        status = True
        like = Activity.objects.filter(activity_type = Activity.LIKE, post=post, user=user)
        dislike = Activity.objects.filter(activity_type = Activity.DISLIKE, post=post, user=user)
        
        if actype in Activity.LIKE:
            atype = Activity.LIKE      
            if not dislike:
                if like:
                    like.delete()
                    status = False
            else:
                 dislike.delete()

        elif actype in Activity.DISLIKE:
            atype = Activity.DISLIKE
            if not like:
                if dislike: 
                    dislike.delete() 
                    status = False   
            else:
                like.delete()
        else:
            return HttpResponseBadRequest()

        if status:
            Activity.create_activity(user, post, atype)
        
        context ={
        }
    
        count = Activity.calculate_activity(post, atype)
        context = {
            'status': True,
            'count': count,
        }
        return JsonResponse(context)
Beispiel #49
0
def home(request):
    if request.method == 'POST':
        # get the POST data
        name_value = request.POST.get('name', '')
        type_value = request.POST.get('type', '')
        date_value = request.POST.get('date', '')
        description_value = request.POST.get('description', '')

        # save the POST data

        activity = Activity(name=name_value,
                            type=type_value,
                            date=date_value,
                            description=description_value)

        activity.save()

        return HttpResponseRedirect('/table/')
    form = ActivityForm()
    return render(request, 'form.html', {'form': form})
Beispiel #50
0
def send(actor, verb, object, target=None):
    """
    Create an activity. Activities are composed of an actor, verb, object and
    optionally a target. For example:

    <paul> <posted> a <status update> to <project>

    Actors can be instances of ```User``` or dictionaries that will be
    used to represent remote users (e.g. a user who does not have an
    account on this system).

    Verbs are represented by IRIs as per the Atom Activity specification.
    http://activitystrea.ms/spec/1.0/atom [3.1].

    Objects and Targets can be instances of ```Model``` or dictionaries
    that will be used to represent remote objects (e.g. a blog post or a
    status update from another site).

    Example 1 - Creating an activity with a local user and local object:

    >>> activity.send(status.author, 'post', status)

    Example 2 - Creating an activity with a remote user and remote object:

    >>> user = dict(name='Paul Osman', email='*****@*****.**')
    >>> status = dict(type='note', title='A status update', content='Blah')
    >>> activity.send(user, 'post', status)
    """
    actor, created = (isinstance(actor, User) and
                      Actor.objects.get_or_create(user=actor) or
                      Actor.objects.get_or_create(**actor))
    activity = Activity(actor=actor, verb=verb)
    for attr, value in dict(object=object, target=target).iteritems():
        if isinstance(value, dict):
            if 'type' not in value:
                raise ActivityError('Type not defined for %s.' % (attr,))
            setattr(activity, attr, _create_remote_object(value))
        else:
            setattr(activity, attr, value)
    activity.save()
    return activity
Beispiel #51
0
def fire_activity(sender, **kwargs):
    instance = kwargs.get('instance', None)
    created = kwargs.get('created', False)

    is_page = isinstance(instance, Page)
    is_comment = isinstance(instance, PageComment)
    if created and (is_page or is_comment):
        # Do not fire activities for comments on the sign-up page.
        if is_comment and instance.page.slug == 'sign-up':
            instance.send_sign_up_notification()
            return
        # fire activity
        activity = Activity(
            actor=instance.author,
            verb='http://activitystrea.ms/schema/1.0/post',
            target_object=instance,
        )
        activity.target_project = instance.project
        activity.save()
        # Send notifications.
        activity.target_project.send_update_notification(activity, wall=False)
Beispiel #52
0
def like(request):
    article_id = request.POST['article']
    comment_id = request.POST['comment']
    comment = ArticleComment.objects.get(pk=comment_id)
    user = request.user
    like = Activity.objects.filter(activity_type=Activity.LIKE,
                                   article=article_id,
                                   user=user,
                                   article_comment=comment_id)
    if like:
        user.profile.unotify_liked_comment(comment)
        like.delete()
        pass
    else:
        like = Activity(activity_type=Activity.LIKE,
                        article=article_id,
                        user=user,
                        article_comment=comment_id)
        like.save()
        user.profile.notify_liked_comment(comment)
    return HttpResponse(comment.calculate_likes())
Beispiel #53
0
def vote(request):
    article_id = request.POST['article']
    article = Article.objects.get(pk=article_id)
    vote = request.POST['vote']
    user = request.user
    activity = Activity.objects.filter(Q(activity_type=Activity.UP_VOTEA)
                                       | Q(activity_type=Activity.DOWN_VOTEA),
                                       user=user,
                                       article=article_id)
    if activity:
        activity.delete()
    if vote in [Activity.UP_VOTEA, Activity.DOWN_VOTEA]:
        activity = Activity(activity_type=vote, user=user, article=article_id)
        activity.save()

    if request.user != article.create_user:
        if vote == Activity.UP_VOTEA:
            request.user.profile.notify_upvoted_article(article)
        else:
            request.user.profile.notify_downvoted_article(article)
    return HttpResponse(article.calculate_votes())
    def test_can_crate_activity_with_section(self):
        """
        tests if activity section is connected to activity correctly
        """
        start_date = time = timezone.now()
        activity_type = Activity.STRENGTH
        name = 'Test Training'
        new_activity = Activity(
            start_date=start_date,
            activity_type=activity_type,
            name=name,
            posted_by=self.user1,
        )
        new_activity.save()

        section_data = StrengthSections(section_name='MAIN',
                                        activity=new_activity)

        section_data.save()

        self.assertEqual(new_activity.get_sections().count(), 1)
Beispiel #55
0
def follow_handler(sender, **kwargs):
    rel = kwargs.get('instance', None)
    created = kwargs.get('created', False)
    if not created or not isinstance(rel, Relationship) or rel.deleted:
        return
    activity = Activity(actor=rel.source,
                        verb=verbs['follow'],
                        target_object=rel)
    receipts = []
    if rel.target_user:
        preferences = AccountPreferences.objects.filter(
            user=rel.target_user, key='no_email_new_follower')
        for pref in preferences:
            if pref.value:
                break
        else:
            receipts.append(rel.target_user)
    else:
        activity.scope_object = rel.target_project
        for organizer in rel.target_project.organizers():
            if organizer.user != rel.source:
                preferences = AccountPreferences.objects.filter(
                    user=organizer.user, key='no_email_new_project_follower')
                for pref in preferences:
                    if pref.value:
                        break
                else:
                    receipts.append(organizer.user)
    activity.save()
    context = {
        'user': rel.source,
        'project': rel.target_project,
        'domain': Site.objects.get_current().domain
    }
    subjects, bodies = localize_email(
        'relationships/emails/new_follower_subject.txt',
        'relationships/emails/new_follower.txt', context)
    for user in receipts:
        SendUserEmail.apply_async((user, subjects, bodies))
Beispiel #56
0
def create(request):
    user = request.user.get_profile()
    if request.method == "POST":
        form = project_forms.ProjectForm(request.POST)
        if form.is_valid():
            project = form.save()
            act = Activity(actor=user, verb=verbs["post"], scope_object=project, target_object=project)
            act.save()
            participation = Participation(project=project, user=user, organizing=True)
            participation.save()
            new_rel, created = Relationship.objects.get_or_create(source=user, target_project=project)
            new_rel.deleted = False
            new_rel.save()
            detailed_description_content = render_to_string("projects/detailed_description_initial_content.html", {})
            detailed_description = Page(
                title=_("Full Description"),
                slug="full-description",
                content=detailed_description_content,
                listed=False,
                author_id=user.id,
                project_id=project.id,
            )
            if project.category != Project.STUDY_GROUP:
                detailed_description.collaborative = False
            detailed_description.save()
            project.detailed_description_id = detailed_description.id
            sign_up = Signup(author_id=user.id, project_id=project.id)
            sign_up.save()
            project.create()
            messages.success(request, _("The %s has been created.") % project.kind.lower())
            return http.HttpResponseRedirect(reverse("projects_show", kwargs={"slug": project.slug}))
        else:
            msg = _("Problem creating the study group, course, ...")
            messages.error(request, msg)
    else:
        form = project_forms.ProjectForm()
    return render_to_response(
        "projects/project_edit_summary.html", {"form": form, "new_tab": True}, context_instance=RequestContext(request)
    )
Beispiel #57
0
def follow_handler(sender, **kwargs):
    rel = kwargs.get('instance', None)
    created = kwargs.get('created', False)
    if not created or not isinstance(rel, Relationship):
        return
    user_subject = ugettext('%(display_name)s is following you on P2PU!') % {
        'display_name': rel.source.display_name,
    }
    project_subject = ugettext('%(display_name)s is following %(project)s on P2PU!') % {
        'display_name': rel.source.display_name,
        'project': rel.target_project,
    }
    activity = Activity(actor=rel.source,
                        verb='http://activitystrea.ms/schema/1.0/follow')
    subject = ugettext('%(display_name)s is now following')
    if rel.target_user:
        activity.target_user = rel.target_user
        user = rel.target_user
        pref_key = 'no_email_new_follower'
        subject = user_subject
    else:
        activity.project = rel.target_project
        user = rel.target_project.created_by
        pref_key = 'no_email_new_project_follower'
        subject = project_subject
    activity.save()

    preferences = AccountPreferences.objects.filter(user=user)
    for pref in preferences:
        if pref.value and pref.key == pref_key:
            return

    body = render_to_string("relationships/emails/new_follower.txt", {
        'user': rel.source,
        'project': rel.target_project,
        'domain': Site.objects.get_current().domain,
    })
    SendUserEmail.apply_async((user, subject, body))
    def handle(self, *args, **options):
        number = int(options['number'][0])
        print(options['number'])
        
        for i in range(number):
            print("Creating user {} of {}".format(i+1, number))
            user = User()
            user.username = self.get_username()
            user.first_name = self.get_username().capitalize()
            user.last_name = self.get_username().capitalize()
            user.password = make_password("password")
            user.email = fake.email()
            user.save()
        print("Done. Created {} users".format(i+1))

        print("==================================UserActivities=========================")
        users = User.objects.all()
        for user in users:            
            for activiti in activities:
                activity = Activity()
                activity.owner = user
                activity.activity_name = activiti
                activity.save()
                
        print("=================Statistics======================")
        
        user_activities = Activity.objects.all()
        for i in range(10):
            print("Activities round {}".format(i))
            for activity in user_activities:
                print("User {}".format(activity.owner.username))
                activity_stat = ActivityStatistics()
                activity_stat.activity = activity
                activity_stat.owner = activity.owner
                activity_stat.value = random.randint(3, 20)
                activity_stat.statistics_date = fake.date()
                activity_stat.save()
Beispiel #59
0
def todo_creation_handler(sender, **kwargs):
    todo = kwargs.get('instance', None)
    created = kwargs.get('created', False)

    if not created or not isinstance(todo, Todo):
        return

    # convert todo body to markdown and bleachify
    bl = Bleach()
    todo.title = urlize(todo.title)
    todo.description = urlize(todo.description)
    todo.title = bl.clean(markdown(todo.title), tags=TAGS)
    todo.description = bl.clean(markdown(todo.description), tags=TAGS)
    todo.save()

    # fire activity
    activity = Activity(
        actor=todo.author,
        verb='http://activitystrea.ms/schema/1.0/post',
        target_todo=todo,
    )
    if todo.project:
        activity.target_project = todo.project
    activity.save()