示例#1
0
 def post(self):
     """Create a new campaign."""
     campaign_dict = self.get_request_json()
     validate_campaign_dict(campaign_dict)
     # get a list of platforms
     platforms_list = campaign_dict["platforms"]
     del campaign_dict["platforms"]
     # construct and store a new campaign
     campaign = Campaign(**campaign_dict)
     campaign.put()
     campaign_id = campaign.key.id()
     # construct and store platforms for campaign
     platforms = []
     for platform_name in platforms_list:
         platform = Platform(name=platform_name,
                             counter=0,
                             campaign=campaign.key,
                             id="%d-%s" % (campaign_id, platform_name))
         platforms.append(platform)
     ndb.put_multi_async(platforms)
     # prepare response representation of the created campaign
     output = campaign_to_dict(campaign, platforms=platforms)
     # set the appropriate response headers
     self.response.location = self.uri_for("campaign-detail",
                                           campaign_id=campaign_id)
     self.response.status_int = 201
     return output
示例#2
0
def CreateCampaign():
    if 'file' not in request.files:
        return Response('no file found', status=400)
    file = request.files['file']
    if not allowed_file(file.filename):
        return Response('invalid file type', status=400)
    try:
        newCampaign = Campaign(
            request.form['name'] or None,
            f'/mediafiles/campaigns/{secure_filename(file.filename)}')
        if request.form['is_default'] == 'true':
            old_default = Campaign.query.filter_by(is_default=True).all()
            for camp in old_default:
                camp.is_default = False
            newCampaign.is_default = True
        db.session.add(newCampaign)
        db.session.commit()
        os.makedirs(
            f'/usr/src/app/mediafiles/campaigns/{newCampaign.name.replace(" ", "_")}',
            exist_ok=True)
        file.save(f'/usr/src/app{newCampaign.image}')
        data = jsonify(newCampaign.to_dict())
        data.status_code = 201
        return data
    except IntegrityError as error:
        return Response(error.args[0], status=400)
示例#3
0
    def test_parse_campaign(self):

        response = '''
            {"response":[
                {"id":"111","name":"Campaign1","status":0,"day_limit":2000,"all_limit":1000000,"start_time":"0","stop_time":"0"},
                {"id":"222","name":"Campaign2","status":1,"day_limit":6000,"all_limit":9000000,"start_time":"1298365200","stop_time":"1298451600"}
            ]}
            '''
        account = AccountFactory(remote_id=1)
        instance = Campaign(account=account, fetched=datetime.now())
        instance.parse(json.loads(response)['response'][0])
        instance.save(commit_remote=False)

        self.assertEqual(instance.remote_id, 111)
        self.assertEqual(instance.name, "Campaign1")
        self.assertEqual(instance.status, False)
        self.assertEqual(instance.day_limit, 2000)
        self.assertEqual(instance.all_limit, 1000000)
        self.assertEqual(instance.start_time, None)
        self.assertEqual(instance.stop_time, None)

        instance = Campaign(account=account, fetched=datetime.now())
        instance.parse(json.loads(response)['response'][1])
        instance.save(commit_remote=False)

        self.assertTrue(isinstance(instance.account, Account))
        self.assertEqual(instance.account.remote_id, 1)

        self.assertEqual(instance.remote_id, 222)
        self.assertEqual(instance.name, "Campaign2")
        self.assertEqual(instance.status, True)
        self.assertEqual(instance.day_limit, 6000)
        self.assertEqual(instance.all_limit, 9000000)
        self.assertEqual(instance.start_time, datetime(2011,2,22,12,0,0))
        self.assertEqual(instance.stop_time, datetime(2011,2,23,12,0,0))
示例#4
0
 def post(self, campaign_id):
     campaign = Campaign.get_by_key_name(campaign_id)
     if not campaign:
         campaign =  Campaign(key_name = campaign_id,
                             name = campaign_id,
                             short_code = campaign_id)
         campaign.put()
         status_view = CampaignStatusView(campaign = campaign, response = self.response)
示例#5
0
 def post(self):
     user = users.get_current_user()
     if user:
         name = self.request.get('name')
         c = Campaign(name=name,owner=user)
         c.put()
         return self.redirect("/campaign/%s" % c.key().id())
     else:
         return self.redirect(users.create_login_url(self.request.uri))
