Ejemplo n.º 1
0
def submit_suggestion(request, suggestion_form):
    """
    Save a new suggestion in the database.
    """
    slug = suggestion_form.cleaned_data['slug']
    tag_list = suggestion_form.cleaned_data['tags'].split()
    for tag_name in tag_list:
        tag = Tag.get_by_key_name(tag_name)
        if tag is None:
            tag = Tag(key_name=tag_name, count=0)
        tag.suggestions.append(slug)
        tag.count += 1
        tag.put()
    suggestion = Reminder(
        key_name=slug,
        title=suggestion_form.cleaned_data['title'],
        days=suggestion_form.cleaned_data['days'],
        months=suggestion_form.cleaned_data['months'],
        years=suggestion_form.cleaned_data['years'],
        miles=suggestion_form.cleaned_data['miles'],
        kilometers=suggestion_form.cleaned_data['kilometers'],
        tags=tag_list)
    logging.debug(suggestion)
    suggestion.put()
    return HttpResponseRedirect(suggestion.get_absolute_url())
Ejemplo n.º 2
0
def add_new_listing(request):
    if request.method == 'POST':
        schema = SubmitListingSchema()
        data, errors = schema.load(request.POST)
        if not errors:
            form = ListingsForms(request.POST, request.FILES)
            tags_list = data['tag'].split(',')
            if form.is_valid():
                try:
                    listing = form.save(commit=False)
                    listing.user_id = request.profile.user_id
                    listing.save()

                    for tag in tags_list:
                        new_tag = Tag(name=tag)
                        try:
                            new_tag.save()
                            new_tag.listings_set.add(listing)
                            update_profile_tags(new_tag, request.profile,
                                                listing)
                        except IntegrityError as e:
                            existing_tag = Tag.objects.get(name=tag)
                            existing_tag.listings_set.add(listing)
                            update_profile_tags(existing_tag, request.profile,
                                                listing)
                    # save_document(listing)
                    return JsonResponse({'msg': 'Success!'})
                except Exception as e:
                    print(e)
                    return HttpResponseRedirect(reverse('frontend:home'))
        else:
            return JsonResponse({'errors': errors}, status=400)
    else:
        form = ListingsForms()
    return render(request, 'frontend/home.html', {'form': form})
Ejemplo n.º 3
0
 def test_suggestion_tag_reverse(self):
     # Create a suggestion and tags but with a missing reverse reference.
     Reminder(key_name='a-b', title='a b', tags='a b'.split()).put()
     Reminder(key_name='b-c', title='b c', tags='b'.split()).put()
     Tag(key_name='a', suggestions='a-b'.split(), count=0).put()
     Tag(key_name='b', suggestions='b-c'.split(), count=0).put()
     self.assertEqual(Reminder.all().count(), 2)
     self.assertEqual(Tag.all().count(), 2)
     self.assertEqual(len(Tag.get_by_key_name('b').suggestions), 1)
     # Check that the missing tag-reminder reference is detected.
     response = self.client.get('/consistency/')
     self.assertTrue('suggestion_tag_reverse'
                     in response.context['problems'])
     self.assertTrue("Suggestion a-b references b but not reverse."
                     in response.content)
     # Simulate button click to fix this problem.
     response = self.client.post('/consistency/', {
             'suggestion_tag_reverse': "Create reverse references"})
     self.assertRedirects(response, '/consistency/')
     # Check that the tags are now existing.
     self.assertEqual(Reminder.all().count(), 2)
     self.assertEqual(Tag.all().count(), 2)
     self.assertEqual(len(Tag.get_by_key_name('b').suggestions), 2)
     response = self.client.get('/consistency/')
     self.assertFalse('suggestion_tag_reverse'
                      in response.context['problems'])
Ejemplo n.º 4
0
    def setUp(self):
        from regions.models import Region
        from pages.models import Page
        from tags.models import Tag, PageTagSet

        self.factory = RequestFactory()

        # Create a new region and associate a domain with it
        self.sf = Region(full_name="San Francisco", slug="sf")
        self.sf.save()
        self.sf.regionsettings.domain = 'fakename.org'
        self.sf.regionsettings.save()

        self.user = User.objects.create_user(
            username='******', email='*****@*****.**', password='******')
        self.user.save()
       
        # Create a page in the SF region
        p = Page(name='Parks', content='<p>Hi</p>', region=self.sf)
        p.save(user=self.user)
        p.content += "!"
        p.save(user=self.user)

        # Add a tag to the page
        t = Tag(name='park', slug='park', region=self.sf)
        t.save(user=self.user)
        pts = PageTagSet(region=self.sf, page=p)
        pts.save(user=self.user)
        pts.tags.add(t)
        pts.save(user=self.user)
Ejemplo n.º 5
0
    def mutate_and_get_payload(cls, input, request, info):
        gid_type, gid = from_global_id(input.get('lifeNode'))
        node = LifeNode._meta.model.objects.get(document_id=gid)

        error = has_permission(cls, request, node, 'edit')
        if error:
            return error

        tag_title = input.get('title').strip(' \t\n\r')
        tag_slug = slugify(tag_title)

        try:
            tag = TagModel.objects.get(slug=tag_slug)
        except TagModel.DoesNotExist:
            tag = TagModel(
                title=tag_title,
                slug=tag_slug,
            )
            tag.save(request=request)

        c = CharacteristicModel(
            tag=tag.document,
            lifeNode=node.document,
            value=input.get('value')
        )
        c.save(request=request)

        return CharacteristicAdd(
            lifeNode=node,
            characteristic=Characteristic.Connection.Edge(
                node=c, cursor=offset_to_cursor(0))
        )
