Exemplo n.º 1
0
def signup_verify(request):
    email = request.GET.get('email', '')
    skey = request.GET.get('skey', '')
    old = datetime.now() - timedelta(days=10)
    blists = []
    try:
        optin = Optin.objects.get(skey=skey, email=email, created__gte=old)
        for l in optin.bulk_lists.all():
            if Subscription.subscribed.filter(email__iexact=optin.email,
                                              bulk_list=l).count() == 0:
                s = Subscription(email=optin.email,
                                 signup_location=optin.signup_location,
                                 bulk_list=l)
                s.save()

            blists.append(l)

        optin.verify(request)
    except Optin.DoesNotExist:
        #they've already subscribed; let's show them that instead of a 404
        #this prevents emails like "my link isn't working" after they've already clicked it once
        subs = Subscription.objects.filter(email=email)
        if len(subs):
            for sub in subs:
                blists.append(sub.bulk_list)
        else:
            raise Http404

    c = {'lists': blists}
    return TemplateResponse(request, 'signup_verified.html', c)
Exemplo n.º 2
0
    def post(self):
        data = json.loads(request.data)
        print(data)
        email = data.get("email")

        if Subscription.query.filter_by(email=email).first():
            print("already subscribed.")
            return jsonify(status="ok", data="Already subscribed", error=True)

        subscription_instance = Subscription(email=email)
        subscription = subscription_instance.save_to_db()
        if subscription:
            # sending sms
            # sms_message = "Thank you for registering for the event. We will send you a reminder on the day, so you don't miss out. Love Hive"
            # sms_res = send_sms(phone, sms_message, network, STATUS_URL)
            # print("sms response to user", sms_res)
            # print("successfully saved")

            # sending email
            print("sending email...")
            destination = "*****@*****.**"
            email_message = f"Email: {email}"
            subject = "SUBSCRIPTION"
            send_email(subject, destination, email_message)

            return jsonify(status="ok", data=data, error=False)
        else:
            print("an error occured....")
            return jsonify(status="ok", data=data, error=True)
Exemplo n.º 3
0
def cmd_list(bot, update, chat=None):
    subscriptions = list(
        Subscription.select().where(Subscription.tg_chat == chat))

    subs = ['']
    for sub in subscriptions:
        subs.append(sub.tw_user.full_name)

    subject = "This group is" if chat.is_group else "You are"

    subject = subject + " subscribed to the following Twitter users:\n" +\
         "\n - ".join(subs) + "\n\nYou can remove any of them using /unsub username"

    subscriptions = list(
        Subscription.select().where(Subscription.tg_chat != chat))

    subs = ['']
    for sub in subscriptions:
        subs.append(sub.tw_user.full_name + ", " + str(sub.tg_chat.chat_id))

    subject = subject + "\n grups from other chats \n"

    bot.reply(
        update, subject + " subscribed to the following Twitter users:\n" +
        "\n - ".join(subs) +
        "\n\nYou can remove any of them using /unChan username")
def subscribe(subscriber, resource):
    # HACK workaround for using get_or_create / create_or_get with GFKFields.
    try:
        # HACK workaround for querying equality of GFKField. I'd love to do the following:
        # Subscription.get(
        #     (Subscription.subscriber == subscriber) &
        #     (Subscription.resource == resource))

        sub = Subscription.get(
            (Subscription.subscriber_id == subscriber._get_pk_value()) &
            (Subscription.subscriber_type == subscriber._meta.db_table) &
            (Subscription.resource_id == resource._get_pk_value()) &
            (Subscription.resource_type == resource._meta.db_table))

        created = False

    except Subscription.DoesNotExist:
        sub = Subscription.create(
            subscriber=subscriber,
            resource=resource,
        )

        created = True

    return sub, created
def cmd_unsub(bot, update, args, chat=None):
    if len(args) < 1:
        bot.reply(update, "Use /unsub username1 username2 username3 ...")
        return
    tw_usernames = args
    not_found = []
    successfully_unsubscribed = []

    for tw_username in tw_usernames:
        tw_user = bot.get_tw_user(tw_username)

        if tw_user is None or Subscription.select().where(
                Subscription.tw_user == tw_user, Subscription.tg_chat
                == chat).count() == 0:
            not_found.append(tw_username)
            continue

        Subscription.delete().where(Subscription.tw_user == tw_user,
                                    Subscription.tg_chat == chat).execute()

        successfully_unsubscribed.append(tw_user.full_name)

    reply = ""

    if len(not_found) is not 0:
        reply += "I didn't find any subscription to {}\n\n".format(
            ", ".join(not_found))

    if len(successfully_unsubscribed) is not 0:
        reply += "You are no longer subscribed to {}".format(
            ", ".join(successfully_unsubscribed))

    bot.reply(update, reply)
Exemplo n.º 6
0
    def test_clears_all_subscriptions(self):
        user3 = User(name="user3",
                     email="*****@*****.**",
                     email_confirmed=1)
        user3.set_password('asdfasdf')
        user3.save()

        Subscription(user_id=self.sender.id, shake_id=2).save()
        Subscription(user_id=user3.id, shake_id=2).save()

        Notification.new_subscriber(self.sender, self.receiver, 1)
        Notification.new_subscriber(user3, self.receiver, 2)

        request = HTTPRequest(
            self.get_url('/account/clear-notification'), 'POST',
            {'Cookie': '_xsrf=%s;sid=%s' % (self.xsrf, self.receiver_sid)},
            '_xsrf=%s&type=subscriber' % (self.xsrf))
        self.http_client.fetch(request, self.stop)
        response = self.wait()

        j = json_decode(response.body)
        self.assertEqual(j['response'], "You have 0 new followers")
        ns = Notification.where('receiver_id=%s' % (self.receiver.id))
        for n in ns:
            self.assertTrue(n.deleted)
Exemplo n.º 7
0
    def post(self):
        """
			New Subscription
			@param username: str
			@param subreddit: str
			#return {}
		"""
        a = parser.parse_args()
        s_username, s_subreddit = \
         a['username'], a['subreddit']
        if not s_username \
         or not s_subreddit:
            return {'message': 'all fields required'}, 400, cors

        try:
            s_user = User.objects(username=s_username).get()
        except DoesNotExist:
            return {'message': 'user does not exist'}, 400, cors

        try:
            s_subreddit = Subreddit.objects(name=s_subreddit).get()
        except DoesNotExist:
            return {'message': 'user does not exist'}, 400, cors

        try:
            Subscription.objects(Q(user=s_user)
                                 & Q(subreddit=s_subreddit)).get()
        except DoesNotExist:
            pass
        else:
            return {'message': 'already subscribed'}, 400, cors

        Subscription(user=s_user, subreddit=s_subreddit).save()

        return {}, 200, cors