示例#6
0
 def post(self, campaign_id):
     campaign = Campaign.get_by_key_name(campaign_id)
     if not campaign:
         campaign = Campaign(key_name=campaign_id,
                             name=campaign_id,
                             short_code=campaign_id)
         campaign.put()
         status_view = CampaignStatusView(campaign=campaign,
                                          response=self.response)
示例#7
0
 def post(self):
     user = users.get_current_user()
     if user:
         name = self.request.get('name')
         c = Campaign(name=name, owner=user)
         c.put()
         return self.redirect("/campaign/%s" % c.key().id())
     else:
         return self.redirect(users.create_login_url(self.request.uri))
示例#8
0
async def post_newsletter_to_mailing_list(post: Newsletter):
    mail_list = list(
        map(lambda row: row[EMAIL_KEY], data.get_all_emails_unpaginated()))
    await newsletter(mail_list, post.subject, post.body)
    campaign = Campaign(subject=post.subject,
                        body=post.body,
                        template=post.template,
                        sent_to=mail_list)
    data.add_campaign(campaign.dict())
    return {"msg": "success"}
示例#9
0
 def post(self,campaign_id):
     user = users.get_current_user()
     if not user:
         return self.redirect(users.create_login_url(self.request.uri))
     name = self.request.get('name',None)
     target_url = self.request.get('target_url',None)
     priority = self.request.get('priority',None)
     img = self.request.POST['img']
     alt_text = self.request.get('alt_text',None)
     title_text = self.request.get('title_text',None)
     if not target_url  or not img.value:
         return self.get(campaign_id,['Faltan campos obligatorios',])
     campaign = Campaign.get_by_id(int(campaign_id))
     ad = ImgAdvert(
         name = name,
         target_url=target_url,
         priority=int(priority),
         img=img.value,
         mimetype=img.type,
         alt_text = alt_text,
         title_text = title_text,
         campaign = campaign)
     ad.put()
     if ad.is_saved():
         return self.redirect(webapp2.uri_for('advert.view',advert_id=ad.key().id()))
     self.response.set_status(500)
示例#10
0
 def post(self,campaign_id):
     user = users.get_current_user()
     if not user:
         return self.redirect(users.create_login_url(self.request.uri))
     name = self.request.get('name',None)
     target_url = self.request.get('target_url',None)
     priority = self.request.get('priority',None)
     title = self.request.get('title',None)
     description_text_line_1 = self.request.get('description_text_line_1',None)
     description_text_line_2 = self.request.get('description_text_line_2',None)
     visible_url = self.request.get('visible_url',None)
     if not target_url or not title or not description_text_line_1:
         return self.get(campaign_id,['Faltan campos obligatorios',])
     campaign = Campaign.get_by_id(int(campaign_id))
     ad = TextAdvert(
         name = name,
         target_url=target_url,
         priority=int(priority),
         title=title,
         description_text_line_1=description_text_line_1,
         description_text_line_2=description_text_line_2,
         visible_url = visible_url,
         campaign=campaign)
     ad.put()
     if ad.is_saved():
         return self.redirect(webapp2.uri_for('advert.view',advert_id=ad.key().id()))
     self.response.out.write("Error Raro")
示例#11
0
 def post(self, campaign_id):
     user = users.get_current_user()
     if not user:
         return self.redirect(users.create_login_url(self.request.uri))
     name = self.request.get('name', None)
     target_url = self.request.get('target_url', None)
     priority = self.request.get('priority', None)
     title = self.request.get('title', None)
     description_text_line_1 = self.request.get('description_text_line_1',
                                                None)
     description_text_line_2 = self.request.get('description_text_line_2',
                                                None)
     visible_url = self.request.get('visible_url', None)
     if not target_url or not title or not description_text_line_1:
         return self.get(campaign_id, [
             'Faltan campos obligatorios',
         ])
     campaign = Campaign.get_by_id(int(campaign_id))
     ad = TextAdvert(name=name,
                     target_url=target_url,
                     priority=int(priority),
                     title=title,
                     description_text_line_1=description_text_line_1,
                     description_text_line_2=description_text_line_2,
                     visible_url=visible_url,
                     campaign=campaign)
     ad.put()
     if ad.is_saved():
         return self.redirect(
             webapp2.uri_for('advert.view', advert_id=ad.key().id()))
     self.response.out.write("Error Raro")