Ejemplo n.º 6
0
 def test_tag_suggestion_missing(self):
     self.assertEqual(Tag.all().count(), 0)
     # Create tags but not all suggestions.
     Reminder(key_name='a-b', title='a b', tags='a b'.split()).put()
     Tag(key_name='a', count=2, suggestions='a-b a-c'.split()).put()
     Tag(key_name='b', count=2, suggestions='b-c'.split()).put()
     self.assertEqual(Tag.all().count(), 2)
     # Check that the missing suggestions are detected.
     response = self.client.get('/consistency/')
     self.assertTrue('tag_suggestion_missing'
                     in response.context['problems'])
     self.assertTrue("Tag a references missing suggestion a-c."
                     in response.content)
     self.assertTrue("Tag b references missing suggestion b-c."
                     in response.content)
     # Simulate button click to fix this problem.
     response = self.client.post('/consistency/', {
             'tag_suggestion_missing': "Create missing"})
     self.assertRedirects(response, '/consistency/')
     # Check that the references are now gone.
     self.assertEqual(Tag.all().count(), 1)
     self.assertEqual(Tag.get_by_key_name('a').count, 1)
     self.assertEqual(len(Tag.get_by_key_name('a').suggestions), 1)
     response = self.client.get('/consistency/')
     self.assertFalse('tag_suggestion_missing'
                      in response.context['problems'])
Ejemplo n.º 7
0
def add(request, app_label, model, object_id):

    content_type = get_object_or_404(ContentType, app_label=app_label,
                                     model=model)
    model = content_type.model_class()
    object_id = int(object_id)

    item = get_object_or_404(model, id=object_id)
    user = request.user

    new_tags = []

    if request.method == "POST":
        tags = [t.strip() for t in request.POST.get("tags", u"").split(u",")]
        for tag in tags:
            if not item.tags.filter(user=user, slug=slugify(tag)).count():
                tag = Tag(content_type=content_type, object_id=object_id,
                    user=user, name=tag)
                tag.save()
                new_tags.append(tag)

    reindex(item)

    response = {"tags": []}
    for tag in new_tags:
        response["tags"].append(dict(name=tag.name,
                                     id=tag.id,
                                     url=reverse("materials:keyword_index",
                                                 kwargs={"keywords": tag.slug}),
                                     ))

    return response
Ejemplo n.º 8
0
def tagref_create(request, tag_name):
  """ Create a single tag reference. 
  
  The resource must exist and the reference must be valid, but if the tag
  doesn't exist, then then it is created. 
  """
  try:
    # resource MUST exist
    res_str = request.POST['resource'].strip()
    resource = library.get(res_str)
    # reference must be valid
    ref_str = request.POST['reference']
    ref = resource.reference(ref_str)
  except:
    log.info("User provided bad resource or reference. (res: %s; ref: )", res_str, ref_str)
    raise Http404
  # if tag name doesn't exist, create it
  try:
    t = get_exact_tag(request.user, tag_name)
  except:
    # TODO: move to models
    t = Tag(tag=tag_name, user=request.user)
    t.save()
  log.debug("Saving new tag %s %s %s %s", ref_str, tag_name, t, ref.pretty())
  # TODO: move to models
  new_ref = Reference(tag=t, resource=res_str, reference=ref.pretty(), 
      offset_start=ref.indices().start, offset_end=ref.indices().end, 
      user=request.user)
  new_ref.save()
  return HttpResponseRedirect(reverse('tagref_detail', args=(tag_name, str(new_ref.id))));
Ejemplo n.º 9
0
def post_save(post, args, request):
    post.url = args.get('url')
    post.title = args.get('title')
    post.body = args.get('body')
    post.published_at = args.get('published_at')
    post.save(request=request)

    post.tags.clear()
    from tags.models import Tag
    tags_raw = args.get('tags', '')
    for tag_title in tags_raw.split(','):
        tag_title = tag_title.strip(' \t\n\r')
        tag_slug = slugify(tag_title)

        if len(tag_title) == 0:
            # don't save empty tag
            continue

        try:
            tag = Tag.objects.get(slug=tag_slug)
        except Tag.DoesNotExist:
            tag = Tag(
                title=tag_title,
                slug=tag_slug,
            )
            tag.save(request=request)
        post.tags.add(tag.document)

    return post
Ejemplo n.º 10
0
def ask(request):
    ask_form = AskQuestion(request.POST or None)
    args = {}
    args['form'] = ask_form
    if request.POST and ask_form.is_valid():
        question = Question(text=ask_form.cleaned_data['text'], title=ask_form.cleaned_data['title'])
        tags = ask_form.cleaned_data['tags']

        g = Tag.objects.all()
        getTag = tags.split(', ')

        for tag in getTag:
            counter = 0
            for l in g:
                if l.tag == tag:
                    counter += 1
            if counter == 0:
                t = Tag(tag=tag)
                t.save()


        user = auth.get_user(request)
        question.author = user

        question.save()
        a = g.filter(tag__in=getTag)
        question.tags.add(*a)
        return redirect('questionGet', question_id=question.id)

    else:
        return render(request, 'ask.html', args)
Ejemplo n.º 11
0
def test_bookmarks_get_delete_url_returns_correct_url():
    user = make_users(1)[0]
    tag = Tag(title='Test Tag', slug='test-tag', user=user)
    tag.save()
    Bookmark(title='Test Bookmark', slug='test-bookmark', tag=tag,
             url="http://www.testers.com", user=user).save()
    bookmark = Bookmark.objects.get(pk=1)
    assert bookmark.get_delete_url() == '/bookmarks/delete/test-tag/test-bookmark/'
