Ejemplo n.º 1
0
def home(request):
    group_query = db.Query(Group)
    groups = group_query.fetch(20)
    if len(groups) <1:
        return redirect("/group/edit/")

    return respond('group_home.html', {'groups': groups,})
Ejemplo n.º 2
0
def edit(request):
  """Create or edit a listings.  GET shows a blank form, POST processes it."""
  user = users.GetCurrentUser()
  if user is None:
    return http.HttpResponseForbidden('You must be signed in to edit your allocations')

  query = Allocation.all()
  query.filter('creator =', user)
  result = query.fetch(limit=1)
  allocation = None
  flash = {}
  for entry in result:
    allocation = entry

  form = AllocationForm(data=request.POST or None, instance=allocation)

  if not request.POST:
    return common.respond(request, user, 'allocation', {'form': form, 'allocation': allocation, 'budget':TOTAL_BUDGET, 'flash': flash})

  errors = form.errors
  if not errors:
    try:
      allocation = form.save(commit=False)
    except ValueError, err:
      errors['__all__'] = unicode(err)
Ejemplo n.º 3
0
def list(request, listing_id):
  user = users.GetCurrentUser()
  if user is None:
    return http.HttpResponseForbidden('You must be signed in to view listing values')
  listing_values = None
  listing = None
  lvs_paginator = None
  if request.GET.has_key('page'):
    page = int(request.GET['page'])
  else:
    page = 0

  if listing_id:
    listing = get_listing(listing_id)
    lvs = ListingValue.all().order('-date').filter('listing_key = ', str(listing.key()))
    lvs_paginator = ObjectPaginator(lvs, 10)
    listing_values = lvs_paginator.get_page(page)

  if listing is None or listing_values is None or listing_id is None:
      return http.HttpResponseNotFound(
          'No values exists for that listing (%r)' %
          listing_id)

  paginator = {}
  paginator['has_previous_page'] = lvs_paginator.has_previous_page(page)
  paginator['has_next_page'] = lvs_paginator.has_next_page(page)
  paginator['next_page_number'] = page+1
  paginator['previous_page_number'] = page-1
  return common.respond(request, user,
                        'values_list',
                        {'listing': listing,
                         'listing_values' : listing_values,
                         'paginator': paginator})
Ejemplo n.º 4
0
def page_redirect(request, url):
    params = {}
    for code in ('login', 'power', 'param', 'missing'):
        if request.GET.has_key(code):
            params.update({"code_%s" % code: True,})

    params.update({'url': "/%s" % url,})
    return respond('redirect.html', params)
Ejemplo n.º 5
0
def get_key(request):
  symbol = None
  if request.GET.has_key('symbol'):
    symbol = request.GET['symbol']
  else:
    return http.HttpResponseNotFound('Please provide symbol parameter')
  listing_key = get_key_from_symbol(symbol)
  if listing_key is None:
    return http.HttpResponseNotFound('None')
  return common.respond(request, None, 'key', {'listing_key': listing_key})
Ejemplo n.º 6
0
def edit(request, group_id):
    param = {}
    if group_id:
        group = get_group(group_id)
        require = check_user(group)
        if require:
            return redirect("/redirect/?%s" % require)
        
        users = get_users(group)
        param.update({'group': group,
                      'users': users,})

    errs = get_param(request, 'errs')
    if errs:
        errs = errs.split(',')
        for err in errs:
            param.update({"%s_error" % err: True,})
    return respond('group_edit.html', param)
Ejemplo n.º 7
0
def detail(request, group_id):
    group = get_group(group_id)
    if not group:
        raise Http404()
        
    require_privilege = check_user(group)
        
    summaries = [] +group.summaries
    summaries.sort()
    due_payer_index = group.summaries.index(summaries[0])
    due_payer = get_user(group.members[due_payer_index])

    params = {'fees': get_fees(group),
              'members': get_users(group),
              'is_valid_user': not require_privilege,
              'group': group,
              'due_payer': due_payer.name,
              'due_amount': -summaries[0], }

    return respond('group_detail.html', params)