示例#12
0
 def post(self, campaign_id):
     user = users.get_current_user()
     if not user:
         return self.redirect(users.create_login_url(self.request.uri))
     name = self.request.get('name', None)
     target_url = self.request.get('target_url', None)
     priority = self.request.get('priority', None)
     img = self.request.POST['img']
     alt_text = self.request.get('alt_text', None)
     title_text = self.request.get('title_text', None)
     if not target_url or not img.value:
         return self.get(campaign_id, [
             'Faltan campos obligatorios',
         ])
     campaign = Campaign.get_by_id(int(campaign_id))
     ad = ImgAdvert(name=name,
                    target_url=target_url,
                    priority=int(priority),
                    img=img.value,
                    mimetype=img.type,
                    alt_text=alt_text,
                    title_text=title_text,
                    campaign=campaign)
     ad.put()
     if ad.is_saved():
         return self.redirect(
             webapp2.uri_for('advert.view', advert_id=ad.key().id()))
     self.response.set_status(500)
示例#13
0
    def get(self, campaign_id, platform_name):
        """
        Handles incoming clicks for given campaign_id and platform_name.
        If click is valid then user is redirected to url defined in the campaign
        and statistic about this click is saved. All invalid clicks (e.g. for non
        existing campaigns, platforms) users are redirected to http://outfit7.com.
        """
        # cast campaign_id, type checking is done through route definition
        try:
            campaign_id = int(campaign_id)
        except ValueError:
            return webapp2.redirect("http://outfit7.com", permanent=True)

        platform_id = "%d-%s" % (campaign_id, platform_name)
        platform = Platform.get_by_id(platform_id)
        if platform:
            memcache.incr(platform_id, 1, namespace="counters", initial_value=0)
            try:
                deferred.defer(Platform.increment, platform_id, _countdown=TRACKER_COUNTER_UPDATE_INTERVAL_LENGTH,
                               _name="%s-%d" % (platform_id, get_interval_index()))
            except (taskqueue.TaskAlreadyExistsError, taskqueue.TombstonedTaskError), e:
                pass
            # TODO: optimize with async operations
            campaign = Campaign.get_by_id(campaign_id)
            return webapp2.redirect(campaign.link.encode("utf8"))
示例#14
0
    def setUp(self):
        app = create_app(test_config)

        with app.app_context():
            db.drop_all()
            db.create_all()

        self.app = app.test_client()
        self.app_context = app.app_context()
        self.app_context.push()

        guild = Guild('Flames of Exile')
        db.session.add(guild)
        db.session.commit()
        foe_guild = db.session.query(Guild).filter_by(
            name='Flames of Exile').first()

        admin = User('DiscordBot', sha256_crypt.encrypt('admin'), foe_guild.id,
                     User.Role.ADMIN)
        admin.discord_confirmed = True
        db.session.add(admin)
        db.session.commit()

        campaign = Campaign('campaign_name',
                            '/mediafiles/campaigns/campaign.png', True)
        db.session.add(campaign)
        db.session.commit()

        world = World('world_name',
                      '/mediafiles/campaigns/campaign_name/world.png', 1, 1, 1,
                      1)
        db.session.add(world)
        db.session.commit()

        pin = Pin(1, 1, Pin.Symbol.ANIMAL, Pin.Resource.WOLF, 1, 1, '', 1, 1,
                  'notes', 1, 1)
        db.session.add(pin)
        db.session.commit()

        edit = Edit("", 1, 1)
        db.session.add(edit)
        db.session.commit()

        event = Event('event', 'game',
                      datetime.datetime.now().isoformat(), 'note')
        db.session.add(event)
        db.session.commit()

        self.DEFAULT_GUILD = guild
        self.DEFAULT_USER = admin
        self.DEFAULT_CAMPAIGN = campaign
        self.DEFAULT_WORLD = world
        self.DEFAULT_PIN = pin
        self.DEFAULT_TOKEN = f'Bearer {self.login("DiscordBot", "admin").get_json()["token"]}'
        self.DEFAULT_EVENT = event

        self.maxDiff = None

        self.assertEqual(app.debug, False)