Ejemplo n.º 12
0
def test_bookmarks_unicode_method_returns_title_correctly():
    user = make_users(1)[0]
    tag = Tag(title='Test Tag', slug='test-tag', user=user)
    tag.save()
    Bookmark(title='Test Bookmark', slug='test-bookmark', tag=tag,
             url="http://www.testers.com", user=user).save()
    bookmark = Bookmark.objects.get(pk=1)
    assert bookmark.__unicode__() == 'Test Bookmark'
Ejemplo n.º 13
0
def test_edit_tag_form_is_valid():
    user = make_users(1)[0]
    tag = Tag(title='title', user=user)
    tag.save()
    form = EditTagForm({
        'title': 'test',
    }, user=user, instance=tag)
    assert form.is_valid()
Ejemplo n.º 14
0
def create_tag(request):
    name_zh = request.REQUEST.get('name_zh', '')
    description = request.REQUEST.get('desc', '')
    if not name_zh:
        raise Http404()

    Tag.create_tag(name_zh=name_zh, description=description)
    return HttpResponse("Success")
Ejemplo n.º 15
0
 def test_remove_tag_button(self):
     self.client.login(username='******', password='******')
     tag = Tag(tag_text='f')
     tag.save()
     AddonTag(addon=Addon.objects.get(pk=3615), tag=tag, user_id=999).save()
     r = self.client.get(reverse('addons.detail', args=[3615]))
     doc = pq(r.content)
     assert len(doc('#tags li input.removetag'))
Ejemplo n.º 16
0
    def save(self, addon, commit=True):
        if (self.cleaned_data.get('DELETE')
                and 'upload_hash' not in self.changed_data and self.promo.id):
            self.promo.delete()
        elif self.promo and 'upload_hash' in self.changed_data:
            self.promo.delete()
        elif self.cleaned_data.get('upload_hash'):
            super(AdminSettingsForm, self).save(addon, True)

        contact = self.cleaned_data.get('mozilla_contact')
        if contact:
            addon.update(mozilla_contact=contact)

        tags = self.cleaned_data.get('tags')
        if tags:
            tags_new = self.cleaned_data['tags']
            tags_old = [slugify(t, spaces=True) for t in self.get_tags(addon)]

            add_tags = set(tags_new) - set(tags_old)
            del_tags = set(tags_old) - set(tags_new)

            # Add new tags.
            for t in add_tags:
                Tag(tag_text=t).save_tag(addon)

            # Remove old tags.
            for t in del_tags:
                Tag(tag_text=t).remove_tag(addon)

        # Content ratings.
        ratings = self.cleaned_data.get('app_ratings')
        if ratings:
            ratings = [ALL_RATINGS()[int(i)] for i in ratings]

            # Delete content ratings with ratings body not in new set.
            r_bodies = set([rating.ratingsbody.id for rating in ratings])
            addon.content_ratings.exclude(ratings_body__in=r_bodies).delete()

            # Set content ratings, takes {<ratingsbody class>: <rating class>}.
            addon.set_content_ratings(
                dict((rating.ratingsbody, rating) for rating in ratings))
        else:
            addon.content_ratings.all().delete()

        geodata = addon.geodata
        geodata.banner_regions = self.cleaned_data.get('banner_regions')
        geodata.banner_message = self.cleaned_data.get('banner_message')
        geodata.save()

        toggle_game(addon)
        uses_flash = self.cleaned_data.get('flash')
        af = addon.get_latest_file()
        if af is not None:
            af.update(uses_flash=bool(uses_flash))

        index_webapps.delay([addon.id])

        return addon
Ejemplo n.º 17
0
    def save(self):
        addon = self.instance
        persona = addon.persona
        data = self.cleaned_data

        # Update Persona-specific data.
        persona_data = {
            'license': int(data['license']),
            'accentcolor': data['accentcolor'].lstrip('#'),
            'textcolor': data['textcolor'].lstrip('#'),
            'author': self.request.amo_user.username,
            'display_username': self.request.amo_user.name
        }
        changed = False
        for k, v in persona_data.iteritems():
            if v != getattr(persona, k):
                changed = True
                setattr(persona, k, v)
        if changed:
            persona.save()

        if self.changed_data:
            amo.log(amo.LOG.EDIT_PROPERTIES, addon)
        self.instance.modified = datetime.now()

        # Update Addon-specific data.
        changed = (
            set(self.old_tags) != data['tags'] or  # Check if tags changed.
            self.initial['slug'] != data['slug'] or  # Check if slug changed.
            transfield_changed('description', self.initial, data)
            or transfield_changed('name', self.initial, data))
        if changed:
            # Only save if addon data changed.
            super(EditThemeForm, self).save()

        # Update tags.
        tags_new = data['tags']
        tags_old = [slugify(t, spaces=True) for t in self.old_tags]
        # Add new tags.
        for t in set(tags_new) - set(tags_old):
            Tag(tag_text=t).save_tag(addon)
        # Remove old tags.
        for t in set(tags_old) - set(tags_new):
            Tag(tag_text=t).remove_tag(addon)

        # Update category.
        if data['category'].id != self.initial['category']:
            addon_cat = addon.addoncategory_set.all()[0]
            addon_cat.category = data['category']
            addon_cat.save()

        # Theme reupload.
        if not addon.is_pending():
            if data['header_hash'] or data['footer_hash']:
                save_theme_reupload.delay(data['header_hash'],
                                          data['footer_hash'], addon)

        return data
Ejemplo n.º 18
0
def test_edit_tag_form_is_invalid_due_to_no_title():
    user = make_users(1)[0]
    tag = Tag(title='title', user=user)
    tag.save()
    form = EditTagForm({
        'title': '',
    }, user=user, instance=tag)
    assert not form.is_valid()
    assert ['title'] == form.errors.keys()