Ejemplo n.º 8
0
def delete(request):
  user = users.GetCurrentUser()
  if user is None:
    return http.HttpResponseForbidden('You must be signed in to delete listing values')
  symbol = None
  if request.GET.has_key('symbol'):
    symbol = request.GET['symbol']
  else:
    return http.HttpResponseNotFound('Please provide symbol parameter')
  listing_key = listings.get_key_from_symbol(symbol)
  if listing_key is None:
    return http.HttpResponseNotFound('None')
  q = db.GqlQuery("SELECT * FROM ListingValue WHERE listing_key = :key",
                  key = str(listing_key))
  results = q.fetch(1000)
  while results:
    db.delete(results)
    results = q.fetch(1000, len(results))
  return common.respond(request, user,
                        'values_delete')
Ejemplo n.º 9
0
def delete(request, fee_id):
    try:
        fee = get_fee(fee_id)
        group_id = fee.group.key().id()
        if not request.GET.has_key('confirm'):
            params = {'name': u"%s的%d个家伙腐败掉%.1f的证据" % (fee.group.name, len(fee.participants), fee.amount),
                      'confirm': "%s?confirm" % request.path,
                      'cancel': "/group/%s" % group_id,}
            return respond("confirm.html", params)

        require = check_user(fee.group)
        if require:
            return redirect("/redirect/?%s" % require)

        update_group_summary(fee, add_fee=False)
        fee.delete()
    except:
        raise
    else:
        return redirect("/redirect/group/%s" % group_id)
Ejemplo n.º 10
0
def delete(request, group_id):
    try:
        group = get_group(group_id)
        require = check_user(group)
        if require:
            raise Exception("invalid user")
        if not request.GET.has_key('confirm'):
            params = {'name': group.name,
                      'confirm': "%s?confirm" % request.path,
                      'cancel': "/group/%s" % group_id,}
            return respond("confirm.html", params)
    except ValueError:
        return redirect('/redirect/?param')
    except:
        return redirect("/redirect/?%s" % require)
    else:
        for member_id in group.members:
           member = get_user(member_id)
           member.delete()
        group.delete()
        return home(request)
Ejemplo n.º 11
0
def fetch_historic_values(request, listing_id):
  user = users.GetCurrentUser()
  if user is None:
    return http.HttpResponseForbidden('You must be signed in to view listing values')
  listing_values = None
  listing = None
  historic_results = None
  if listing_id:
    listing = get_listing(listing_id)
    listing_values = get_all_listing_values(listing.key())
    start_date = datetime.date.today() - datetime.timedelta(days=60)
    for listing_value in listing_values:
      start_date = listing_value.date
      break
    historic_results = ystockquote.get_historical_prices(
      listing.symbol, start_date.strftime("%Y%m%d"),
      datetime.date.today().strftime("%Y%m%d"))
    for historic_result in historic_results:
      is_in_data_store = False
      split_date = historic_result[0].split('-')
      historic_date = datetime.date(int(split_date[0]),
                                    int(split_date[1]),
                                    int(split_date[2]))
      for data_store_value in listing_values:
        if historic_date == data_store_value.date:
          is_in_data_store = True
      if not is_in_data_store:
        lv = ListingValue(listing_key = str(listing.key()),
                          date = historic_date,
                          open = float(historic_result[1]),
                          high = float(historic_result[2]),
                          low = float(historic_result[3]),
                          volume = int(historic_result[5]),
                          adj_close = float(historic_result[6]),
                          value = float(historic_result[4]),
                          creator = user)
        lv.save()
  return common.respond(request, user,
                        'values_fetch',
                        {'listing': listing})