示例#15
0
    def put(self, campaign_id):
        """Update the existing campaign."""
        campaign_id = int(campaign_id)
        future = Campaign.get_by_id_async(campaign_id)
        campaign_dict = self.get_request_json()
        validate_campaign_dict(campaign_dict, all_required=False)

        campaign = future.get_result()

        platforms = []
        # get a list of existing campaign platforms
        existing_platforms_list = {
            platform.name: platform
            for platform in Platform.query(
                Platform.campaign == campaign.key).fetch(3)
        }

        # special processing for platforms field
        platforms_to_store = []
        if "platforms" in campaign_dict:
            # get a list of platforms from the request
            platforms_list = campaign_dict["platforms"]
            del campaign_dict["platforms"]
            # construct platforms for campaign
            for platform_name in platforms_list:
                if platform_name not in existing_platforms_list:
                    platform = Platform(name=platform_name,
                                        counter=0,
                                        campaign=campaign.key,
                                        id="%d-%s" %
                                        (campaign_id, platform_name))
                    platforms_to_store.append(platform)
                else:
                    platform = existing_platforms_list[platform_name]
                platforms.append(platform)
        else:
            # no changes to platforms field, just copy
            for platform in existing_platforms_list.values():
                platforms.append(platform)

        # update the rest of the fields
        for field_name in campaign_dict:
            setattr(campaign, field_name, campaign_dict[field_name])
        campaign.update_date = datetime.now()

        @ndb.transactional_async(xg=True)
        def _update():
            """Do the update in transaction"""
            ndb.put_multi_async(platforms_to_store)
            campaign.put_async()

        future = _update()

        output = campaign_to_dict(campaign, platforms=platforms)
        # explicitly do the json conversion here, while we may be waiting for the _update to finish
        output = json.dumps(output, default=json_serial, sort_keys=True)
        future.get_result()
        return output
示例#16
0
def comments():
    if request.method == "POST":
        usernames = [
            u.strip() for u in request.form.get("usernames").split(",")
        ]
        comment = request.form.get("comment")
        api = instagram.client.InstagramAPI(
            access_token=current_user.access_token)  #,
        #client_ips="127.0.0.1",
        #client_secret=INSTAGRAM_SECRET)
        campaign = Campaign(current=False,
                            like_campaign=False,
                            comment=comment,
                            user=current_user)
        session.add(campaign)
        session.commit()
        for username in usernames:
            user = api.user_search(q=username)[0]
            prospect = session.query(Prospect).filter_by(\
                    username=user.username).first()
            if not prospect:
                prospect = Prospect(
                    username=user.username,
                    instagram_id=user.id,
                )
                session.add(prospect)
            prospect_profile = ProspectProfile(campaign=campaign,
                                               prospect=prospect,
                                               done=False,
                                               followed_back=False)
            session.add(prospect_profile)
            session.commit()
        soon = datetime.datetime.now() + datetime.timedelta(minutes=1)
        logging.basicConfig()
        scheduler = get_scheduler()
        job = update_comments.delay(campaign.id, api)
        campaign.job_id = job.id
        session.commit()
        campaigns = session.query(Campaign).filter_by(user=current_user, \
                like_campaign=False)
    else:
        campaigns = session.query(Campaign).filter_by(user=current_user, \
                like_campaign=False)

    return render_template("comments.html", campaigns=campaigns)
示例#17
0
def campaignDelete(id):

    campaign = Campaign()
    campaign = Campaign.query.filter_by(id=id).first()
    borrado = campaign
    db.session.delete(campaign)  #PASOXXX
    db.session.commit()

    return jsonify('Campaña borrada'), 200
示例#18
0
def comments():
    if request.method == "POST":
        usernames = [u.strip() for u in
                request.form.get("usernames").split(",")]
        comment = request.form.get("comment")
        api = instagram.client.InstagramAPI(access_token=current_user.access_token)#,
                                            #client_ips="127.0.0.1",
                                            #client_secret=INSTAGRAM_SECRET)
        campaign = Campaign(current=False,
                        like_campaign=False,
                        comment=comment,
                        user=current_user)
        session.add(campaign)
        session.commit()
        for username in usernames:
            user = api.user_search(q=username)[0]
            prospect = session.query(Prospect).filter_by(\
                    username=user.username).first()
            if not prospect:
                prospect = Prospect(
                        username=user.username,
                        instagram_id=user.id,
                        )
                session.add(prospect)
            prospect_profile = ProspectProfile(
                    campaign=campaign,
                    prospect=prospect,
                    done=False,
                    followed_back=False)
            session.add(prospect_profile)
            session.commit()
        soon = datetime.datetime.now() + datetime.timedelta(minutes=1)
        logging.basicConfig()
        scheduler = get_scheduler()
        job = update_comments.delay(campaign.id, api)
        campaign.job_id=job.id
        session.commit()
        campaigns = session.query(Campaign).filter_by(user=current_user, \
                like_campaign=False)
    else:
        campaigns = session.query(Campaign).filter_by(user=current_user, \
                like_campaign=False)

    return render_template("comments.html", campaigns=campaigns)