Ejemplo n.º 19
0
 def setUp(self):
     u = UserProfile(username='******')
     u.save()
     t = Tag(tag_text='donkeybuttrhino')
     t.save()
     a = Addon.objects.all()[0]
     at = AddonTag(tag=t, user=u, addon=a)
     at.save()
     super(TagTest, self).setUp()
Ejemplo n.º 20
0
 def _create_tags_and_questions(self):
     for i in range(len(self.titles)):
         current_question = Question(id=i,
                                     title=self.titles[i],
                                     user_id=0,
                                     details=self.descriptions[i])
         current_question.save()
         tag = Tag(id=i, name=self.tags[i])
         tag.save()
Ejemplo n.º 21
0
    def save(self):
        for tag_title in self.tag_titles:
            tag_title = tag_title.lower()
            try:
                tag = Tag.objects.get(title=tag_title)
            except Tag.DoesNotExist:
                tag = Tag(title=tag_title)
                tag.save()

            yield tag
Ejemplo n.º 22
0
def test_edit_tag_form_saves_correctly():
    user = make_users(1)[0]
    tag = Tag(title='tag', user=user)
    tag.save()
    form = EditTagForm({
        'title': 'new name',
    }, user=user, instance=tag)
    assert form.is_valid()
    form.save()
    assert Tag.objects.get(pk=1).title == 'new name'
Ejemplo n.º 23
0
    def save(self):
        addon = self.instance
        persona = addon.persona
        data = self.cleaned_data

        # Update Persona-specific data.
        persona_data = {
            'license': int(data['license']),
            'accentcolor': data['accentcolor'].lstrip('#'),
            'textcolor': data['textcolor'].lstrip('#'),
            'author': self.request.amo_user.username,
            'display_username': self.request.amo_user.name
        }
        changed = False
        for k, v in persona_data.iteritems():
            if v != getattr(persona, k):
                changed = True
                setattr(persona, k, v)
        if changed:
            persona.save()

        if self.changed_data:
            amo.log(amo.LOG.EDIT_PROPERTIES, addon)
        self.instance.modified = datetime.now()

        # Save the Addon object.
        super(EditThemeForm, self).save()

        tags_new = data['tags']
        tags_old = [slugify(t, spaces=True) for t in self.get_tags(addon)]

        # Add new tags.
        for t in set(tags_new) - set(tags_old):
            Tag(tag_text=t).save_tag(addon)

        # Remove old tags.
        for t in set(tags_old) - set(tags_new):
            Tag(tag_text=t).remove_tag(addon)

        # Update category.
        try:
            old_cat = (addon.addoncategory_set
                       .exclude(category_id=data['category'].id))[0]
        except IndexError:
            # The category has remained unchanged.
            pass
        else:
            old_cat.category = data['category']
            old_cat.save()

        # Theme reupload.
        save_theme_reupload.delay(data['header_hash'], data['footer_hash'],
                                  addon)

        return data
Ejemplo n.º 24
0
def create(request):
    valid = True
    if request.method == 'POST':
        if request.POST['name'] == "":
            valid = False
    if request.method == 'POST' and valid:
        tag = Tag(name=request.POST['name'])
        tag.save()
        return render_to_response('tags/detail.html', {'tag': tag})
    else:
        return render(request, 'tags/create.html', {'valid': valid})
Ejemplo n.º 25
0
    def test_fix_tags(self):
        """
        Test the `fix_tags` utility function.
        """
        from pages.models import Page
        from tags.tag_utils import fix_tags

        #########################
        # Create some test regions
        #########################
       
        sf = Region(full_name="San Francisco Test", slug='sftest')
        sf.save()

        mission = Region(full_name="Mission", slug="mission")
        mission.save()

        #########################
        # Create some test tags
        #########################

        park = Tag(name='park', region=sf)
        park.save()

        fun = Tag(name='fun', region=sf)
        fun.save()

        #########################
        # Add the tags to a test page
        #########################

        page = Page(name="Duboce Park", content="<p>Park.</p>", region=sf)
        page.save()

        pts = PageTagSet(
            page=page,
            region=sf
        )
        pts.save()
        pts.tags.add(park)
        pts.tags.add(fun)
        pts.save()

        # Now do something odd and make one of the referenced `Tag`s point
        # to a different region than the PageTagSet.
        fun.region = mission
        fun.save()

        self.assertTrue(pts.tags.filter(region=mission).exists())

        # Then attempt a fix:
        fix_tags(sf, PageTagSet.objects.filter(id=pts.id))

        pts = PageTagSet.objects.get(page=page, region=sf)
        self.assertFalse(pts.tags.filter(region=mission).exists())

        # Check that this is fixed in historical versions as well
        for pts_h in pts.versions.all():
            self.assertFalse(pts_h.tags.filter(region=mission).exists())
Ejemplo n.º 26
0
    def handle(self, *args, **options):
        #i = 0
        #n = int(args[0])

        allTags = ['java', 'c++', 'incapsulation', 'programming', 'python',
                   'django', 'web', 'tags', 'questions', 'users', 'heap', 'ask']
        allTags.
        #for tagname in allTags:
        for i in range(len(allTags)):
            t = Tag(tag=allTags[i])
            t.save()
Ejemplo n.º 27
0
def create(request):
    valid = True
    if request.method == 'POST':
        if request.POST['name'] == "":
            valid = False
    if request.method == 'POST' and valid:
        tag = Tag(name=request.POST['name'])
        tag.save()
        return render_to_response('tags/detail.html', {'tag': tag})
    else:
        return render(request, 'tags/create.html', {'valid': valid})