Exemplo n.º 8
0
def populate_tables():
    logger.info("Started populating tables")

    tracks = get_tracks()
    vehicle_classes = get_vehicle_classes()
    vehicles = get_vehicles()

    populate_table(Track, tracks)
    populate_table(TrackDetails, get_track_details())
    populate_table(VehicleClass, vehicle_classes)
    populate_table(Vehicle, vehicles)
    populate_table(VehicleDetails, get_vehicle_details())
    populate_table(Controller, get_controllers())

    logger.info(
        f"Adding {len(tracks) * len(vehicles)} rows to table 'subscriptions'")
    ignored_classes = list(
        vehicle_classes[vehicle_classes["ignored"] == True]["id"])
    for _, track in tracks.iterrows():
        for _, vehicle in vehicles.iterrows():
            new_subscription = Subscription(track_id=track["id"],
                                            vehicle_id=vehicle["id"])
            if not (track["ignored"] or vehicle["ignored"]
                    or vehicle["class_id"] in ignored_classes):
                new_subscription.update_interval_hours = MID_UPDATE_INTERVAL
            db.session.merge(new_subscription)
        db.session.commit()
    logger.info(f"Finished populating table 'subscriptions'")

    logger.info("Finished populating tables")
    return True
Exemplo n.º 9
0
def subscribe(request):
    options = ""
    text = ""
    for catg in Categories.objects.all():  #fetch all the categories from DB
        options += "<option value=\"" + catg.category + "\">" + catg.category + "</option>"
    if options == "":
        text = "No Categories in the list..Come back later"

    if request.method == 'POST':
        name = request.POST['name']
        email = request.POST['email']
        phnNo = request.POST['phnNo']
        category = request.POST['category']
        user = User(name=name, email=email, phnno=phnNo)
        user.save()  #save user details in the DB
        subscription = Subscription(
            user=User.objects.get(email=email),
            category=Categories.objects.get(category=category))
        subscription.save()  #save users subscription details in the DB
        mailgun.send_mail(
            email, category + " News",
            "Congratulations You have been subscribed to" + category +
            "news\n\nThank you for subscribing to our news service"
        )  #Send subscription mail to the client
        text = "Subscribed successfully"
    return render(request, "CRM/subscribe.html", {
        'options': options,
        'message': text
    })
Exemplo n.º 10
0
  def post(self):
    cl = Checklist.get(Key.from_path('Checklist', long(self.request.get('cl_id'))))
    if not helpers.checkPermissionAndRespond(self, cl=cl, edit=False):
      return
    
    user = users.get_current_user()
    
    for sub in Subscription.all().filter("user ==", user).filter("deleted ==", False):
      if sub.source.key() == cl.key():
        helpers.createResponse(self, 'message_already_subscribed.html', 
          {'old_checklist': cl})
        
    sub = Subscription(
        user=user,
        source=cl,
        deleted=False,                       
                       )        

    sub.put()

    for item in cl.item_set:
      subItem = SubscribedItem(
          subscription=sub,
          original=item,
          finished=False,
          deleted=False,                               
                               )
      subItem.put()
    
    helpers.createResponse(self, 'message_subscribed.html')
Exemplo n.º 11
0
    def sub_command(self, message=None):
        """Subscribe the user to XMPP or SMS"""
        user = message.sender.split('/')[0]
	
        plist = message.body.split(' ' )
 	service_name = plist[1]

	if len(plist)>2:
	    type = "sms"
            user = plist[2]
	else:
	    type = "xmpp"
		
        service = Service.all().filter('name = ', service_name).get()

        if service:
            subscription = Subscription.all().filter('address =', user).filter('service = ', service).get()
            if subscription:
                message.reply("user %s is already subscribed to service %s" % (user, service.name))
            else:
                subscription = Subscription(key_name=hashlib.sha1(user).hexdigest(), type=type, address=user, service=service)
                subscription.put()
                message.reply("Subscribed %s to service %s" % (user, service.name))
        else:
            message.reply("Sorry, I couldn't find a service called "
                          "%s" % service_name)
Exemplo n.º 12
0
def signup_verify(request):
    email = request.GET.get('email', '')
    skey = request.GET.get('skey', '')
    old = datetime.now() - timedelta(days=10)
    blists = []
    try:
        optin = Optin.objects.get(skey=skey, email=email, created__gte=old)
        for l in optin.bulk_lists.all():
            if Subscription.subscribed.filter(email__iexact=optin.email, bulk_list=l).count() == 0:
                s = Subscription(email=optin.email, signup_location=optin.signup_location, bulk_list=l)
                s.save()

            blists.append(l)

        optin.verify(request)
    except Optin.DoesNotExist:
        #they've already subscribed; let's show them that instead of a 404
        #this prevents emails like "my link isn't working" after they've already clicked it once
        subs = Subscription.objects.filter(email=email)
        if len(subs):
            for sub in subs:
                blists.append(sub.bulk_list)
        else:
            raise Http404

    c = {'lists': blists}
    return TemplateResponse(request, 'signup_verified.html', c)
Exemplo n.º 13
0
    def test_subscribe_unsubscribe_works(self):
        user_a = User(name='user_a',
                      email='*****@*****.**',
                      email_confirmed=1,
                      is_paid=1,
                      stripe_plan_id="mltshp-double")
        user_a.set_password('asdfasdf')
        user_a.save()
        self.sign_in('user_a', 'asdfasdf')
        arguments = {
            'name': 'asdf',
            'description': 'A shake test.',
            'title': 'Shake Test',
        }
        self.post_url('/shake/create', arguments=arguments)
        shake = Shake.get('name = %s', 'asdf')

        self.sign_in('admin', 'asdfasdf')
        self.post_url('/shake/%s/subscribe?json=1' % shake.id)

        #subscription #1 is the user subscribing to their own new shake
        subscription = Subscription.get('id=2')
        self.assertEqual(subscription.user_id, 1)
        self.assertEqual(subscription.deleted, 0)

        self.post_url('/shake/%s/unsubscribe?json=1' % shake.id)

        #subscription #1 is the user subscribing to their own new shake
        subscription = Subscription.get('id=2')
        self.assertEqual(subscription.user_id, 1)
        self.assertEqual(subscription.deleted, 1)