示例#19
0
 def get(self, campaign_id, type='text'):
     model = TextAdvert
     f = text_json
     if type == 'image':
         model = ImgAdvert
         f = img_json
     c = Campaign.get_by_id(int(campaign_id))
     q = model.all().filter('campaign', c)
     count = model.all().filter('campaign', c).count()
     rdm = random.randint(0, count - 1)
     self.response.out.write(f(q.fetch(limit=1, offset=rdm)[0]))
示例#20
0
 def get(self,campaign_id,type='text'):
     model = TextAdvert
     f = text_json
     if type == 'image':
         model = ImgAdvert
         f = img_json
     c = Campaign.get_by_id(int(campaign_id))
     q = model.all().filter('campaign',c)
     count = model.all().filter('campaign',c).count()
     rdm = random.randint(0,count-1)
     self.response.out.write(f(q.fetch(limit=1,offset=rdm)[0]))
示例#21
0
 def get(self,campaign_id):
     c = Campaign.get_by_id(int(campaign_id))
     user = users.get_current_user()
     if c:
         if c.owner == user:
             ads = Advert.all().filter('campaign',c)
             self.response.out.write(template.render('templates/campaigns/view.html',{'campaign':c,'ads':ads}))
         else:
             self.response.out.write("No tenes permisos")
     else:
         self.response.out.write("La campania no existe")
示例#22
0
def create_campaign_and_redirect(request):
    campaign_name = request.GET.get("campaign_name_field", None)
    rule_set_pk = request.GET.get("rule_set_field", None)

    #generate access code
    size = 8
    chars = string.ascii_uppercase + string.digits
    while True:
        code = ''.join(random.choice(chars) for _ in range(size))
        if Campaign.objects.filter(access_code=code).count() is 0:
            break

    new_campaign = Campaign(rule_set=RuleSet.objects.get(pk=rule_set_pk),
                            name=campaign_name,
                            owning_user=request.user,
                            access_code=code)
    new_campaign.save()

    #redirect to the gm_session page
    return HttpResponseRedirect(reverse('gm_session', args=[new_campaign.pk]))
def run(maxPages, persist, campaignName=None, query=None):
    """
    Get labels first before attempting to do searches and then find labels
    are missing.

    :param maxPages: Count.
    :param persist: Flag.
    :param campaignName: Custom campaign name to label tweets with.
    :param query: Search query.

    :return: Tuple of processed profile and tweet counts.
    """
    global API_CONN

    utilityCampaignRec = Campaign.getOrCreate(UTILITY_CAMPAIGN, None)

    if query:
        customCampaignRec = None
    else:
        customCampaignRec = Campaign.getOrRaise(campaignName)
        query = customCampaignRec.searchQuery
        assert query, ("Use the Campaign Manager to set a search query"
                       " for the campaign: {0}".format(campaignName))

    # Process the category and campaign records above before fetching
    # data from the API.
    print("Search query: {0}".format(query))

    # Use app auth here for up to 480 search requests per window, rather
    # than 180 when using the user auth.
    API_CONN = lib.twitter_api.authentication.getAppOnlyConnection()
    profileCount, tweetCount = searchStoreAndLabel(
        query,
        maxPages,
        persist,
        utilityCampaignRec,
        customCampaignRec,
    )

    return profileCount, tweetCount
示例#24
0
 def get(self, campaign_id):
     """
     Display information about the existing campaign.
     :param campaign_id: ID of the campaign.
     """
     campaign_id = int(campaign_id)
     campaign = Campaign.get_by_id(campaign_id)
     if campaign:
         return campaign_to_dict(campaign)
     else:
         raise TrackerException("Campaign with id %s does not exist." %
                                campaign_id,
                                status_code=404)
示例#25
0
    def get(self):
        """List all existing campaigns."""
        @ndb.tasklet
        def callback(campaign):
            platforms = yield Platform.query(
                Platform.campaign == campaign.key,
                projection=[Platform.name, Platform.counter
                            ]).order(Platform.name).fetch_async(3)
            raise ndb.Return(campaign_to_dict(campaign, platforms=platforms))

        query = Campaign.query()
        output = query.map(callback)
        return output