Ejemplo n.º 12
0
def edit(request, listing_id):
  """Create or edit a listings.  GET shows a blank form, POST processes it."""
  user = users.GetCurrentUser()
  if user is None:
    return http.HttpResponseForbidden('You must be signed in to add or edit a listing')

  listing = None
  if listing_id:
    listing = db.get(db.Key.from_path(Listing.kind(), int(listing_id)))
    if listing is None:
      return http.HttpResponseNotFound('No listing exists with that key (%r)' %
                                       listing_id)

  form = ListingForm(data=request.POST or None, instance=listing)

  if not request.POST:
    return common.respond(request, user, 'listing', {'form': form, 'listing':listing})

  errors = form.errors
  if not errors:
    try:
      listing = form.save(commit=False)
    except ValueError, err:
      errors['__all__'] = unicode(err)
Ejemplo n.º 13
0
  flash = {}
  for entry in result:
    allocation = entry

  form = AllocationForm(data=request.POST or None, instance=allocation)

  if not request.POST:
    return common.respond(request, user, 'allocation', {'form': form, 'allocation': allocation, 'budget':TOTAL_BUDGET, 'flash': flash})

  errors = form.errors
  if not errors:
    try:
      allocation = form.save(commit=False)
    except ValueError, err:
      errors['__all__'] = unicode(err)
  if errors:
    flash["message"] = "No change from default, I'll fix this sometime"
    return common.respond(request, user, 'allocation', {'form': form, 'allocation': allocation, 'budget':TOTAL_BUDGET, 'flash': flash})

  if not allocation.creator:
    allocation.creator = user

  allocation.put()
  flash["message"] = "Allocations saved..."
  return common.respond(request, user, 'allocation', {'form': form, 'allocation': allocation, 'budget':TOTAL_BUDGET, 'flash': flash})
  #return http.HttpResponseRedirect('/')

def new(request):
  """Create and allocations entry .  GET shows a blank form, POST processes it."""
  return edit(request, None)