def update_subscription(subscription_id, params):
    original_subscription = db_session_users.query(Subscription).filter_by(
        id=subscription_id).first()
    new_subscription_dict = original_subscription.__dict__
    today = datetime.datetime.utcnow()
    new_subscription_dict['latest'] = True
    new_subscription_dict['notes'] = None

    if 'expiration_date' in params:
        new_exiration_date = params['expiration_date']
        new_exiration_date_obj = datetime.datetime.strptime(
            new_exiration_date, "%Y-%m-%d")
        new_subscription_dict['expiration_date'] = new_exiration_date_obj
        # update status of subscription depending on new expiration date
        if new_exiration_date_obj < today or new_exiration_date_obj.date(
        ) == today.date():
            new_subscription_dict[
                'status_reason'] = Subscription.EXPIRED_STATUS_REASON
            new_subscription_dict['status'] = Subscription.INACTIVE_STATUS
        elif new_subscription_dict['status'] != Subscription.ACTIVE_STATUS:
            new_subscription_dict[
                'status_reason'] = Subscription.REACTIVATED_STATUS_REASON
            new_subscription_dict['status'] = Subscription.ACTIVE_STATUS

    if 'plan_id' in params:
        new_plan_id = params['plan_id']
        plan = db_session_users().query(Plan).filter_by(id=new_plan_id).first()
        if plan:
            new_subscription_dict['plan_id'] = new_plan_id
            new_subscription_dict['stripe_id'] = plan.stripe_id
            new_subscription_dict['start_date'] = datetime.datetime.utcnow()
            new_subscription_dict[
                'status_reason'] = Subscription.REACTIVATED_STATUS_REASON
            new_subscription_dict['status'] = Subscription.ACTIVE_STATUS
            if plan.recurring:
                new_subscription_dict['expiration_date'] = None
            else:
                new_subscription_dict[
                    'expiration_date'] = get_default_expiration_date(plan)
        else:
            return {'errors': "Plan is not found"}

    if 'payment_type' in params:
        new_subscription_dict['payment_type'] = params['payment_type']
    if 'notes' in params:
        new_subscription_dict['notes'] = params['notes']

    new_subscription_dict['modified_by_user_id'] = g.user_id

    new_subscription = Subscription(new_subscription_dict)
    db_session_users.add(new_subscription)

    # deactivate old subscription
    deactivate_subscriptions(new_subscription_dict['user_id'])

    db_session_users.commit()
    db_session_users.refresh(new_subscription)

    return {'new_subscription': new_subscription.to_dict()}
Exemplo n.º 15
0
    def _handle(self, url, tags, latlon, radius, period):
        self._set_response_headers()

        user = users.get_current_user()

        if not user:
            response = {'success': False, 'login': self._loginURL()}
        else:
            try:
                period = int(period)
            except:
                period = 86400
            try:
                radius = int(radius)
            except:
                radius = None

            if tags is not None:
                tags = tags.split(',')
            else:
                tags = []

            tags = [x for x in tags if len(x) > 0]

            src = NotificationSource.query(
                NotificationSource.url == url).fetch(1)
            if len(src) == 1:
                src = src[0]
            else:
                src = NotificationSource(url=url)
                ndb.put_multi([src])

            conditions = [
                Subscription.user == user, Subscription.source == src.key,
                Subscription.latlon == latlon, Subscription.radius == radius
            ]
            if len(tags) > 0:
                conditions.append(
                    ndb.AND(*[Subscription.tags == tag for tag in tags]))

            subscription = Subscription.query(*conditions).fetch(1)
            if len(subscription) == 1:
                subscription = subscription[0]
                subscription.period = period
            else:
                subscription = Subscription(user=user,
                                            source=src.key,
                                            tags=tags,
                                            latlon=latlon,
                                            radius=radius,
                                            period=period,
                                            next_poll=datetime.datetime.now(),
                                            last_read=datetime.datetime.now() -
                                            datetime.timedelta(hours=3))
            ndb.put_multi([subscription])
            response = {'success': True, 'id': subscription.key.urlsafe()}

        return json.dumps(response)
Exemplo n.º 16
0
    def test_delete_subscription(self, mock_model_employee):
        mock_model_employee.get_current_employee.return_value = create_employee(
        )

        subscription = create_subscription()
        self.assertIsNotNone(Subscription.get_by_id(subscription.key.id()))

        logic.subscription.delete_subscription(subscription.key.id())

        self.assertIsNone(Subscription.get_by_id(subscription.key.id()))
Exemplo n.º 17
0
    def test_quick_notifications(self):
        """
        /account/quick-notifications should return without error when populated with
        all possible  notification types.

        Page should also not be accessible if you're not signed in.
        """
        self.user2 = User(name='example2',email='*****@*****.**', \
            verify_email_token = 'created', password='******', email_confirmed=1,
            is_paid=1)
        self.user2.save()
        self.sourcefile = Sourcefile(width=20,height=20,file_key="asdf", \
            thumb_key="asdf_t")
        self.sourcefile.save()
        self.sharedfile = Sharedfile(source_id=self.sourcefile.id, name="my shared file", \
            user_id=self.user.id, content_type="image/png", share_key="ok")
        self.sharedfile.save()
        self.shake = Shake(user_id=self.user2.id,
                           name='asdf',
                           type='group',
                           title='My Test Shake',
                           description='Testing this shake test.')
        self.shake.save()

        # new subscription
        new_sub = Subscription(user_id=self.user2.id, shake_id=1)
        new_sub.save()
        new_subscriber = Notification.new_subscriber(sender=self.user2,
                                                     receiver=self.user,
                                                     action_id=new_sub.id)
        # new favorite
        new_favorite = Notification.new_favorite(sender=self.user2,
                                                 sharedfile=self.sharedfile)
        # new save
        new_save = Notification.new_save(sender=self.user2,
                                         sharedfile=self.sharedfile)
        # new comment
        new_comment = Comment(user_id=self.user2.id,
                              sharedfile_id=self.sharedfile.id,
                              body="Testing comment")
        new_comment.save()
        # new mention
        new_mention = Notification.new_mention(receiver=self.user,
                                               comment=new_comment)
        # new invitation
        new_mention = Notification.new_invitation(sender=self.user2,
                                                  receiver=self.user,
                                                  action_id=self.shake.id)

        response = self.fetch_url('/account/quick-notifications')
        self.assertEqual(200, response.code)
        self.sign_out()
        response = self.fetch_url('/account/quick-notifications',
                                  follow_redirects=False)
        self.assertEqual(302, response.code)