示例#26
0
    def mutate(self, info, user_email, campaign_name):
        session = Session()
        campaign = Campaign(user_email=user_email, campaign_name=campaign_name)
        session.add(campaign)
        session.commit()
        campaign_id = campaign.id
        session.close()

        return CreateCampaign(
            id=campaign_id,
            campaign_name=campaign_name,
            user_email=user_email,
        )
示例#27
0
    def setUp(self):
        app = create_app(test_config)

        with app.app_context():
            db.drop_all()
            db.create_all()

        self.app = app
        self.test_client = app.test_client()
        self.app_context = app.app_context()
        self.app_context.push()

        self.socketio = SocketIO(app)

        self.socketio.on_event('connect', on_connect)
        self.socketio.on_event('campaign-update', handle_campaign_update)

        guild = Guild('Flames of Exile')
        db.session.add(guild)
        db.session.commit()
        foe_guild = db.session.query(Guild).filter_by(
            name='Flames of Exile').first()

        admin = User('DiscordBot', sha256_crypt.encrypt('admin'), foe_guild.id,
                     User.Role.ADMIN)
        admin.discord_confirmed = True
        db.session.add(admin)
        db.session.commit()

        campaign = Campaign('campaign_name', '/mediafiles/campaign.png', True)
        db.session.add(campaign)
        db.session.commit()

        self.campaign = campaign.to_dict()

        self.maxDiff = None

        self.assertEqual(app.debug, False)
示例#28
0
 def get(self, campaign_id):
     c = Campaign.get_by_id(int(campaign_id))
     user = users.get_current_user()
     if c:
         if c.owner == user:
             ads = Advert.all().filter('campaign', c)
             self.response.out.write(
                 template.render('templates/campaigns/view.html', {
                     'campaign': c,
                     'ads': ads
                 }))
         else:
             self.response.out.write("No tenes permisos")
     else:
         self.response.out.write("La campania no existe")
示例#29
0
def index_page(request, *args, **kwargs):
    response = webapp2.Response()
    user = users.get_current_user()
    #response.write("<a href='%s'>Home</a>" % webapp2.uri_for('home'))
    campaigns = None
    if user:
        url = users.create_logout_url(request.uri)
        link_text = "Logout"
        campaigns = Campaign.all().filter('owner',user)
    else:
        url = users.create_login_url(request.uri)
        link_text = "Login"
    response.write(template.render('templates/pages/index.html',{'user':user,'url':url,'link_text':link_text,'campaigns':campaigns}))
    #self.response.out.write(template.render('templates/campaigns/new.html',{}))
    return response
示例#30
0
def test_api_request():
    if 'credentials' not in flask.session:
        return flask.redirect('authorize')

    # Load credentials from the session.
    credentials = google.oauth2.credentials.Credentials(
        **flask.session['credentials'])

    gmail = googleapiclient.discovery.build(API_SERVICE_NAME,
                                            API_VERSION,
                                            credentials=credentials)
    flask.session['credentials'] = credentials_to_dict(credentials)

    # get the user profile using Gmail API
    userProfile = gmail.users().getProfile(userId="me").execute()
    # create a User object with the data provided by Gmail API
    user = User.query.filter_by(email=userProfile['emailAddress']).first()
    flask.session['fromEmail'] = userProfile['emailAddress']

    # add user to DB if not present already
    if not user:
        user = User(email=userProfile['emailAddress'],
                    unique_id=uuid.uuid4().hex)
        db.session.add(user)
        db.session.commit()

    form = DripEmailBasicDetailsForm(request.form)
    if request.method == 'POST' and form.validate():
        # create a Campaign object based on the form data.
        campaign = Campaign(title=form.title.data,
                            stages=form.noOfStages.data,
                            frequency=2,
                            recipients=form.receiverList.data,
                            user_id=user.unique_id,
                            unique_id=uuid.uuid4().hex)

        # store some session variables to be used in emailTemplate form
        flask.session['campaign_id'] = campaign.unique_id
        flask.session['campaign'] = campaign.title
        flask.session['frequency'] = campaign.stages

        # add campaign to DB
        db.session.add(campaign)
        db.session.commit()
        flash('Thanks for registering')
        return flask.redirect(flask.url_for('addEmail'))
    return render_template('register.html', form=form)
