Beispiel #1
0
def manage_multimedia(request, domain):
    media = request.project.all_media()
    if request.method == "POST":
        for m_file in media:
            if '%s_tags' % m_file._id in request.POST:
                m_file.tags[domain] = request.POST.get('%s_tags' % m_file._id, '').split(' ')

            if domain not in m_file.shared_by and request.POST.get('%s_shared' % m_file._id, False):
                m_file.shared_by.append(domain)
            elif domain in m_file.shared_by and not request.POST.get('%s_shared' % m_file._id, False):
                m_file.shared_by.remove(domain)

            if '%s_license' % m_file._id in request.POST:
                m_file.update_or_add_license(domain, type=request.POST.get('%s_license' % m_file._id, 'public'))
            m_file.save()
        messages.success(request, "Multimedia updated successfully!")

    return render(request, 'domain/admin/media_manager.html', {'domain': domain,
        'media': [{
            'license': m.license.type if m.license else 'public',
            'shared': domain in m.shared_by,
            'url': m.url(),
            'm_id': m._id,
            'tags': m.tags.get(domain, []),
            'type': m.doc_type
                   } for m in media],
        'licenses': LICENSES.items()
    })
Beispiel #2
0
def _appstore_context(context={}):
    context['sortables'] = [
            ('category', [(d.replace(' ', '+'), d, count) for d, count in Domain.field_by_prefix('project_type')]),
            ('region', [(d.replace(' ', '+'), d, count) for d, count in Domain.field_by_prefix('region')]),
            ('author', [(d.replace(' ', '+'), d, count) for d, count in Domain.field_by_prefix('author')]),
            ('license', [(d, LICENSES.get(d), count) for d, count in Domain.field_by_prefix('license')]),
        ]
    return context
Beispiel #3
0
def manage_multimedia(request, domain):
    media = request.project.all_media()
    if request.method == "POST":
        for m_file in media:
            if '%s_tags' % m_file._id in request.POST:
                m_file.tags[domain] = request.POST.get('%s_tags' % m_file._id,
                                                       '').split(' ')

            if domain not in m_file.shared_by and request.POST.get(
                    '%s_shared' % m_file._id, False):
                m_file.shared_by.append(domain)
            elif domain in m_file.shared_by and not request.POST.get(
                    '%s_shared' % m_file._id, False):
                m_file.shared_by.remove(domain)

            if '%s_license' % m_file._id in request.POST:
                m_file.update_or_add_license(domain,
                                             type=request.POST.get(
                                                 '%s_license' % m_file._id,
                                                 'public'))
            m_file.save()
        messages.success(request, "Multimedia updated successfully!")

    return render(
        request, 'domain/admin/media_manager.html', {
            'domain':
            domain,
            'media': [{
                'license': m.license.type if m.license else 'public',
                'shared': domain in m.shared_by,
                'url': m.url(),
                'm_id': m._id,
                'tags': m.tags.get(domain, []),
                'type': m.doc_type
            } for m in media],
            'licenses':
            LICENSES.items()
        })
Beispiel #4
0
 def display_name(self):
     return LICENSES.get(self.type, "Improper License")
Beispiel #5
0
 def display_name(self):
     return LICENSES.get(self.type, "Improper License")
Beispiel #6
0
 def options(self):
     return [(code, license_name) for code, license_name in LICENSES.items()]
Beispiel #7
0
 def page_context(self):
     return {
         'media': self.project_media_data,
         'licenses': list(LICENSES.items()),
     }
Beispiel #8
0
 def update_params(self):
     available_licenses = [{'val': code, 'text': license} for code, license in LICENSES.items()]
     self.selected = self.request.GET.get(self.slug,'')
     self.options = available_licenses