Exemplo n.º 18
0
def subscribe(request):
    """
        Subscribe to the blog posts of a given address.
    """
    address = request.POST.get('address')

    new_sub = Subscription(**{"address": address})
    new_sub.save()

    return HttpResponse(json.dumps({"status": "success"},
                                   default=helpers.json_custom_parser),
                        content_type='application/json')
Exemplo n.º 19
0
def create():
    existing = Subscription.query.filter(Subscription.email == request.form["email"]).first()
    if existing is not None:
        abort(409)

    subscription = Subscription()
    subscription.email = request.form["email"]

    db.session.add(subscription)
    db.session.commit()

    return jsonify({"Subscription": "success"})
Exemplo n.º 20
0
def subscriptions_db_add_sub(chat_id, streamer_id):
    subs = Subscription.query.filter(
        Subscription.user_id == chat_id,
        Subscription.streamer_id == streamer_id).first()
    if not subs:
        print(subs)
        sub_new = Subscription()
        sub_new.streamer_id = streamer_id
        sub_new.user_id = chat_id
        db_session.add(sub_new)
        # db_session.add(Subscription.user_id == chat_id, Subscription.streamer_id == streamer_id)
        db_session.commit()
Exemplo n.º 21
0
    def testAddSubscription(self):
        Subscription.add_subscription('user1', 'kw1')
        Subscription.add_subscription('user2', 'kw2')
        Subscription.add_subscription('user1', 'kw2')
        Subscription.add_subscription('user2', 'kw2')

        ret = Subscription.get_active_subscriptions()
        print ret
        self.assertEqual(3, len(ret))
Exemplo n.º 22
0
    def testAddSubscription(self):
        Subscription.add_subscription('user1', 'kw1')
        Subscription.add_subscription('user2', 'kw2')
        Subscription.add_subscription('user1', 'kw2')
        Subscription.add_subscription('user2', 'kw2')

        ret = Subscription.get_active_subscriptions()
        print ret
        self.assertEqual(3, len(ret))
Exemplo n.º 23
0
def subscription_post(client, service):
    exists = Subscription.query.filter_by(device=client).filter_by(service=service).first() is not None
    if exists:
        return Error.DUPLICATE_LISTEN

    subscription_new = Subscription(client, service)
    db.session.add(subscription_new)
    db.session.commit()

    if zeromq_relay_uri:
        queue_zmq_message(json_encode({'subscription': subscription_new.as_dict()}))

    return jsonify({'service': service.as_dict()})
Exemplo n.º 24
0
def create():
    existing = Subscription.query.filter(
        Subscription.email == request.form["email"]).first()
    if existing is not None:
        abort(409)

    subscription = Subscription()
    subscription.email = request.form["email"]

    db.session.add(subscription)
    db.session.commit()

    return jsonify({"Subscription": "success"})
    def post(self):

        with db_session:

            email = self.get_argument("email")
            subscription = Subscription.get(email=email)
            if subscription:
                self.set_status(409)
                self.finish()
                return
            Subscription(email=email)
            self.set_status(201)
            self.finish()
            return
Exemplo n.º 26
0
    def __call__(self, chat_id, args):
        args.reverse()
        if args:
            arg = args.pop().lower()
            node_type = _parse_node_type(arg)
            if node_type is not None:
                node_id = node_type
            else:
                node_id = _parse_node_id(arg)
            if node_id is None:
                return MSG_INCORRECT_COMMAND
        else:
            return MSG_INCORRECT_COMMAND

        exception = False
        no_comments = False
        no_replies = False
        if 'no-replies' in args:
            no_replies = True
            args.remove('no-replies')
        if 'no-comments' in args:
            no_comments = True
            no_replies = False
            args.remove('no-comments')
        if 'except' in args:
            exception = True
            no_comments = False
            no_replies = False
            args.remove('except')
        if args:
            return MSG_INCORRECT_COMMAND

        node = self.bot.session.query(Node).filter_by(id=node_id).first()
        if not node:
            node = Node(id=node_id)

        subscription = self.bot.session.query(Subscription).filter_by(
            node_id=node_id, chat_id=chat_id).first()
        if not subscription:
            subscription = Subscription(node=node, chat_id=chat_id)

        subscription.exception = exception
        subscription.no_comments = no_comments
        subscription.no_replies = no_replies

        self.bot.session.add(subscription)
        self.bot.session.commit()

        return MSG_OK
Exemplo n.º 27
0
Arquivo: web.py Projeto: sharan1/love
def create_subscription():
    subscription_dict = dict(
        request_url=request.form.get('request_url').strip(),
        event=request.form.get('event').strip(),
        active=(request.form.get('active') == 'true'),
        secret=request.form.get('secret').strip(),
    )

    try:
        Subscription.create_from_dict(subscription_dict)
        flash('Subscription created. Refresh the page to see it.')
    except ValueError:
        flash('Something went wrong. Please check your input.', 'error')

    return redirect(url_for('subscriptions'))
Exemplo n.º 28
0
    def test_new_subscriber_notification(self):
        #generate a notification
        new_sub = Subscription(user_id=self.user2.id, shake_id=1)
        new_sub.save()

        notification = Notification.new_subscriber(sender=self.user2,
                                                   receiver=self.user,
                                                   action_id=new_sub.id)

        sent_notification = Notification.get("id=%s", notification.id)
        self.assertEqual(sent_notification.id, notification.id)
        self.assertEqual(sent_notification.sender_id, self.user2.id)
        self.assertEqual(sent_notification.receiver_id, self.user.id)
        self.assertEqual(sent_notification.action_id, new_sub.id)
        self.assertEqual(sent_notification.type, 'subscriber')
Exemplo n.º 29
0
def subscription_post(client, service):
    exists = Subscription.query.filter_by(device=client).filter_by(
        service=service).first() is not None
    if exists:
        return jsonify(Error.DUPLICATE_LISTEN)

    subscription_new = Subscription(client, service)
    db.session.add(subscription_new)
    db.session.commit()

    if zeromq_relay_uri:
        queue_zmq_message(
            json_encode({'subscription': subscription_new.as_dict()}))

    return jsonify({'service': service.as_dict()})