示例#31
0
    def delete(self, campaign_id):
        """Delete the existing campaign."""
        campaign_id = int(campaign_id)
        campaign = Campaign.get_by_id(campaign_id)

        if campaign:
            # delete the campaign first, so that updates are not possible
            futures = [campaign.key.delete_async()]
            # delete all platforms that correspond to the campaign
            futures.extend(
                ndb.delete_multi_async([
                    platform.key for platform in Platform.query(
                        Platform.campaign == campaign.key).fetch(3)
                ]))
            Future.wait_all(futures)
        else:
            # the campaign does not exist, just send 204
            self.response.status_int = 204
示例#32
0
文件: views.py 项目: demidov91/curs4
def create_campaign(request):
    if request.method == 'POST':
        campaign = Campaign(client=request.user)
        form = CampaignForm(request.POST, request.FILES, instance=campaign)
        if form.is_valid():
            campaign = form.save()
            if campaign.id:
                return redirect('client_index')
    if request.method == 'GET':
        form = CampaignForm()
    form.fields[
        'contacts'].widget = django.forms.widgets.CheckboxSelectMultiple(
            choices=((c.username, c.username)
                     for c in get_profile(request.user).knows.all()))
    transaction.commit()
    return render(request, 'new_campaign.html', {
        'form': form,
    })
示例#33
0
def create_campaign():
    return_url = request.referrer or '/'
    form = CreateCampaignForm()
    if form.validate_on_submit():
        if validate_name(form.name.data):
            campaign = Campaign(name=form.name.data,
                                city=form.city.data,
                                start_date=form.start_date.data,
                                is_active=True,
                                goal=form.goal.data)
            flash(f'!קמפיין "{campaign.name}" נוצר בהצלחה', 'success')
            db.session.add(campaign)
            db.session.commit()
            return redirect(url_for('home'))
        form.name.errors.append('קמפיין בשם הזה כבר קיים, אנא בחר שם אחר.')
    return render_template('/create_campaign.html',
                           form=form,
                           legend="יצירת קמפיין",
                           return_url=return_url)
示例#34
0
文件: views.py 项目: PESTLab/team-b
def newcamp():
    if ((g.user.role != ROLE_SALESEXEC) and (g.user.role != ROLE_ADMIN)):
        flash(
            'Only an Administrator or Users with Web Developer Roles can access this page'
        )
        return redirect(url_for('index'))

    form = newcampaign()

    if form.validate_on_submit():

        camp = Campaign(creator_id=g.user.id, name=form.campaignname.data)

        checkcamp = findcamp_byname(camp.name)

        if not checkcamp:

            db.session.add(camp)
            db.session.commit()

            url = api_url + '/fmapi/addcamp'
            data = {'id': camp.id, 'campname': camp.name, 'funids': 'none'}
            headers = {
                'Content-type': 'application/json',
                'Accept': 'text/plain'
            }
            r = requests.post(url,
                              data=json.dumps(data),
                              headers=headers,
                              auth=('unibluefm', '123456789'))

            return redirect(url_for('managecamp', cid=camp.id))
        else:
            flash(
                'A campaign with the same name already exists, please chose another name'
            )
            return render_template('newcampaign1.html',
                                   title='Add New Campaign',
                                   form=form)

    return render_template('newcampaign1.html',
                           title='Add New Campaign',
                           form=form)
示例#35
0
def index_page(request, *args, **kwargs):
    response = webapp2.Response()
    user = users.get_current_user()
    #response.write("<a href='%s'>Home</a>" % webapp2.uri_for('home'))
    campaigns = None
    if user:
        url = users.create_logout_url(request.uri)
        link_text = "Logout"
        campaigns = Campaign.all().filter('owner', user)
    else:
        url = users.create_login_url(request.uri)
        link_text = "Login"
    response.write(
        template.render(
            'templates/pages/index.html', {
                'user': user,
                'url': url,
                'link_text': link_text,
                'campaigns': campaigns
            }))
    #self.response.out.write(template.render('templates/campaigns/new.html',{}))
    return response
示例#36
0
def home():
    if request.method == "POST":
        username = request.form.get("username")
        api = instagram.client.InstagramAPI(
            access_token=current_user.access_token)  #,
        #client_ips="127.0.0.1",
        #client_secret=INSTAGRAM_SECRET)
        user = api.user_search(q=username)[0]
        campaign = Campaign(current=False,
                            username=user.username,
                            instagram_id=user.id,
                            like_campaign=True,
                            user=current_user)
        session.add(campaign)
        session.commit()
        campaigns = session.query(Campaign).filter_by(user=current_user, \
                like_campaign=True)
    else:
        campaigns = session.query(Campaign).filter_by(user=current_user, \
                like_campaign=True)

    return render_template("home.html", campaigns=campaigns)