Ejemplo n.º 28
0
def highlight(request):
  success = False
  user = request.user
  errors = {}
  data = {}

  if request.POST:
    url = process_url(request.POST.get('url'))
    highlight = request.POST.get('highlight')
    highlight_id = request.POST.get('highlight_id')
    tags = json.loads(request.POST.get('tags'))
    errors['add_highlight'] = []

    if highlight != "" or highlight_id:
      p = Page.objects.get(url=url)

      if highlight_id: 
        try:
          h = Highlight.objects.get(id=highlight_id)
          data['highlight_id'] = h.id
        except: 
          errors['add_highlight'].append('Get highlight failed')
      else:
        try:
          h, created = Highlight.objects.get_or_create(page=p, highlight=highlight)
          h.user = user
          h.save()

          success = True
          data['highlight_id'] = h.id
        except:
          errors['add_highlight'].append('Add highlight failed')

      if not len(errors['add_highlight']):
        for tag in tags:
          if len(Tag.objects.filter(highlight=h, common_tag__name=tag)) == 0:
            try:
              common_tag = CommonTag.objects.get(name=tag)
              vt = Tag(
                page=p, 
                highlight=h, 
                common_tag=common_tag,
                user=user, 
              )
              vt.save()
              success = True
            except CommonTag.DoesNotExist:
              errors['add_highlight'].append("Base tag " + tag + " does not exist")

  return {
    'success': success,
    'errors': errors,
    'data': data,
  }
Ejemplo n.º 29
0
 def populate(self):
     self.instance = Addon.objects.create(type=amo.ADDON_PERSONA,
         status=amo.STATUS_PUBLIC, slug='swag-overload',
         name='Bands Make Me Dance', summary='tha summary')
     self.cat = Category.objects.create(
         type=amo.ADDON_PERSONA, name='xxxx')
     self.instance.addoncategory_set.create(category=self.cat)
     self.license = amo.LICENSE_CC_BY.id
     Persona.objects.create(persona_id=0, addon_id=self.instance.id,
         license=self.license, accentcolor='C0FFEE', textcolor='EFFFFF')
     Tag(tag_text='sw').save_tag(self.instance)
     Tag(tag_text='ag').save_tag(self.instance)
Ejemplo n.º 30
0
def test_new_bookmark_form_is_valid():
    user = make_users(1)[0]
    tag = Tag(title='title', user=user)
    tag.save()
    form = NewBookmarkForm({
        'title': 'test',
        'description': 'description',
        'url': 'http://www.google.com',
        'tag': tag.pk,
        'favorited': True,
    }, user=user)
    assert form.is_valid()
Ejemplo n.º 31
0
    def save(self, addon, commit=True):
        if (self.cleaned_data.get('DELETE')
                and 'upload_hash' not in self.changed_data and self.promo.id):
            self.promo.delete()
        elif self.promo and 'upload_hash' in self.changed_data:
            self.promo.delete()
        elif self.cleaned_data.get('upload_hash'):
            super(AdminSettingsForm, self).save(addon, True)

        contact = self.cleaned_data.get('mozilla_contact')
        if contact:
            addon.update(mozilla_contact=contact)

        tags = self.cleaned_data.get('tags')
        if tags:
            tags_new = self.cleaned_data['tags']
            tags_old = [slugify(t, spaces=True) for t in self.get_tags(addon)]

            add_tags = set(tags_new) - set(tags_old)
            del_tags = set(tags_old) - set(tags_new)

            # Add new tags.
            for t in add_tags:
                Tag(tag_text=t).save_tag(addon)

            # Remove old tags.
            for t in del_tags:
                Tag(tag_text=t).remove_tag(addon)

            if add_tags or del_tags:
                index_webapps.delay([addon.id])

        ratings = self.cleaned_data.get('app_ratings')
        if ratings:
            before = set(
                addon.content_ratings.filter(rating__in=ratings).values_list(
                    'rating', flat=True))
            after = set(int(r) for r in ratings)
            addon.content_ratings.exclude(rating__in=after).delete()
            for i in after - before:
                r = ALL_RATINGS[i]
                ContentRating.objects.create(addon=addon,
                                             rating=r.id,
                                             ratings_body=r.ratingsbody.id)
        else:
            addon.content_ratings.all().delete()
        ban_game_in_brazil(addon)
        uses_flash = self.cleaned_data.get('flash')
        af = addon.get_latest_file()
        if af is not None:
            af.update(uses_flash=bool(uses_flash))
        return addon
Ejemplo n.º 32
0
def test_new_bookmark_form_is_invalid_due_to_bad_url():
    user = make_users(1)[0]
    tag = Tag(title='title', user=user)
    tag.save()
    form = NewBookmarkForm({
        'title': 'test',
        'description': 'description',
        'url': 'blah',
        'tag': tag.pk,
        'favorited': True,
    }, user=user)
    assert not form.is_valid()
    assert ['url'] == form.errors.keys()
Ejemplo n.º 33
0
def test_new_bookmark_form_saves_correctly():
    user = make_users(1)[0]
    tag = Tag(title='title', user=user)
    tag.save()
    form = NewBookmarkForm({
        'title': 'Test Bookmark',
        'description': 'description',
        'url': 'http://www.google.com',
        'tag': tag.pk,
        'favorited': True,
    }, user=user)
    assert form.is_valid()
    form.save()
    assert len(Bookmark.objects.all()) == 1
Ejemplo n.º 34
0
 def add_txt_tags(self, txt_tag_set):
     for txt_tag in txt_tag_set:
         try:
             tag = Tag(name=txt_tag)
             try:
                 tag = Tag.objects.get(name=txt_tag)
             except:
                 pass
             if self.active:
                 tag.obj_count += 1
             tag.save()
             self.tags.add(tag)
         except Exception, e:
             print str(e)