def cmd_sub_no_reply(update: telegram.Update,
                     context: CallbackContext) -> None:
    args = context.args
    bot = context.bot
    chat, _created = TelegramChat.get_or_create(
        chat_id=update.message.chat.id,
        tg_type=update.message.chat.type,
    )
    if len(args) < 1:
        bot.reply(update,
                  "Use /sub_no_reply username1 username2 username3 ...")
        return
    tw_usernames = args
    not_found = []
    already_subscribed = []
    successfully_subscribed = []

    for tw_username in tw_usernames:
        tw_user = bot.get_tw_user(tw_username)

        if tw_user is None:
            not_found.append(tw_username)
            continue

        if Subscription.select().where(
                Subscription.tw_user == tw_user,
                Subscription.tg_chat == chat).count() == 1:
            already_subscribed.append(tw_user.full_name)
            continue

        Subscription.create(tg_chat=chat, tw_user=tw_user, sub_kind=2)
        successfully_subscribed.append(tw_user.full_name)

    reply = ""

    if len(not_found) != 0:
        reply += "Sorry, I didn't find username{} {}\n\n".format(
            "" if len(not_found) == 1 else "s", ", ".join(not_found))

    if len(already_subscribed) != 0:
        reply += "You're already subscribed to {}\n\n".format(
            ", ".join(already_subscribed))

    if len(successfully_subscribed) != 0:
        reply += "I've added your subscription to {}".format(
            ", ".join(successfully_subscribed))

    bot.reply(update, reply)
Exemplo n.º 31
0
 def work(self):
     for source in Subscription.select():
         if self.produce(source.url):
             self._logger.info('Producing source url %s.' % source.url)
         else:
             self._logger.info('Skipping source url %s.' % source.url)
     time.sleep(10)
Exemplo n.º 32
0
    def post(self):
        active_subs = Subscription.get_active_subscriptions()

        items = json.loads(self.request.get('items'))
        logging.debug('before parsing, memory: %s' %
                      runtime.memory_usage().current())
        parser = RentParser()
        parsed_items = []

        for item in items:
            try:
                parsed = parser.parse(item)
                ret = RentRecord.add_record(parsed)
            except Exception as e:
                logging.error(repr(e))

            parsed_items.append(parsed)

        logging.debug('after parsing, memory: %s' %
                      runtime.memory_usage().current())

        user2message = filter_items(parsed_items, active_subs)

        for user, item in user2message.items():
            logging.debug('user: %s has %d messages' % (user, len(item)))
            User.update_user_items(user, item)
            url = get_short_url(user)
            if not url:
                url = site_config.url + '?user=%s' % user
            msg = [u'新找到%d条租房信息。' % len(item), u'点击以下链接查看:', url]

            messenger.send_message(user, '\n'.join(msg))
Exemplo n.º 33
0
  def get(self, **args):
    cl = Checklist.get(Key.from_path("Checklist", long(args['id'])))
    
    if not cl or cl.deleted: 
      helpers.createResponse(self, 'message_not_exist.html')
      return
    
    if not helpers.checkPermissionAndRespond(self, cl=cl, edit=False): return
    
    item_q = cl.item_set.filter("deleted ==", False).order("creation_time")
    cursor = self.request.get('cursor')
    if cursor:
      item_q = item_q.with_cursor(cursor)
    items = item_q.fetch(20)

    user = users.get_current_user()
    subscribed = False
    for sub in Subscription.all().filter("user ==", user).filter("deleted ==", False):
      if sub.source.key() == cl.key():
        subscribed = True
        break
   
    helpers.createResponse(self, 'dashboard_subscribe.html', 
        {'items': items,
        'cl': cl,
        'cursor_item': item_q.cursor(),
        'subscribed': subscribed,
        },
                           )   
Exemplo n.º 34
0
    def unsub_command(self, message=None):
        """Unsubscribe the user from a service"""
        user = message.sender.split('/')[0]

        plist = message.body.split(' ' )
        service_name = plist[1]

	if len(plist)>2:
	    type = "sms"
            user = plist[2]
	else:
	    type = "xmpp"
		
        service = Service.all().filter('name = ', service_name).get()

        if service:
            subscription = Subscription.all().filter('address =', user).filter('service = ', service).filter('type =', type).get()
            if subscription:
                subscription.delete()
		if type == "xmpp":
	            	mobile = Mobile.all().filter('subscription = ', subscription).get()
			if mobile:
				mobile.delete()
                message.reply("Unsubscribed %s from service %s" % (user, service.name))
            else:
                message.reply("user %s is not subscribed to service %s" % (user, service.name))
        else:
            message.reply("Sorry, I couldn't find a service called "
                          "%s" % service_name)
Exemplo n.º 35
0
  def get(self):
    user = users.get_current_user()
    checklist_q = Checklist.all().filter("user ==", user).filter("deleted ==", False).order("title");
    cursor = self.request.get('cursor_cl')
    if cursor:
      checklist_q = checklist_q.with_cursor(cursor)
    checklists = checklist_q.fetch(20)
    
    cursor_cl = checklist_q.cursor()
    checklist_q = checklist_q.with_cursor(cursor_cl)

    subs_q = Subscription.all().filter("user ==", user).filter("deleted ==", False);
    cursor = self.request.get('cursor_sub')
    if cursor:
      subs_q = subs_q.with_cursor(cursor)
    subs = subs_q.fetch(20)
    
    cursor_sub = subs_q.cursor()
    subs_q = subs_q.with_cursor(cursor_sub)
    
    helpers.createResponse(self, 'dashboard_cls.html',
        {'checklists': checklists,
         'cursor_cl': cursor_cl,
         'subs': subs,
         'cursor_sub': cursor_sub,
         'more_subs': subs_q.count(1) == 1,
         'more_cls': checklist_q.count(1) == 1,
         })