Beispiel #9
0
class SnapshotSettingsForm(SnapshotSettingsMixin):
    title = CharField(label=ugettext_noop("Title"),
                      required=True,
                      max_length=100)
    project_type = CharField(label=ugettext_noop("Project Category"),
                             required=True,
                             help_text=ugettext_noop("e.g. MCH, HIV, etc."))
    license = ChoiceField(label=ugettext_noop("License"),
                          required=True,
                          choices=LICENSES.items(),
                          widget=Select(attrs={'class': 'input-xxlarge'}))
    description = CharField(
        label=ugettext_noop("Long Description"),
        required=False,
        widget=forms.Textarea,
        help_text=ugettext_noop(
            "A high-level overview of your project as a whole"))
    short_description = CharField(
        label=ugettext_noop("Short Description"),
        required=False,
        widget=forms.Textarea(attrs={'maxlength': 200}),
        help_text=ugettext_noop(
            "A brief description of your project (max. 200 characters)"))
    share_multimedia = BooleanField(
        label=ugettext_noop("Share all multimedia?"),
        required=False,
        help_text=ugettext_noop(
            "This will allow any user to see and use all multimedia in this project"
        ))
    share_reminders = BooleanField(
        label=ugettext_noop("Share Reminders?"),
        required=False,
        help_text=ugettext_noop(
            "This will publish reminders along with this project"))
    image = forms.ImageField(
        label=ugettext_noop("Exchange image"),
        required=False,
        help_text=ugettext_noop(
            "An optional image to show other users your logo or what your app looks like"
        ))
    video = CharField(
        label=ugettext_noop("Youtube Video"),
        required=False,
        help_text=ugettext_noop(
            "An optional youtube clip to tell users about your app. Please copy and paste a URL to a youtube video"
        ))
    cda_confirmed = BooleanField(
        required=False, label=ugettext_noop("Content Distribution Agreement"))

    def __init__(self, *args, **kw):
        super(SnapshotSettingsForm, self).__init__(*args, **kw)
        self.fields.keyOrder = [
            'title',
            'short_description',
            'description',
            'project_type',
            'image',
            'video',
            'share_multimedia',
            'share_reminders',
            'license',
            'cda_confirmed',
        ]
        self.fields['license'].help_text = \
            render_to_string('domain/partials/license_explanations.html', {
                'extra': _("All un-licensed multimedia files in "
                           "your project will be given this license")
            })
        self.fields['cda_confirmed'].help_text = \
            render_to_string('domain/partials/cda_modal.html')

    def clean_cda_confirmed(self):
        data_cda = self.cleaned_data['cda_confirmed']
        data_publish = self.data.get('publish_on_submit', "no") == "yes"
        if data_publish and data_cda is False:
            raise forms.ValidationError(
                'You must agree to our Content Distribution Agreement to publish your project.'
            )
        return data_cda

    def clean_video(self):
        video = self.cleaned_data['video']
        if not video:
            return video

        def video_id(value):
            # http://stackoverflow.com/questions/4356538/how-can-i-extract-video-id-from-youtubes-link-in-python#answer-7936523
            """
            Examples:
            - http://youtu.be/SA2iWivDJiE
            - http://www.youtube.com/watch?v=_oPAwA_Udwc&feature=feedu
            - http://www.youtube.com/embed/SA2iWivDJiE
            - http://www.youtube.com/v/SA2iWivDJiE?version=3&hl=en_US
            """
            query = urlparse(value)
            if query.hostname == 'youtu.be':
                return query.path[1:]
            if query.hostname in ('www.youtube.com', 'youtube.com'):
                if query.path == '/watch':
                    p = parse_qs(query.query)
                    return p['v'][0]
                if query.path[:7] == '/embed/':
                    return query.path.split('/')[2]
                if query.path[:3] == '/v/':
                    return query.path.split('/')[2]
                    # fail?
            return None

        v_id = video_id(video)
        if not v_id:
            raise forms.ValidationError(
                'This is not a correctly formatted youtube URL. Please use a different URL.'
            )
        return v_id

    def clean(self):
        cleaned_data = self.cleaned_data
        sm = cleaned_data["share_multimedia"]
        license = cleaned_data["license"]
        app_ids = self._get_apps_to_publish()

        if sm and license not in self.dom.most_restrictive_licenses(
                apps_to_check=app_ids):
            license_choices = [
                LICENSES[l] for l in self.dom.most_restrictive_licenses(
                    apps_to_check=app_ids)
            ]
            msg = render_to_string('domain/partials/restrictive_license.html',
                                   {'licenses': license_choices})
            self._errors["license"] = self.error_class([msg])

            del cleaned_data["license"]

        sr = cleaned_data["share_reminders"]
        if sr:  # check that the forms referenced by the events in each reminders exist in the project
            referenced_forms = CaseReminderHandler.get_referenced_forms(
                domain=self.dom.name)
            if referenced_forms:
                apps = [Application.get(app_id) for app_id in app_ids]
                app_forms = [
                    f.unique_id for forms in [app.get_forms() for app in apps]
                    for f in forms
                ]
                nonexistent_forms = filter(lambda f: f not in app_forms,
                                           referenced_forms)
                nonexistent_forms = [
                    FormBase.get_form(f) for f in nonexistent_forms
                ]
                if nonexistent_forms:
                    msg = """
                        Your reminders reference forms that are not being published.
                        Make sure the following forms are being published: %s
                    """ % str([f.default_name()
                               for f in nonexistent_forms]).strip('[]')
                    self._errors["share_reminders"] = self.error_class([msg])

        return cleaned_data

    def _get_apps_to_publish(self):
        app_ids = []
        for d, val in self.data.iteritems():
            d = d.split('-')
            if len(d) < 2:
                continue
            if d[1] == 'publish' and val == 'on':
                app_ids.append(d[0])

        return app_ids