Ejemplo n.º 35
0
 def add_txt_tags(self, txt_tag_set):
     for txt_tag in txt_tag_set:
         try:
             tag = Tag(name=txt_tag)
             try:
                 tag = Tag.objects.get(name=txt_tag)
             except:
                 pass
             if self.active:
                 tag.obj_count += 1
             tag.save()
             self.tags.add(tag)
         except Exception, e:
             print str(e)
Ejemplo n.º 36
0
def test_new_bookmark_form_is_invalid_because_bookmark_exists():
    user = make_users(1)[0]
    tag = Tag(title='title', user=user)
    tag.save()
    Bookmark(title='Test Bookmark', slug='test-bookmark', user=user,
             description='', tag=tag, url='http://www.google.com').save()
    form = NewBookmarkForm({
        'title': 'Test Bookmark',
        'description': 'description',
        'url': 'http://www.google.com',
        'tag': tag.pk,
        'favorited': True,
    }, user=user)
    assert not form.is_valid()
    assert ['title'] == form.errors.keys()
Ejemplo n.º 37
0
def test_edit_bookmark_form_is_valid():
    user = make_users(1)[0]
    tag = Tag(title='title', user=user)
    tag.save()
    Bookmark(title='Test Bookmark', slug='test-bookmark', user=user,
             description='', tag=tag, url='http://www.google.com').save()
    bookmark = Bookmark.objects.get(pk=1)
    form = EditBookmarkForm({
        'title': 'Test Bookmark',
        'description': 'description',
        'url': 'http://www.google.com',
        'tag': tag.pk,
        'favorited': True,
    }, user=user, instance=bookmark)
    assert form.is_valid()
Ejemplo n.º 38
0
    def test_slug(self):
        t = Tag(name='Library of Congress', region=self.region)
        t.save()
        self.assertEqual(t.slug, 'libraryofcongress')

        t = Tag(name='Сочи 2014', region=self.region)
        t.save()
        self.assertEqual(t.slug, 'сочи2014'.decode('utf-8'))
Ejemplo n.º 39
0
def site_add(request):
    """
    :param request:
    :return:
    """
    msg_ok = ""
    msg_err = ""

    form = SiteForm()

    if request.method == 'POST':
        form = SiteForm(request.POST)
        if form.is_valid():
            f = form.save(commit=False)
            f.user = request.user
            f.save()

            Tag(name=f.tags).save()

            # admin
            msg = (u"Hi admin;\n\nNew site submit. {0}\n\n".format(f.title))
            msg += emailmsg
            send_mail("{0} | New web site".format(WEBSITE_NAME), msg,
                      DEFAULT_FROM_EMAIL, TO, True)

            msg_ok = u'Submit site successful.'
        else:
            msg_err = u'Attention! Please correct the mistake!'

    return render(request, "site_add.html", locals())
Ejemplo n.º 40
0
    def save(self, commit=False):
        from .tasks import create_persona_preview_image, save_persona_image
        # We ignore `commit`, since we need it to be `False` so we can save
        # the ManyToMany fields on our own.
        addon = super(NewPersonaForm, self).save(commit=False)
        addon.status = amo.STATUS_UNREVIEWED
        addon.type = amo.ADDON_PERSONA
        addon.save()
        addon._current_version = Version.objects.create(addon=addon,
                                                        version='0')
        addon.save()
        amo.log(amo.LOG.CREATE_ADDON, addon)
        log.debug('New persona %r uploaded' % addon)

        data = self.cleaned_data

        header = data['header_hash']
        footer = data['footer_hash']

        header = os.path.join(settings.TMP_PATH, 'persona_header', header)
        footer = os.path.join(settings.TMP_PATH, 'persona_footer', footer)
        dst = os.path.join(settings.PERSONAS_PATH, str(addon.id))

        # Save header, footer, and preview images.
        save_persona_image(src=header, dst=dst, img_basename='header.jpg')
        save_persona_image(src=footer, dst=dst, img_basename='footer.jpg')
        create_persona_preview_image(src=header, dst=dst,
                                     img_basename='preview.jpg',
                                     set_modified_on=[addon])

        # Save user info.
        user = self.request.amo_user
        AddonUser(addon=addon, user=user).save()

        p = Persona()
        p.persona_id = 0
        p.addon = addon
        p.header = 'header'
        p.footer = 'footer'
        if data['accentcolor']:
            p.accentcolor = data['accentcolor'].lstrip('#')
        if data['textcolor']:
            p.textcolor = data['textcolor'].lstrip('#')
        p.license_id = data['license']
        p.submit = datetime.now()
        p.author = user.name
        p.display_username = user.username
        p.save()

        # Save tags.
        for t in data['tags']:
            Tag(tag_text=t).save_tag(addon)

        # Save categories.
        tb_c = Category.objects.get(application=amo.THUNDERBIRD.id,
                                    name__id=data['category'].name_id)
        AddonCategory(addon=addon, category=data['category']).save()
        AddonCategory(addon=addon, category=tb_c).save()

        return addon
Ejemplo n.º 41
0
def dump_app(request, app_name, format):
    if app_name == 'reminders':
        reminder_list = Reminder.all()
    elif app_name == 'tags':
        tag_list = Tag.all()
    template = 'dumpdata/%s.%s' % (app_name, format)
    return render_to_response(request, template, locals())
Ejemplo n.º 42
0
    def update(self, request, pk=None, *args, **kwargs):
        try:
            obj = self.queryset.get(id=pk)
        except Link.DoesNotExist:
            return Response(
                'This link does not exist or you do not have permission to access it',
                status=404,
            )
        serializer = self.serializer_class(obj, data=request.data)

        if serializer.is_valid():
            m = serializer.save()

            try:
                tags_str = request.data['tags_str']
            except MultiValueDictKeyError:
                tags_str = None

            if tags_str:
                tags_list = [s.strip() for s in tags_str.split(',')]
                Tag.objects.bulk_create(
                    [Tag(link=m, name=tag.lower()) for tag in tags_list])

            return Response(LinkSerializer(m).data)

        else:
            return Response(serializer.errors, status=400)