Exemplo n.º 36
0
def subscribe(request_id, method, address):
    '''
    Create a new subscription the request identified by request_id.
    @param request_id: The request to subscribe to
    @param method:     The type of subscription (e.g. 'email' or 'sms')
    @param address:    The adress to send updates to (e.g. '*****@*****.**' or '63055512345')
    '''

    # TODO: validate the subscription by seeing if the request_id exists via Open311?
    with db() as session:
        subscription = get_subscription(request_id, method, address)
        if subscription:
            return subscription.key

        else:
            subscription = Subscription(sr_id=request_id,
                                        method=method,
                                        contact=address)
            session.add(subscription)

            # If we haven't ever updated, set the last update date
            last_update_info = session.query(UpdateInfoItem).filter(
                UpdateInfoItem.key == 'date').first()
            if not last_update_info:
                # TODO: get the SR's updated_datetime and use that
                session.add(
                    UpdateInfoItem(key='date', value=datetime.datetime.now()))

            return subscription.key

    return False
Exemplo n.º 37
0
def remove_all_sub(house_name):
    house_list = House.query(House.name == house_name).fetch()
    house_key = house_list[0].key
    sub_list = Subscription.query(Subscription.house_key == house_key).fetch()
    for sub in sub_list:
        sub.key.delete()
    return
Exemplo n.º 38
0
def subscribe(request, topic):
    browse_host = request.META.get('HTTP_ORIGIN', '%s://%s' %
                                    (request.META.get('wsgi.url_scheme', 'https'),
                                        request.META['HTTP_HOST']))
    protocal, dev_null = browse_host.split('://')
    subscription = Subscription.subscribe(topic, protocal, browse_host)
    return HttpResponse(subscription.message, content_type="application/json")
Exemplo n.º 39
0
def seed(db=DATABASE_URI):
    """Seed the database with some seed data."""
    connect(db)
    user = User.create(email='*****@*****.**', password='******')

    # Create seed subscriptions through json file.
    with open('resources/seed/subscriptions.json', 'r') as f:
        subscriptions = Subscription.from_json(f.read())
        for subscription in subscriptions:
            if random.choice([True, False]):
                user.subscribe(subscription)

        # Ensure at least one subscription
        user.subscribe(subscriptions[0])

    # Create seed topics through json file.
    with open('resources/seed/topics.json', 'r') as f:
        topics = Topic.from_json(f.read())
        for topic in topics:
            user.subscribe(subscriptions[0], topic)

    # Create seed articles through json file.
    with open('resources/seed/articles.json', 'r') as f:
        articles = Article.from_json(f.read())
        for article in articles:
            topic = random.choice(list(article.source.topics()))
            ArticleTopic.create(article=article, topic=topic)

            user.add_article(article)
Exemplo n.º 40
0
    def get(self):
        user, logout = check_user(users.get_current_user())
        if user:
            template_args = {'logout_url': users.create_logout_url('/')}
            subscription_list = list()
            more = True
            curs = None
            while more:
                s, curs, more = Subscription.query(
                ).fetch_page(
                    10, start_cursor=curs)
                for sitem in s:
                    subscription_list.append(sitem)

            template_args['subscriptions'] = subscription_list

            users_list = list()
            more = True
            curs = None
            while more:
                u, curs, more = User.query(
                ).order(
                    -User.when).fetch_page(
                        10, start_cursor=curs)
                for uitem in u:
                    users_list.append(uitem)

            template_args['users'] = users_list

            template = JINJA_ENVIRONMENT.get_template('users.html')
            self.response.write(template.render(template_args))

        else:
            self.redirect('/admin')
Exemplo n.º 41
0
    def _handle(self,url,tags,latlon):
        self._set_response_headers()

        user = users.get_current_user()

        if not user:
            response = { 'success': False, 'login': self._loginURL() }
        else:
            response = { 'success': False }
            if tags is not None:
                tags = tags.split(',')
            else:
                tags = []

            tags = [x for x in tags if len(x) > 0]

            src = NotificationSource.query( NotificationSource.url == url ).fetch(1)
            if len(src) == 1:
                src = src[0]
                conditions = [ Subscription.user == user,
                               Subscription.source == src.key,
                               Subscription.latlon == latlon ]
                if len(tags) > 0:
                  conditions.append( ndb.AND(*[Subscription.tags == tag for tag in tags]) )

                subscription = Subscription.query( *conditions ).fetch(1)
                if len(subscription) == 1:
                  subscription = subscription[0]
                  response = { 'success': True, 'id': subscription.key.urlsafe() }

        return json.dumps(response)
Exemplo n.º 42
0
def cmd_all(bot, update, chat=None):
    subscriptions = list(
        Subscription.select().where(Subscription.tg_chat == chat))

    if len(subscriptions) == 0:
        return bot.reply(update,
                         'You have no subscriptions, so no tweets to show!')

    text = ""

    for sub in subscriptions:
        if sub.last_tweet is None:
            text += "\n{screen_name}: <no tweets yet>".format(
                screen_name=escape_markdown(sub.tw_user.screen_name), )
        else:
            text += ("\n{screen_name}:\n{text} "
                     "[link](https://twitter.com/{screen_name}/status/{tw_id})"
                     ).format(
                         text=markdown_twitter_usernames(
                             escape_markdown(sub.last_tweet.text)),
                         tw_id=sub.last_tweet.tw_id,
                         screen_name=escape_markdown(sub.tw_user.screen_name),
                     )

    bot.reply(update,
              text,
              disable_web_page_preview=True,
              parse_mode=telegram.ParseMode.MARKDOWN)
Exemplo n.º 43
0
    def sms_command(self, message=None):
        """Subscribe the user to a offline SMS"""

        plist = message.body.split(' ')
	if len(plist)==3:
	        user = message.sender.split('/')[0]
	 	service_name = plist[1]
	 	number = plist[2]
	
	        service = Service.all().filter('name = ', service_name).get()
	
	        if service:
		 	subscription = Subscription.all().filter('address =', user).filter('service = ', service).get()
		
		        if subscription:
		            mobile = Mobile.all().filter('number =', number).get()
		            if mobile:
		                message.reply("user %s is already registered backup mobile %s for service %s" % (user, mobile.number,service_name))
		            else:
		                mobile = Mobile(number=number, subscription = subscription)
		                mobile.put()
		                message.reply("Subscribed user %s to backup mobile %s for service %s" % (user, number,service_name))
		        else:
		            message.reply("Sorry, I couldn't find a subscription on %s for %s" % (service_name,user))
	        else:
	            message.reply("Sorry, I couldn't find a service called "
	                          "%s" % service_name)
	else:
		message.reply("Usage: sms SERVICE +61412345678")