Ejemplo n.º 14
0
def lambda_handler(event, context):
    global TEAM_INFO
    global USER_INFO
    global NAME_MAP
    global PUBLIC_CHANNELS_INFO
    global sc
    global sms_controller
    global redis_client
    if not sc:
        sc = SlackClient(slack_client_token)
    if not USER_INFO:
        USER_INFO = get_member_info(client=sc)
        NAME_MAP = build_user_name_map(USER_INFO)
        if not USER_INFO:
            log.error(
                json.dumps(
                    {"message":
                     "unable to retrieve user info from slack api"}))
    if not sms_controller:
        sms_controller = APIController(username=FLOWROUTE_ACCESS_KEY,
                                       password=FLOWROUTE_SECRET_KEY)
    event_body = parse_qs(event['body'])
    if not event_body:
        event_body = json.loads(event['body'])
    log.debug(
        json.dumps({
            "message": "the event body from slack",
            "event_body": event_body
        }))
    challenge = check_for_challenge(event_body)
    if challenge:
        return respond(None, challenge)
    token = unpack_token(event_body)
    if not token:
        event_body = json.loads(event_body['payload'][0])
        token = event_body['token']
    if token != slack_verification_token:
        log.error("Request token (%s) does not match expected", token)
        return respond(Exception('Invalid request token'))
    if 'command' in event_body:
        # It's a slash command
        command = event_body['command'][0]
        if command != COMMAND_WORD:
            return
        else:
            log.debug(
                json.dumps({
                    "message":
                    "User triggered {} command, retrieving customer contact info."
                    .format(COMMAND_WORD)
                }))
        user = event_body['user_name'][0]
        channel = event_body['channel_name'][0]
        command_text = unicode(event_body['text'][0])
        user_id = event_body['user_id']
        team_domain = event_body['team_domain'][0]
        # TODO get team id and channel id to load them into the cache
        try:
            recipient, text = command_text.split('@', 1)[1].split(
                ' ', 1)  # FIXME support multiple recipients
        except [IndexError, KeyError]:
            log.error(
                json.dumps({
                    "message":
                    "Could not parse the {} command".format(COMMAND_WORD)
                }))
            return respond(None, "Could not parse the command")
        try:
            recipient_number = USER_INFO[NAME_MAP[recipient]]['number']
            if not recipient_number:
                raise KeyError('number')
        except KeyError:
            log.error(
                json.dumps({
                    "message":
                    "Unable to find contact number for user {}. Refreshing global contact info before returning."
                    .format(recipient)
                }))
            USER_INFO = get_member_info(client=sc)
            NAME_MAP = build_user_name_map(USER_INFO)
            return respond(
                None,
                "Could not find a phone number listed for that user. Please try again once they update their profile."
            )
        else:
            log.info(
                json.dumps({
                    "message":
                    "Found contact info for {}. Attempting SMS send.".format(
                        recipient)
                }))
            content = MESSAGE_TEMPLATE.format(user=user,
                                              team=team_domain,
                                              channel=channel,
                                              body=emoji.emojize(
                                                  text, use_aliases=True))
            message = Message(to=recipient_number,
                              from_=FLOWROUTE_NUMBER,
                              content=content)
            try:
                sms_controller.create_message(message)
            except Exception as e:
                log.error(
                    json.dumps({
                        "message": "Failed to send SMS",
                        "exc": e
                    }))
                return respond(None, "Unable to send SMS, please try again.")
            else:
                log.info(
                    json.dumps({
                        "message":
                        "Successfully sent SMS to {}".format(recipient)
                    }))
                return respond(None, "Successfully sent SMS!")
    if event_body['type'] == 'interactive_message':
        log.info(
            json.dumps({
                "message":
                ("Received interactive message event with callback_id {}."
                 " Retrieving message context.").format(
                     event_body['callback_id'])
            }))
        user_response = event_body['actions'][0].get('value')
        if user_response == 'no':
            return respond(
                None,
                "Ok, you can always message them with '/sms' if you change your mind later."
            )
        else:
            if not redis_client:
                log.debug(
                    json.dumps({
                        "message": "Getting redis client connection",
                        "timestamp": str(arrow.get())
                    }))
                redis_client = get_redis_client()
                log.debug(
                    json.dumps({
                        "message": "Got redis client connection",
                        "timestamp": str(arrow.get())
                    }))
            try:
                message_context = redis_client.get(event_body['callback_id'])
            except Exception as e:
                log.error(
                    json.dumps({
                        "message": "Failed to get event from Redis",
                        "exc": e
                    }))
                return respond(None, 'Something went wrong, please try again.')
            if not message_context:
                log.error(
                    json.dumps({
                        "message":
                        "Callback id {} not found in Redis".format(
                            event_body['callback_id'])
                    }))
                return respond(None, 'Session not found. Sorry!')
            else:
                event_context = json.loads(message_context)
                log.debug(
                    json.dumps({
                        "message": "interactive event context",
                        "context": event_context
                    }))
                sender_id = event_context['sender']
                channel_id = event_context['channel']
                for recipient in event_context['recipients']:
                    try:
                        recipient_number = USER_INFO[recipient]['number']
                        recipient_name = USER_INFO[recipient]['name']
                    except KeyError:
                        log.warning(
                            json.dumps({
                                "message":
                                "Unable to find contact number for user {}. Refreshing global contact info before returning."
                                .format(recipient)
                            }))
                        USER_INFO = get_member_info(client=sc)
                        NAME_MAP = build_user_name_map(USER_INFO)
                        try:
                            recipient_number = USER_INFO[recipient]['number']
                            recipient_name = USER_INFO[recipient]['name']
                        except KeyError:
                            log.debug(
                                json.dumps({
                                    "message":
                                    "unable to find contact number for user",
                                    "recipient_id": recipient,
                                    "user_info": USER_INFO,
                                    "name_map": NAME_MAP,
                                    "context": event_context
                                }))
                            log.error(
                                json.dumps({
                                    "message":
                                    "Unable to find contact number for user {}. Returning now."
                                    .format(recipient)
                                }))
                            return (
                                None,
                                "Could not find a contact number for that user."
                            )
                    if not recipient_number:
                        log.info(
                            json.dumps({
                                "message":
                                "Could not find a contact number for {}".
                                format(recipient_name)
                            }))
                        return (
                            None,
                            "Could not find a contact number for that user on their profile."
                        )
                    try:
                        sender_info = USER_INFO.get(sender_id)
                        if not sender_info:
                            log.debug(
                                json.dumps({
                                    "message":
                                    "unable to find contact number for user",
                                    "channel_id": channel_id,
                                    "sender_id": sender_id,
                                    "user_info": USER_INFO,
                                    "name_map": NAME_MAP,
                                    "context": event_context
                                }))
                            return (
                                None,
                                "Could not find info for that user. Please try again."
                            )
                        else:
                            sender_name = sender_info['name']
                        team_domain = TEAM_INFO.get('team_domain')
                        if not team_domain:
                            TEAM_INFO = get_team_info(client=sc)
                            team_domain = TEAM_INFO['team_domain']
                        channel_info = PUBLIC_CHANNELS_INFO.get(channel_id)
                        if not channel_info:
                            PUBLIC_CHANNELS_INFO.update(
                                get_channel_info(channel_id, client=sc))
                            channel_name = PUBLIC_CHANNELS_INFO[channel_id][
                                'name']
                        else:
                            channel_name = PUBLIC_CHANNELS_INFO[channel_id][
                                'name']
                    except Exception as e:
                        log.error(
                            json.dumps({
                                "message": "unable to get information",
                                "channel_id": channel_id,
                                "sender_id": sender_id,
                                "user_info": USER_INFO,
                                "name_map": NAME_MAP,
                                "channel_info": PUBLIC_CHANNELS_INFO,
                                "team_info": TEAM_INFO,
                                "context": event_context,
                                "exc": str(e)
                            }))
                        raise e

                    log.info(
                        json.dumps({
                            "message":
                            "Found contact info for {}. Attempting SMS send.".
                            format(recipient_name)
                        }))
                    human_readable_message = event_context['message'].replace(
                        '<@{}>'.format(recipient),
                        "@{}".format(recipient_name))
                    log.debug(
                        json.dumps({
                            "message": "sms message",
                            "sms": human_readable_message
                        }))
                    content = MESSAGE_TEMPLATE.format(
                        user=sender_name,
                        team=team_domain,
                        channel=channel_name,
                        body=emoji.emojize(human_readable_message,
                                           use_aliases=True))
                    message = Message(to=recipient_number,
                                      from_=FLOWROUTE_NUMBER,
                                      content=content)
                    try:
                        sms_controller.create_message(message)
                    except Exception as e:
                        log.error(
                            json.dumps({
                                "message": "Failed to send SMS",
                                "exc": str(e)
                            }))
                        return respond(
                            None, "Unable to send SMS, please try again.")
                    else:
                        log.info(
                            json.dumps({
                                "message":
                                "Successfully sent SMS to {}".format(recipient)
                            }))
                return respond(None, "Successfully sent!")
    elif event_body['type'] == 'event_callback':
        log.debug(
            json.dumps({
                "message": "event callback body",
                "body": event_body
            }))
        # It's a channel message event
        event = event_body['event']
        # TODO make sure this isn't a duplicate request
        event_id = event_body['event_id']

        if event['type'] == 'message':
            if event_body.get('subtype') == 'message_changed' and event.get(
                    'hidden') == True:
                # This is the ephemeral message change that
                # was just posted back.
                return
            try:
                text = event['text']
            except Exception as e:
                log.info(
                    json.dumps({
                        "message": "unknown message event with no text",
                        "body": event_body
                    }))
                return
            # lookup channel, team, and user

            channel = event['channel']
            sender = event['user']
            timestamp = event['ts']
            mentioned_users = look_for_mentions(text)
            if mentioned_users:
                away_users = []
                for user_id in mentioned_users:
                    presence = get_user_presence(user_id, client=sc)
                    log.debug(
                        json.dumps({
                            "message":
                            "Found mentioned user {} in '{}' public channel message with status {}."
                            .format(user_id, channel, presence)
                        }))
                    if presence != 'active':
                        away_users.append(user_id)
            else:
                log.debug(
                    json.dumps({
                        "message":
                        "Found no mentioned users in '{}' public channel message"
                        .format(channel)
                    }))
                return
            if away_users:
                users_have_numbers = False
                for recipient in away_users:
                    try:
                        recipient_number = USER_INFO[recipient]['number']
                        recipient_name = USER_INFO[recipient]['name']
                    except KeyError:
                        log.warning(
                            json.dumps({
                                "message":
                                "Unable to find contact number for user {}. Refreshing global"
                                " contact info before returning.".format(
                                    recipient)
                            }))
                        USER_INFO = get_member_info(client=sc)
                        NAME_MAP = build_user_name_map(USER_INFO)
                    else:
                        if recipient_number:
                            log.debug(
                                json.dumps({
                                    "message": "Found number of away users",
                                    "user_id": recipient,
                                    "number": recipient_number
                                }))
                            users_have_numbers = True
                if not users_have_numbers:
                    log.info({
                        "message":
                        "None of the away users mentioned have phone numbers listed."
                    })
                    return
                log.info(
                    json.dumps({
                        "message":
                        "Found {} non-active users in '{}' public channel message. Sending message prompt."
                        .format(len(away_users), channel),
                        "users":
                        away_users
                    }))
                if not redis_client:
                    log.debug(
                        json.dumps({
                            "message": "Getting redis client connection",
                            "timestamp": str(arrow.get())
                        }))
                    redis_client = get_redis_client()
                    log.debug(
                        json.dumps({
                            "message": "Got redis client connection",
                            "timestamp": str(arrow.get())
                        }))
                store_event_context(event_id,
                                    channel,
                                    sender,
                                    away_users,
                                    timestamp,
                                    text,
                                    client=redis_client)
                send_message_prompt(event_id, sender, channel, client=sc)
                log.info(
                    json.dumps({
                        "message":
                        "Successfully posted ephemeral prompt to {} in channel {}"
                        .format(sender, channel),
                        "callback_id":
                        event_id
                    }))
                return respond(None, 'Successfully sent prompt')
            else:
                log.debug(
                    json.dumps({
                        "message":
                        "Found no away users in '{}' public channel message mentions."
                    }))
                return