示例#37
0
def send_async_email(camp_title,recipients,template,temp_var,email):
	with app.app_context():
		user = User.query.filter_by(user_id=email).all()
		credentials = dict(json.loads(user[0].credentials))
		credentials = google.oauth2.credentials.Credentials(**credentials)
		user[0].credentials = json.dumps(credentials_to_dict(credentials))
		db.session.commit()
		for key in temp_var:
			if key in template:
				template = template.replace(key,temp_var[key])
		gmail_service = googleapiclient.discovery.build("gmail", "v1", credentials=credentials)
		message = MIMEText(template)
		message['to'] = recipients
		message['from'] = email
		message['subject'] = camp_title
		body = {'raw': base64.b64encode(message.as_string())}
		try:
			camp_obj = Campaign.query.filter_by(camp_title=camp_title).all()
			#if reply of previous followup detected .. send no further mails
			if camp_obj and camp_obj[0].thread_id and reply_detect(camp_obj[0].thread_id,email,credentials):
				print "Reply detected."
				return
			message = gmail_service.users().messages().send(userId=email, body=body).execute()
			thread_id = message["threadId"]
			# if campaign does not exist.. create one
			if not camp_obj:
				new_camp_obj = Campaign(camp_title,thread_id)
				db.session.add(new_camp_obj)
				db.session.commit()
			# else update to thread id of last mail to current one.
			else:
				camp_obj[0].thread_id = thread_id
				db.session.commit()

		except Exception as error:
			print "Error occured" + str(error)
示例#38
0
文件: app.py 项目: montrealist/delvr2
def create_campaign():
    if "user_id" not in session:
        flash("Please login first!")
        return redirect('/login')

    form = CampaignForm()

    if form.validate_on_submit():
        title = form.title.data
        description = form.description.data
        max_players = form.max_players.data
        
        campaign = Campaign(
        title=title, 
        description=description, 
        max_players=max_players, 
        user_id=session['user_id']
        )

        db.session.add(campaign)   
        db.session.commit()
        return redirect('/campaigns')
    
    return render_template('new_campaign.html', form=form)
示例#39
0
                                   fill=c)
                draw.rectangle([(margin, h - margin - height),
                                (w - margin, h - margin)],
                               outline="black",
                               width=1)
            else:
                draw.rectangle([(margin, h - margin - height),
                                (w - margin, h - margin)],
                               outline="black",
                               width=1,
                               fill=country.colors[0])
            font_margin = 8
            draw.text(
                (margin + font_margin, h - margin - height + font_margin),
                str(start_date.year),
                font=self.font,
                fill='white')
            draw.text((w - margin - 42, h - margin - height + font_margin),
                      str(end_date.year),
                      font=self.font,
                      fill='white')
        out = out.resize(np.array(out.size) * resize_ratio, Image.BILINEAR)
        out.save(f"{ASSETS_DIR}/heatmap.png")


if __name__ == '__main__':
    analyzer = Analyzer()
    campaign = Campaign.from_file(f"{ASSETS_DIR}/Bharat.json",
                                  player_only=True)
    analyzer.analyze(campaign)
示例#40
0
文件: grabber.py 项目: nickhs/poodle
import bootstrap
from models import Campaign

actives = Campaign.get_active()
urls = []

f = open('urls.txt', 'w')

for active in actives:
    rewards = active.get_reward_groups()
    for reward in rewards:
        url = reward.image_url
        urls.append(url)

for url in urls:
    f.write(url + '\n')
    print url

f.close()
示例#41
0
def add_campaign(data_list):
    player = Player.objects.get(id=data_list['dungeon_master'])
    campaign = Campaign(campaign_name=data_list['campaign_name'], dungeon_master=player)
    campaign.save()
    return campaign.campaign_name
示例#42
0
文件: views.py 项目: eyuen/cametrics
def list_campaigns(request):
  return object_list(request, Campaign.all().filter('organizer =', request.user), paginate_by = 10, template_name = 'campaign_list.html')
示例#43
0
文件: views.py 项目: eyuen/cametrics
def show_campaign(request, key):
  return object_detail(request, Campaign.all().filter('organizer =', request.user), key, template_name = 'campaign_detail.html')
示例#44
0
 def get(self, campaign_id):
     campaign = Campaign.get_by_key_name(campaign_id)
     if campaign:
         status_view = CampaignStatusView(campaign = campaign, response = self.response)