Exemplo n.º 44
0
def post(request):
    if not request.user.is_superuser:
        raise Http404

    if request.GET and request.GET.get('sent'):
        return render_to_response(request, 'subscribe/message.html', {'message': u'%s писем отправлено.' % request.GET.get('sent')})

    form = PostForm(request.POST)
    if request.POST and form.is_valid():
        log = logging.getLogger('django.email')
        subject, content = form.cleaned_data['message'].split("\n", 1)
        subject = subject.strip()
        count = 0
        fails = 0
        for s in Subscription.valid_emails():
            try:
                unsubscribe = u"\n\nЧтобы отписаться от рассылки, перейдите по ссылке\n\nhttp://%s/subscribe/cancel?email=%s&code=%s"\
                              % (settings.DOMAIN, s.email, s.delete_code)
                send_mail(subject, content + unsubscribe, settings.DEFAULT_FROM_EMAIL, [s.email])
                count += 1
            except Exception, e:
                log.error("Cannot send mail: %s", e)
                fails += 1

        log.info("%s emails sended, %s failed", count, fails)
        return HttpResponseRedirect(reverse('post') + '?sent=%s' % count)
Exemplo n.º 45
0
    def unsms_command(self, message=None):
        """Unsubscribe the user from a service"""
	plist = message.body.split(' ')
	if len(plist)==2:
	        user = message.sender.split('/')[0]
	
	        service_name = plist[1]
	
	        service = Service.all().filter('name = ', service_name).get()
	
	        if service:
		    subscription = Subscription.all().filter('address =', user).filter('service = ', service).get()
		
		    if subscription:
	            	mobile = Mobile.all().filter('subscription = ', subscription).get()
	            	if mobile:
		    	    message.reply("Unsubscribed user %s from backup mobile %s for service %s" % (user, mobile.number,service_name))
	            	    mobile.delete()
			else:
			    message.reply("No backup mobile for user %s on %s service" % (user,service_name))
	 	    else:
	            	message.reply("User %s is not subscribed to service %s" % (user, service.name))
	        else:
	            message.reply("Sorry, I couldn't find a service called "
                          "%s" % service_name)
	else:
		 message.reply("Usege: unsms SERVICE +6112345678")
Exemplo n.º 46
0
    def post(self):
        """Notify subscribers that a service changed status."""

        address = self.request.get('address')
        service = Service.get(self.request.get('service'))
        oldstatus = Status.get(self.request.get('oldstatus'))
        number = self.request.get('number')

        logging.info("Service: %s" % service)
        logging.info("Service name: %s" % service.name)

        msg = "%s changed state from %s to %s (%s)" % (
                service.name, oldstatus.name,
                service.current_event().status.name,
                service.current_event().message)

        user = Subscription.get_by_email(address)
        if user.status == "available" or not number:
        	status_code = xmpp.send_message(address, msg)
    		chat_message_sent = (status_code == xmpp.NO_ERROR)
		logging.info("Notified: %s\nmessage: %s code: %d" % (address, msg, status_code))
        elif user.status == "unavailable" and number:
		sms = smsgw(to = number, msg = msg)
		sms.send()
		logging.info("Offline SMS: %s\nmessage: %s" % (number, msg))
    def cmd_all(self, msg, args, chat=None):
        subscriptions = list(Subscription.select().where(
                             Subscription.tg_chat == chat))

        if len(subscriptions) == 0:
            return self.reply(msg, 'You have no subscriptions, so no tweets to show!')

        text = ""

        for sub in subscriptions:
            if sub.last_tweet is None:
                text += "\n{screen_name}: <no tweets yet>".format(
                    screen_name=escape_markdown(sub.tw_user.screen_name),
                )
            else:
                text += ("\n{screen_name}:\n{text} "
                         "[link](https://twitter.com/{screen_name}/status/{tw_id})").format(
                    text=markdown_twitter_usernames(escape_markdown(sub.last_tweet.text)),
                    tw_id=sub.last_tweet.tw_id,
                    screen_name=escape_markdown(sub.tw_user.screen_name),
                )

        self.reply(msg, text,
                   disable_web_page_preview=True,
                   parse_mode=telegram.ParseMode.MARKDOWN)
Exemplo n.º 48
0
    def locations_insert(self, location):
        """Insert a new location for the current user.

        Not part of the actual mirror API but used by the emulator.
        """

        if location.id is not None:
            raise endpoints.BadRequestException("ID is not allowed in request body.")

        location.put()

        # Notify location subscriptions

        data = {}
        data["collection"] = "locations"
        data["itemId"] = "latest"
        operation = Operation.UPDATE
        data["operation"] = operation.name

        header = {"Content-type": "application/json"}

        query = Subscription.query().filter(Subscription.user == endpoints.get_current_user())
        query = query.filter(Subscription.collection == "locations")
        query = query.filter(Subscription.operation == operation)
        for subscription in query.fetch():
            data["userToken"] = subscription.userToken
            data["verifyToken"] = subscription.verifyToken

            req = urllib2.Request(subscription.callbackUrl, json.dumps(data), header)
            try:
                urllib2.urlopen(req)
            except:
                logging.error(sys.exc_info()[0])

        return location
Exemplo n.º 49
0
 def get(self):
   user = users.get_current_user()
   checklist_q = Checklist.all().filter("user ==", user).filter("deleted ==", False).order("title");
   cursor = self.request.get('cursor_cl')
   if cursor:
     checklist_q = checklist_q.with_cursor(cursor)
   checklists = checklist_q.fetch(10)
   
   checklist_q = checklist_q.with_cursor(checklist_q.cursor())
   
   subs_by_cl = []
   for cl in checklists:
     subs = []
     for sub in cl.subscription_set:
       subs.append(sub)
     subs_by_cl.append(subs)
       
   subs_q = Subscription.all().filter("user ==", user).filter("deleted ==", False);
   cursor = self.request.get('cursor_sub')
   if cursor:
     subs_q = subs_q.with_cursor(cursor)
   subs = subs_q.fetch(10)
   
   subs_q = subs_q.with_cursor(subs_q.cursor())
   
   helpers.createResponse(self, 'dashboard_cls.html',
       {'checklists': checklists,
        'cursor_cl': checklist_q.cursor(),
        'subs_by_cl': subs_by_cl,
        'subs': subs,
        'cursor_sub': subs_q.cursor(),
        'more_subs': subs_q.count(1) == 1,
        'more_cls': checklist_q.count(1) == 1,
        })