Ejemplo n.º 43
0
    def create(self, request):
        serializer = self.serializer_class(data=request.data)

        if serializer.is_valid():
            url = request.data['url']
            parsed_uri = urlparse(url)
            domain = '{uri.netloc}'.format(uri=parsed_uri)
            domain = re.sub(r'(www.|.com)', '', string=domain)

            m = serializer.save(profile=request.user.profile, domain=domain)

            # Parse tags string and create tags for link
            try:
                tags_str = request.data['tags_str']
            except MultiValueDictKeyError:
                tags_str = None

            if tags_str:
                tags_list = [s.strip() for s in tags_str.split(',')]
                Tag.objects.bulk_create(
                    [Tag(link=m, name=tag.lower()) for tag in tags_list])

            return Response(LinkSerializer(m).data)

        else:
            return Response(serializer.errors, status=400)
Ejemplo n.º 44
0
def tag_request_detail(request, request_id):
	context = user_context(request)
	with connection.cursor() as c:
		manager = BaseDBManager()
		c.execute(REQUEST_TAG.request)
		context["tags_list"] = [Tag.from_db(d) for d in manager.fetch_dicts(c)]
	return render(request, 'dbrequests/list_users_or_tags.html', context)
Ejemplo n.º 45
0
 def test_q_is_tag(self):
     Tag(tag_text='whatsupp').save_tag(self.webapp)
     self.webapp.save()
     self.refresh('webapp')
     res = self.client.get(self.url + ({'q': 'whatsupp'}, ))
     eq_(res.status_code, 200)
     obj = res.json['objects'][0]
     eq_(obj['slug'], self.webapp.app_slug)
Ejemplo n.º 46
0
    def test_move_with_fks(self):
        ###########################################################
        # Moving should carry along files and FK'ed items that
        # point to it.
        ###########################################################

        p = Page(region=self.sf)
        p.content = "<p>A page with files and a map in SF.</p>"
        p.name = "Page With FKs"
        p.save()
        # Create a file that points at the page.
        pf = PageFile(file=ContentFile("foo"), name="file.txt", slug=p.slug, region=self.sf)
        pf.save()
        # Create a redirect that points at the page.
        redirect = Redirect(source="foobar", destination=p, region=self.sf)
        redirect.save()
        # Create a map that points at the page.
        points = GEOSGeometry("""MULTIPOINT (-122.4378964233400069 37.7971758820830033, -122.3929211425700032 37.7688207875790027, -122.3908612060599950 37.7883584775320003, -122.4056240844700056 37.8013807351830025, -122.4148937988299934 37.8002956347170027, -122.4183270263600036 37.8051784612779969)""")
        map = MapData(points=points, page=p, region=self.sf)
        map.save()
        # Add tags to page
        tagset = PageTagSet(page=p, region=self.sf)
        tagset.save()
        tag = Tag(name="tag1", region=self.sf)
        tag.save()
        tagset.tags.add(tag)

        move_to_region(self.oak, pages=[p])

        # Check to see that the related objects were moved.
        p = Page.objects.get(name="Page With FKs", region=self.oak)
        self.assertEqual(len(MapData.objects.filter(page=p, region=self.oak)), 1)
        self.assertEqual(len(p.pagetagset.tags.all()), 1)
        self.assertEqual(len(Redirect.objects.filter(destination=p, region=self.oak)), 1)
        self.assertEqual(len(PageFile.objects.filter(slug=p.slug, region=self.oak)), 1)

        # Check to see that version history was moved as well
        self.assertEquals(p.versions.all().count(), 1)
        self.assertEqual(len(MapData.versions.filter(page=p, region=self.oak)), 1)
        for pts in p.pagetagset.tags.all():
            self.assertEqual(pts.versions.all().count(), 1)
        self.assertEqual(len(Redirect.versions.filter(destination=p, region=self.oak)), 1)
        self.assertEqual(len(PageFile.versions.filter(slug=p.slug, region=self.oak)), 1)

        # ..and that the page is no longer in the SF region
        self.assertFalse(Page.objects.filter(region=self.sf, name="Page With FKs").exists())
Ejemplo n.º 47
0
 def test_tags_autogenerate_slugs(self):
     t = Tag(title='title with spaces')
     t.save()
     self.assertEqual(t.title, 'title-with-spaces')
     # saving the tag twice should not change its title
     t.save()
     self.assertEqual(t.title, 'title-with-spaces')
     # A second tag with the same title should return a different slug
     t2 = Tag(title='title with spaces')
     t2.save()
     self.assertEqual(t2.title, 'title-with-spaces-1')
     # Since we're using a different char to avoid collisions, we can also save tags with numbers
     G(Tag, title='Tag 4')
     G(Tag, title='Tag', n=4)
     G(Tag, title='Tag 7')
     G(Tag, title='Tag', n=4)
     self.assertEqual(Tag.objects.latest('pk').title, 'tag-10')
Ejemplo n.º 48
0
 def post(self, request: HttpRequest):
     tag = Tag.from_post_data(request.POST)
     if tag.id:
         Tag.objects.filter(id=tag.id).update(name=tag.name,
                                              description=tag.description)
     else:
         tag.save()
     return redirect("/tags")
Ejemplo n.º 49
0
def prepop_sorts(user):
    reader = csv.reader(open(settings.BASE_DIR+'/prepop/sorts.csv', 'U'), delimiter=',', quotechar='"')
    i = 0
    for row in reader:
        i+=1
        if i == 1:
            continue
       
        descr = row[0]
        icon = row[1]

        tset = Tag.objects.filter(descr=descr)
        if tset.count() > 0:
            continue
             
        t = Tag(descr=descr,creator=user,icon=icon)
        t.save()