Ejemplo n.º 15
0
def home(request):
    fees = get_fees()
    params = { 'fees': fees, }
    
    return respond('home.html', params)
Ejemplo n.º 16
0
def page_not_found(request):
    return respond('404.html')
Ejemplo n.º 17
0
def index(request):
  user = users.GetCurrentUser()
  return common.respond(request, user, 'index')
Ejemplo n.º 18
0
      return http.HttpResponseNotFound('No listing exists with that key (%r)' %
                                       listing_id)

  form = ListingForm(data=request.POST or None, instance=listing)

  if not request.POST:
    return common.respond(request, user, 'listing', {'form': form, 'listing':listing})

  errors = form.errors
  if not errors:
    try:
      listing = form.save(commit=False)
    except ValueError, err:
      errors['__all__'] = unicode(err)
  if errors:
    return common.respond(request, user, 'listing', {'form': form, 'listing': listing})

  if not listing.creator:
    listing.creator = user
  listing.put()

  return http.HttpResponseRedirect('/')

def new(request):
  """Create a listing.  GET shows a blank form, POST processes it."""
  return edit(request, None)

def delete(request ,listing_id):
  """Delete a listing."""
  if request.DELETE:
    return http.HttpResponseRedirect('/')
Ejemplo n.º 19
0
def list(request):
  user = users.GetCurrentUser()
  listings = db.GqlQuery('SELECT * FROM Listing ORDER BY created DESC')
  return common.respond(request, user, 'list', {'listings': listings })