Beispiel #10
0
 def page_context(self):
     return {
         'media': self.project_media_data,
         'licenses': list(LICENSES.items()),
     }
Beispiel #11
0
def create_snapshot(request, domain):
    domain = Domain.get_by_name(domain)
    #latest_applications = [app.get_latest_saved() or app for app in domain.applications()]
    if request.method == 'GET':
        form = SnapshotSettingsForm(initial={
                'default_timezone': domain.default_timezone,
                'case_sharing': json.dumps(domain.case_sharing),
                'city': domain.city,
                'country': domain.country,
                'region': domain.region,
                'project_type': domain.project_type,
                'share_multimedia': True,
                'license': domain.license
            })
        published_snapshot = domain.published_snapshot() or domain
        published_apps = {}
        if published_snapshot is not None:
            form = SnapshotSettingsForm(initial={
                'default_timezone': published_snapshot.default_timezone,
                'case_sharing': json.dumps(published_snapshot.case_sharing),
                'city': published_snapshot.city,
                'country': published_snapshot.country,
                'region': published_snapshot.region,
                'project_type': published_snapshot.project_type,
                'license': published_snapshot.license,
                'title': published_snapshot.title,
                'author': published_snapshot.author,
                'share_multimedia': True,
                'description': published_snapshot.description
            })
            for app in published_snapshot.full_applications():
                if domain == published_snapshot:
                    published_apps[app._id] = app
                else:
                    published_apps[app.original_doc] = app
        app_forms = []
        for app in domain.applications():
            app = app.get_latest_saved() or app
            if published_snapshot and app._id in published_apps:
                original = published_apps[app._id]
                app_forms.append((app, SnapshotApplicationForm(initial={
                    'publish': True,
                    'name': original.name,
                    'description': original.description,
                    'deployment_date': original.deployment_date,
                    'user_type': original.user_type,
                    'attribution_notes': original.attribution_notes,
                    'phone_model': original.phone_model,

                }, prefix=app.id)))
            else:
                app_forms.append((app, SnapshotApplicationForm(initial={'publish': (published_snapshot is None or published_snapshot == domain)}, prefix=app.id)))
        return render_to_response(request, 'domain/create_snapshot.html',
            {'domain': domain.name,
             'form': form,
             #'latest_applications': latest_applications,
             'app_forms': app_forms,
             'autocomplete_fields': ('project_type', 'phone_model', 'user_type', 'city', 'country', 'region')})
    elif request.method == 'POST':
        form = SnapshotSettingsForm(request.POST, request.FILES)
        app_forms = []
        publishing_apps = False
        for app in domain.applications():
            app = app.get_latest_saved() or app
            app_forms.append((app, SnapshotApplicationForm(request.POST, prefix=app.id)))
            publishing_apps = publishing_apps or request.POST.get("%s-publish" % app.id, False)
        if not publishing_apps:
            messages.error(request, "Cannot publish a project without applications to CommCare Exchange")
            return render_to_response(request, 'domain/create_snapshot.html',
                {'domain': domain.name,
                 'form': form,
                 'app_forms': app_forms,
                 'autocomplete_fields': ('project_type', 'phone_model', 'user_type', 'city', 'country', 'region')})
        
        if not form.is_valid():
            return render_to_response(request, 'domain/create_snapshot.html',
                    {'domain': domain.name,
                     'form': form,
                     #'latest_applications': latest_applications,
                     'app_forms': app_forms,
                     'autocomplete_fields': ('project_type', 'phone_model', 'user_type', 'city', 'country', 'region')})

        if request.POST.get('share_multimedia', False):
            media = domain.all_media()
            for m_file in media:
                if domain.name not in m_file.shared_by:
                    m_file.shared_by.append(domain.name)
                    m_file.licenses[domain.name] = domain.license
                    m_file.save()
        old = domain.published_snapshot()
        new_domain = domain.save_snapshot()
        if request.POST['license'] in LICENSES.keys():
            new_domain.license = request.POST['license']
        new_domain.description = request.POST['description']
        new_domain.project_type = request.POST['project_type']
        new_domain.region = request.POST['region']
        new_domain.city = request.POST['city']
        new_domain.country = request.POST['country']
        new_domain.title = request.POST['title']
        new_domain.author = request.POST['author']
        for snapshot in domain.snapshots():
            if snapshot.published and snapshot._id != new_domain._id:
                snapshot.published = False
                snapshot.save()
        new_domain.is_approved = False
        new_domain.published = True
        image = form.cleaned_data['image']
        if image:
            new_domain.image_path = image.name
            new_domain.image_type = image.content_type
        elif request.POST.get('old_image', False):
            new_domain.image_path = old.image_path
            new_domain.image_type = old.image_type
        new_domain.save()

        if image:
            im = Image.open(image)
            out = cStringIO.StringIO()
            im.thumbnail((200, 200), Image.ANTIALIAS)
            im.save(out, new_domain.image_type.split('/')[-1])
            new_domain.put_attachment(content=out.getvalue(), name=image.name)
        elif request.POST.get('old_image', False):
            new_domain.put_attachment(content=old.fetch_attachment(old.image_path), name=new_domain.image_path)

        for application in new_domain.full_applications():
            original_id = application.original_doc
            if request.POST.get("%s-publish" % original_id, False):
                application.name = request.POST["%s-name" % original_id]
                application.description = request.POST["%s-description" % original_id]
                date_picked = request.POST["%s-deployment_date" % original_id].split('-')
                if len(date_picked) > 1:
                    if int(date_picked[0]) > 2009 and date_picked[1] and date_picked[2]:
                        application.deployment_date = datetime.datetime(int(date_picked[0]), int(date_picked[1]), int(date_picked[2]))
                #if request.POST.get("%s-name" % original_id):
                application.phone_model = request.POST["%s-phone_model" % original_id]
                application.attribution_notes = request.POST["%s-attribution_notes" % original_id]
                application.user_type = request.POST["%s-user_type" % original_id]
                application.save()
            else:
                application.delete()

        if new_domain is None:
            return render_to_response(request, 'domain/snapshot_settings.html',
                    {'domain': domain.name,
                     'form': form,
                     #'latest_applications': latest_applications,
                     'app_forms': app_forms,
                     'error_message': 'Snapshot creation failed; please try again'})

        messages.success(request, "Created snapshot. The snapshot will be posted to CommCare Exchange pending approval by admins.")
        return redirect('domain_snapshot_settings', domain.name)
Beispiel #12
0
 def update_params(self):
     available_licenses = [{"val": code, "text": license} for code, license in LICENSES.items()]
     self.selected = self.request.GET.get(self.slug, "")
     self.options = available_licenses
Beispiel #13
0
 def options(self):
     return [(code, license_name)
             for code, license_name in LICENSES.items()]
Beispiel #14
0
 def update_params(self):
     available_licenses = [{'val': code, 'text': license} for code, license in LICENSES.items()]
     self.selected = self.request.GET.get(self.slug,'')
     self.options = available_licenses