Ejemplo n.º 50
0
    def test_not_blacklisted(self):
        """Make sure Tag Manager filters right for not blacklisted tags."""
        tag1 = Tag(tag_text='abc', blacklisted=False)
        tag1.save()
        tag2 = Tag(tag_text='swearword', blacklisted=True)
        tag2.save()

        eq_(Tag.objects.all().count(), 2)
        eq_(Tag.objects.not_blacklisted().count(), 1)
        eq_(Tag.objects.not_blacklisted()[0], tag1)
Ejemplo n.º 51
0
    def save(self, addon, commit=True):
        if (self.cleaned_data.get('DELETE') and
            'upload_hash' not in self.changed_data and self.promo.id):
            self.promo.delete()
        elif self.promo and 'upload_hash' in self.changed_data:
            self.promo.delete()
        elif self.cleaned_data.get('upload_hash'):
            super(AdminSettingsForm, self).save(addon, True)

        contact = self.cleaned_data.get('mozilla_contact')
        if contact is not None:
            addon.update(mozilla_contact=contact)

        vip = self.cleaned_data.get('vip_app')
        addon.update(vip_app=bool(vip))

        tags = self.cleaned_data.get('tags')
        if tags:
            tags_new = self.cleaned_data['tags']
            tags_old = [slugify(t, spaces=True) for t in self.get_tags(addon)]

            add_tags = set(tags_new) - set(tags_old)
            del_tags = set(tags_old) - set(tags_new)

            # Add new tags.
            for t in add_tags:
                Tag(tag_text=t).save_tag(addon)

            # Remove old tags.
            for t in del_tags:
                Tag(tag_text=t).remove_tag(addon)

        geodata = addon.geodata
        geodata.banner_regions = self.cleaned_data.get('banner_regions')
        geodata.banner_message = self.cleaned_data.get('banner_message')
        geodata.save()

        uses_flash = self.cleaned_data.get('flash')
        af = addon.get_latest_file()
        if af is not None:
            af.update(uses_flash=bool(uses_flash))

        index_webapps.delay([addon.id])

        return addon
Ejemplo n.º 52
0
def home(request):
    """ Uses index.html to display a list of all the user's tags """
    ctx = {}
    
    ctx["area"] = "tags"
    ctx["tags"] = make_page(Tag.by_user(request.user), request.GET.get("p"))
    ctx["untag_count"] = Bookmark.by_user(request.user).filter(tags=None).count()
    
    return TemplateResponse(request, "tags/index.html", ctx)
Ejemplo n.º 53
0
    def save(self, addon, commit=False):
        tags_new = self.cleaned_data['tags']
        tags_old = [slugify(t, spaces=True) for t in self.get_tags(addon)]

        # Add new tags.
        for t in set(tags_new) - set(tags_old):
            Tag(tag_text=t).save_tag(addon)

        # Remove old tags.
        for t in set(tags_old) - set(tags_new):
            Tag(tag_text=t).remove_tag(addon)

        # We ignore `commit`, since we need it to be `False` so we can save
        # the ManyToMany fields on our own.
        addonform = super(AddonFormBasic, self).save(commit=False)
        addonform.save()

        return addonform
Ejemplo n.º 54
0
 def test_existing_relation(self):
   tag1 = Tag(name="rock", count=50)
   tag2 = Tag(name="acoustics", count=35)
   
   tag1.save()
   tag2.save()
   
   rel = TagRelation(tag_to=tag1, tag_from=tag2, metric=0.7657)
   rel.save()
   
   self.assertEqual(rel, getRelation(tag1.name, tag2.name))
Ejemplo n.º 55
0
 def create_tag_tree(self):
     """
     Return the model's tags in a tree structure
     """
     tags = self.tags.all()
     tag_tree = Tag.create_tag_tree(Tag,tags)
     tag_tree = pickle.dumps(tag_tree)
     self.tag_tree = tag_tree
     self.save()
     return
Ejemplo n.º 56
0
def tagBlock(tag, **kwargs):
    """ Displays a tag block, for the tag list page
    
    Takes a tag, AddTagForm and RemoveTagForm.
    """
    kwargs["tag"] = tag
    kwargs["implies"] = Tag.expand_implies_check(tag.tags.all())
    kwargs["renametf"] = RenameTagForm(instance=tag)

    return kwargs
Ejemplo n.º 57
0
def create_tag():
    if current_user.is_not_admin():
        return jsonify(
            get_error_response('Permission denied, you must be admin',
                               status_code=401))

    name = request.form.get('name')
    description = request.form.get('description')

    tag = Tag(name=name, description=description)

    if 'images[]' in request.files:
        for image in request.files.getlist('images[]'):
            if image and validate_file_upload(image.filename):
                filename = secure_filename(image.filename)
                dir_path = app.config['IMAGES_LOCATION']
                dir_path = os.path.join((os.path.join(dir_path, 'tags')))

                if not os.path.exists(dir_path):
                    os.makedirs(dir_path)

                file_path = os.path.join(dir_path, filename)
                image.save(file_path)

                file_path = file_path.replace(
                    app.config['IMAGES_LOCATION'].rsplit(os.sep, 2)[0], '')
                if image.content_length == 0:
                    file_size = image.content_length
                else:
                    file_size = os.stat(file_path).st_size

                ti = TagImage(file_path=file_path,
                              file_name=filename,
                              original_name=image.filename,
                              file_size=file_size)
                tag.images.append(ti)

    db.session.add(tag)
    db.session.commit()

    return get_success_response(data=tag.get_summary(),
                                messages='Tag created successfully')