Exemplo n.º 50
0
def get_subscriptions():
    with sqlite3.connect("./rare.db") as conn:

        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        db_cursor.execute("""
        SELECT
           s.id,
           s.user_id,
           s.subscribe_id,
           s.begin,
           s.end
        FROM Subscription s
        """)

        subscriptions = []

        dataset = db_cursor.fetchall()

        for row in dataset:

            subscription = Subscription(row['id'], row['user_id'],
                                        row['subscribe_id'], row['begin'],
                                        row['end'])
            subscriptions.append(subscription.__dict__)

    return json.dumps(subscriptions)
Exemplo n.º 51
0
    def locations_insert(self, location):
        """Insert a new location for the current user.

        Not part of the actual mirror API but used by the emulator.
        """

        if location.id is not None:
            raise endpoints.BadRequestException("ID is not allowed in request body.")

        location.put()

        # Notify location subscriptions

        data = {}
        data["collection"] = "locations"
        data["itemId"] = "latest"
        operation = Operation.UPDATE
        data["operation"] = operation.name

        header = {"Content-type": "application/json"}

        query = Subscription.query().filter(Subscription.user == endpoints.get_current_user())
        query = query.filter(Subscription.collection == "locations")
        query = query.filter(Subscription.operation == operation)
        for subscription in query.fetch():
            data["userToken"] = subscription.userToken
            data["verifyToken"] = subscription.verifyToken

            req = urllib2.Request(subscription.callbackUrl, json.dumps(data), header)
            try:
                urllib2.urlopen(req)
            except:
                logging.error(sys.exc_info()[0])

        return location
Exemplo n.º 52
0
    def post(self):
        active_subs = Subscription.get_active_subscriptions()

        items = json.loads(self.request.get('items'))
        logging.debug('before parsing, memory: %s' % runtime.memory_usage().current())
        parser = RentParser()
        parsed_items = []

        for item in items:
            try:
                parsed  = parser.parse(item)
                ret     = RentRecord.add_record(parsed)
            except Exception as e:
                logging.error(repr(e))

            parsed_items.append(parsed)

        logging.debug('after parsing, memory: %s' % runtime.memory_usage().current())

        user2message = filter_items(parsed_items, active_subs)

        for user, item in user2message.items():
            logging.debug('user: %s has %d messages' % (user, len(item)))
            User.update_user_items(user, item)
            url = get_short_url(user)
            if not url:
                url = site_config.url + '?user=%s' % user
            msg = [u'新找到%d条租房信息。' % len(item),
                   u'点击以下链接查看:',
                   url]

            messenger.send_message(user, '\n'.join(msg))
Exemplo n.º 53
0
def add(request):
    form = EmailForm(request.POST)
    if form.is_valid():
        if Subscription.objects.filter(email=form.cleaned_data['email']).count() > 0:
            return render_to_response(request, 'subscribe/message.html', {'message': u'Вы уже подписаны на нашу рассылку.'})

        else:
            s = Subscription(email=form.cleaned_data['email'])
            s.fill_codes()

            subject, content = process_template('subscribe/invitation.html',
                                                {'subscription': s})
            send_mail(subject, content, settings.DEFAULT_FROM_EMAIL, [s.email])

            return render_to_response(request, 'subscribe/message.html', {'message': u'Вы успешно подписаны, проверьте свою почту.'})

    return render_to_response(request, 'subscribe/add.html', {'form': form})
Exemplo n.º 54
0
def newSubs(resid, clientid):
    
    try:
        parentRes = Resource.objects.get(resource_id=resid)
    except Resource.DoesNotExist:
        return HttpResponse(content="Resource not found", status=404)
    #TODO validate clientid
    duration = parentRes.sub_duration 
    if ( duration == None ):
        timestamp = -1
    else:      
        timestamp = time.time() + duration
    subs = Subscription(resource=parentRes, 
                        client_id = clientid, 
                        credits_count = parentRes.sub_max_credits_count, 
                        expires = timestamp )
    subs.save()
Exemplo n.º 55
0
 def txn():
     user = Subscription.get_by_email(from_jid)
     if user:
         user.is_friend = is_friend
         return user.put()
     else:
         return Subscription(key_name=hashlib.sha1(from_jid).hexdigest(),
                           address=from_jid, is_friend=is_friend).put()
Exemplo n.º 56
0
        def txn():
            user = Subscription.get_by_email(from_jid)
            if user:
		if presence == "probe":
			return xmpp.send_presence(from_jid, presence_type=xmpp.PRESENCE_TYPE_PROBE)
		else:
	                user.status = presence
        	        return user.put()
Exemplo n.º 57
0
 def get_feed_groups_for_user(self, user):
     q = Subscription.select(Subscription).join(User).where(User.id == user.id).distinct().naive()
     groups = defaultdict(lambda: [])
     for s in q:
         groups[str(s.group.id)].append('%d' % s.feed.id)
     result = []
     for g in groups.keys():
         result.append({'group':g, 'feed_ids':','.join(groups[g])})
     return result
Exemplo n.º 58
0
def sns_endpoint(request):
    message = json.loads(request.raw_post_data)
    if message['Type'] == 'SubscriptionConfirmation':
    	obj = Subscription.process(message)
    elif message['Type'] == 'Notification':
    	obj= Notification.add(message)
    else:
    	return HttpResponseBadRequest('Unknown Request')
    return HttpResponse(json.dumps({'status': obj.status, 'message':message}), mimetype="application/json")
Exemplo n.º 59
0
def email(request):
    if request.method == "POST":
        email = request.POST["email"]
        if isLegitEmail(email) and request.POST["lastname"] == "":
            o = Subscription(email=email)
            o.save()
            template = get_template("subscribe_email.html")
            text = template.render(Context({"email": email}))
            print "text!!!"
            msg = EmailMessage("Thanks for subscribing!", text, "*****@*****.**", [email])
            msg.content_subtype = "html"
            msg.send()
            emails = [e for (name, e) in settings.MANAGERS]
            msg2 = EmailMessage(email + " subscribed to benkuhn.net", "", "*****@*****.**", emails)
            msg2.send()
        return render(request, "sub.html", {"title": "thanks :)", "email": email})
    else:
        return render(request, "email.html", {"title": "subscribe via email"})