Example #1
0
 def get_message_new(self,  since = int(back_dates(time.time(), days = 10)), untill = int(time.time())):
     messages = self.fb.request(str(self.id))
     prova.i += 1
     messages["author"] = get_user(self.fb, messages["from"]["id"])
     messages["to"] = [get_user(self.fb, user["id"]) for user in messages["to"]["data"]]
     if "comments" in messages:
         for m in messages["comments"]["data"]:
             m["author"] = get_user(self.fb, m["from"]["id"])
         while time.mktime(time.strptime(messages["comments"]["data"][-1]["created_time"], "%Y-%m-%dT%H:%M:%S+0000")) > since:
             time.sleep(0.5)
             to_add = simple_request(messages["comments"]["paging"]["next"])
             prova.i += 1
             for m in to_add["data"]:
                 m["author"] = get_user(self.fb, m["from"]["id"])
             messages["comments"]["data"].extend(to_add["data"])
             if "paging" in to_add:
                 messages["comments"]["paging"] = to_add["paging"]
             else:
                 self.update(messages)
                 return
             print "\n"*5
             print to_add
             print "\n"*5
             print messages
             print prova.i
     else:
         messages["comments"] = []
         #self.update(messages)
         #return
     self.update(messages)
     return
Example #2
0
 def get_todos(self, request):
     get_user() #check auth
     
     done = True if request.done == 'true' else False
     todo_items = [todo.to_message() for todo in Todo.get_todos_of_user(done)]
     
     return TodoListResponseMessage(items=todo_items)
    def run(self):
        global local_server_diff
        logger.info('AttackThread start, will attack %d times'%(Times))
        logger.info('I will attack peoples: ' + ' '.join(People_List))
        if Delay_Time > 0:
            logger.info('I will start attack at ' + util.next_time(Delay_Time))
            time.sleep(Delay_Time)
        user = People_List[0]
        uid = PEOPLE_ID[user]
        # get user info
        next_time = 0
        ci = 1
        uinfo = util.get_user(uid)
        protectTime = int(uinfo['protectTime'])
        serverTime = int(uinfo['serverTime'])
        sp = protectTime - serverTime + 1
        logger.info('protectTime:%d'%(protectTime))
        #if int(protectTime) == 0:
        if sp < 2:
            self.do_attack(user)
            time.sleep(1)
            uinfo = util.get_user(uid)
            protectTime = int(uinfo['protectTime'])
            serverTime = int(uinfo['serverTime'])
            sp = protectTime - serverTime + 1
            ci += 1

        #server_time, local_server_diff = util.sync_time()
        #sp = util.get_sleep_time(protectTime, local_server_diff)
        logger.info('Attacked %d time, next attack will start at %s'%(ci-1, util.next_time(sp)))
        time.sleep(sp)

        while ci <= Times:
            self.do_attack(user)
            if ci >= Times:
                logger.info('Attacked %d time, I will exit'%(ci))
                break
            time.sleep(1)
            uinfo = util.get_user(uid)
            protectTime = int(uinfo['protectTime'])
            serverTime = int(uinfo['serverTime'])
            sp = protectTime - serverTime + 1
            if sp < 2:
                logger.info('Not in protectTime after attack, will exit')
                break
            else:
                #sp = util.get_sleep_time(protectTime, local_server_diff)
                logger.info('Attacked %d time, I will sleep %d seconds for next attack'%(ci, sp))
                if sp < 0:
                    break
                time.sleep(sp)
            ci += 1
Example #4
0
 def POST(self):
     d = web.input()
     t = template.env.get_template("message.html")
     sender = util.get_user(user_id=d.sender_id)
     recipient = util.get_user(user_id=d.recipient_id)
     message = EmailMessage(
         sender=" ".join([sender.nickname, "<" + (sender.user.email() or "*****@*****.**") + ">"]),
         subject=" ".join(["The Connection Machine:", sender.nickname, "wants to get in touch!"]),
         to=recipient.user.email(),
         reply_to=sender.user.email() or "*****@*****.**",
         body=t.render(msg=d.message, sender=sender.id or "us", site=web.ctx.homedomain, plain_text=True),
         html=t.render(msg=d.message, sender=sender.id or "us", site=web.ctx.homedomain),
     )
     message.send()
Example #5
0
 def GET(self):
     user = users.get_current_user()
     if user:
         e = util.get_user(user=user)
         if e.shared is not None:
             f = prefs_form(
                 first_name="first_name" in e.shared.public,
                 middle_name="middle_name" in e.shared.public,
                 last_name="last_name" in e.shared.public,
                 city="city" in e.shared.public,
                 state="state" in e.shared.public,
                 postal_code="postal_code" in e.shared.public,
                 country="country" in e.shared.public,
                 bio="bio" in e.shared.public,
             )
         else:  # If e.shared if empty then set default to False.
             f = prefs_form(
                 first_name=False,
                 middle_name=False,
                 last_name=False,
                 city=False,
                 state=False,
                 postal_code=False,
                 country=False,
                 bio=False,
             )
         return t.render(
             util.data(
                 form=f, title="Preferences", instructions="Please indicate which items you wish to make public."
             )
         )
     else:
         return t.render(util.data(title="Not Logged In", instructions="Please log in to have preferences!"))
Example #6
0
 def POST(self):
     user = users.get_current_user()
     d = web.input(
         first_name=False,
         middle_name=False,
         last_name=False,
         city=False,
         state=False,
         postal_code=False,
         country=False,
         bio=False,
     )
     f = profile_form(
         first_name=d.first_name,
         middle_name=d.middle_name,
         last_name=d.last_name,
         city=d.city,
         state=d.state,
         postal_code=d.postal_code,
         country=d.country,
         bio=d.bio,
     )
     if not f.validate():
         return t.render(
             util.data(
                 form=f, title="Preferences", instructions="Please indicate which items you wish to make public."
             )
         )
     else:
         prefs = [i.name for i in f if i.data]
         e = util.get_user(user=user)
         e.shared.public = prefs
         e.shared.put()
         mdel(key=user.user_id(), namespace="profile_data")
         raise web.seeother("/preferences")
Example #7
0
 def GET(self, user_id):
     t = template.env.get_template("profile.html")
     if user_id.lower() == "us":
         user_info = {
             "nickname": "Mr. Roboto",
             "first_name": "The",
             "middle_name": "Connection",
             "last_name": "Machine",
             "city": "Google App Engine",
             "state": "The Internet",
         }
     else:
         try:
             e = util.get_user(user_id=user_id.lower())
             user_info = util.strip_private_data(e)
         except AttributeError:
             user_info = {
                 "nickname": "[deleted]",
                 "first_name": "No",
                 "middle_name": "such",
                 "last_name": "user",
                 "city": "reddit.com",
                 "state": "The Internet",
             }
     return t.render(util.data(info=user_info, user_id=user_id))
Example #8
0
 def GET(self):
     user = users.get_current_user()
     if user:
         e = util.get_user(user=user)
         f = profile_form()
         if e.bio:
             f = profile_form(
                 nickname=e.nickname,
                 first_name=e.bio.first_name,
                 middle_name=e.bio.middle_name,
                 last_name=e.bio.last_name,
                 city=e.bio.city,
                 state=e.bio.state,
                 postal_code=e.bio.postal_code,
                 country=e.bio.country,
                 bio=e.bio.bio,
             )
         return t.render(
             util.data(
                 form=f,
                 title="Edit Profile",
                 instructions="""Please enter whatever information you feel comfortable
         sharing. (Please note that your information is not public until you
         grant us permission to share it in your Preferences)""",
             )
         )
     else:
         return t.render(util.data(title="Not Logged In!", instructions="Please Log in to Edit Your Profile"))
Example #9
0
 def get_data(self):
     data = self.fb.request(str(self.id))
     message = data["message"]
     date = data["updated_time"]
     starter = get_user(self.fb, data["from"]["id"])
     self.update({"updated_time" : date, "message" : message, "from" : starter})
     return self
Example #10
0
File: keys.py Project: daisy/lion
def get_keyboard_translation_flags(session):
    langid = util.get_user(session)["users.langid"]
    session.execute_query("""SELECT translate_mnemonics, translate_accelerators FROM
        languages WHERE langid="%s" """ % langid)
    mnem1, accel1 = session.cursor.fetchone()
    mnem2 = session.has_mnemonics()
    accel2 = session.has_accelerators()
    return (mnem1 & mnem2, accel1 & accel2)
Example #11
0
 def index(self):
     """Show the page"""
     user = util.get_user(self.session)
     if user == None:
         e = errorpage.ErrorPage(self.session, "Login error")
         return e.index()
     self.user = user
     self.language = user["languages.langname"]
     return self.respond()
Example #12
0
 def get_todos_of_user(cls, done):        
     query = Todo.query(Todo.user_email == get_user().email()) #TODO
     query = query.filter(Todo.is_done == done)
     
     return query.fetch()
         
         
    
     
Example #13
0
 def get_message(self,  since = int(back_dates(time.time(), days = 10)), untill = int(time.time())):
     query = "SELECT body, author_id, attachment, created_time FROM message WHERE thread_id = " + str(self.id) + " and created_time > " + str(since) + " and created_time < " + str(untill) + " ORDER BY created_time ASC"
     messages = self.fb.fql(query)
     for message in messages:
         message["author"] = get_user(self.fb, message["author_id"])
     if len(messages) >= 20:
         self._get_more_message(messages, since, untill)
     self["comments"] = messages
     return messages
Example #14
0
 def index(self):
     """Show the page"""
     user = util.get_user(self.session)
     if user == None:
         e = errorpage.ErrorPage(self.session, "Login error")
         return e.index()
     self.user = user
     self.language = user["languages.langname"]
     self.prompts_uri = self.generate_prompts_zipfile()
     return self.respond()
Example #15
0
    def get(self):
        if not users.get_current_user():
            return _login_page(self.request, self)

        user_email = self.request.get("u", _current_user_email())
        user = util.get_user(user_email)

        if not user:
            # If there are no app settings, set those up before setting
            # up the user settings.
            if users.is_current_user_admin():
                try:
                    models.AppSettings.get()
                except ValueError:
                    self.redirect(
                        "/admin/settings?redirect_to=user_setting"
                        "&msg=Welcome+to+the+snippet+server!+"
                        "Please+take+a+moment+to+configure+it."
                    )
                    return

            template_values = {
                "new_user": True,
                "login_url": users.create_login_url(self.request.uri),
                "logout_url": users.create_logout_url("/"),
                "username": user_email,
            }
            self.render_response("new_user.html", template_values)
            return

        snippets = util.snippets_for_user(user_email)

        if not _can_view_private_snippets(_current_user_email(), user_email):
            snippets = [snippet for snippet in snippets if not snippet.private]
        snippets = util.fill_in_missing_snippets(snippets, user, user_email, _TODAY_FN())
        snippets.reverse()  # get to newest snippet first

        template_values = {
            "logout_url": users.create_logout_url("/"),
            "message": self.request.get("msg"),
            "username": user_email,
            "is_admin": users.is_current_user_admin(),
            "domain": user_email.split("@")[-1],
            "view_week": util.existingsnippet_monday(_TODAY_FN()),
            # Snippets for the week of <one week ago> are due today.
            "one_week_ago": _TODAY_FN().date() - datetime.timedelta(days=7),
            "eight_days_ago": _TODAY_FN().date() - datetime.timedelta(days=8),
            "editable": (_logged_in_user_has_permission_for(user_email) and self.request.get("edit", "1") == "1"),
            "user": user,
            "snippets": snippets,
            "null_category": models.NULL_CATEGORY,
        }
        self.render_response("user_snippets.html", template_values)
Example #16
0
def tasks(request):
    """
    View for all tasks

    :type request: Request
    :param request: The pyramid request object
    """

    user = util.get_user(request)
    return dict(
            title = 'tasks',
            user = user)
Example #17
0
def profile(request, username=None):
  curr_page = False
  if username == None:
    return HttpResponseRedirect('/profile')
  else:
    if username == request.user.username:
      curr_page = 'profile-view'
    user = util.get_user(username)

  if user is None:
    raise Http404

  # Are we friends?
  prof.start('profile-check-friend')
  count = Friends.objects.filter(Q(user=request.user, friend=user) | Q(user=user, friend=request.user)).count()
  if count > 0:
    is_my_friend = True
  else:
    is_my_friend = False
  prof.stop('profile-check-friend')

  # Discover all accepted friends
  prof.start('profile-accepted-friends')
  friends_count = Friends.objects.filter(Q(friend=user) | Q(user=user)).filter(accepted=True).count()
  friends = Friends.objects.filter(Q(friend=user) | Q(user=user)).filter(accepted=True).values('user', 'friend')[:const.FriendsConst.PROFILE_FRIENDS]
  ids = []
  for friend in [friend.values() for friend in friends]:
    if friend[0] != user.id:
      ids.append(friend[0])
    if friend[1] != user.id:
      ids.append(friend[1])
  friends_profiles = list(Profile.objects.filter(user__in=ids).select_related(depth=1))
  prof.stop('profile-accepted-friends')

  # Build forms
  form_add_news = AddNewsInlineForm(initial={'about_id': user.id, 'video': 'http://'})
  form_profile = ProfileForm(initial={'first_name': request.user.first_name,
                             'last_name': request.user.last_name},
                             instance=user.get_profile())

  return render_to_response('profile/profile.html',
                            {'req_user': user,
                            'add_news_about_name_hide': True,
                            'form_add_news': form_add_news,
                            'form_profile': form_profile,
                            'curr_page': curr_page,
                            'is_my_friend': is_my_friend,
                            'friends_count': friends_count,
                            'friends_profiles': friends_profiles,
                            'js': ('profile.js', 'news.js',
                            'jquery-multifile.js', 'jquery-form.js', 'jquery-ui.js'),
                            'css': ('ui/ui.css', )},
                            context_instance=RequestContext(request))
Example #18
0
    def get(self):
        if not users.get_current_user():
            return _login_page(self.request, self)

        user_email = self.request.get('u', _current_user_email())
        user = util.get_user(user_email)

        if not user:
            # If there are no app settings, set those up before setting
            # up the user settings.
            if users.is_current_user_admin():
                try:
                    models.AppSettings.get()
                except ValueError:
                    self.redirect("/admin/settings?redirect_to=user_setting"
                                  "&msg=Welcome+to+the+snippet+server!+"
                                  "Please+take+a+moment+to+configure+it.")
                    return

            template_values = {
                'new_user': True,
                'login_url': users.create_login_url(self.request.uri),
                'logout_url': users.create_logout_url('/'),
                'username': user_email,
            }
            self.render_response('new_user.html', template_values)
            return

        snippets = util.snippets_for_user(user_email)

        if not _can_view_private_snippets(_current_user_email(), user_email):
            snippets = [snippet for snippet in snippets if not snippet.private]
        snippets = util.fill_in_missing_snippets(snippets, user,
                                                 user_email, _TODAY_FN())
        snippets.reverse()                  # get to newest snippet first

        template_values = {
            'logout_url': users.create_logout_url('/'),
            'message': self.request.get('msg'),
            'username': user_email,
            'is_admin': users.is_current_user_admin(),
            'domain': user_email.split('@')[-1],
            'view_week': util.existingsnippet_monday(_TODAY_FN()),
            # Snippets for the week of <one week ago> are due today.
            'one_week_ago': _TODAY_FN().date() - datetime.timedelta(days=7),
            'eight_days_ago': _TODAY_FN().date() - datetime.timedelta(days=8),
            'editable': (_logged_in_user_has_permission_for(user_email) and
                         self.request.get('edit', '1') == '1'),
            'user': user,
            'snippets': snippets,
            'null_category': models.NULL_CATEGORY,
        }
        self.render_response('user_snippets.html', template_values)
Example #19
0
def _get_or_create_user(email, put_new_user=True):
    """Return the user object with the given email, creating if if needed.

    Considers the permissions scope of the currently logged in web user,
    and raises an IndexError if the currently logged in user is not the same as
    the queried email address (or is an admin).

    NOTE: Any access that causes _get_or_create_user() is an access that
    indicates the user is active again, so they are "unhidden" in the db.
    """
    user = util.get_user(email)
    if user:
        if user.is_hidden:
            # Any access that causes _get_or_create_user() is an access
            # that indicates the user is active again, so un-hide them.
            # TODO(csilvers): move this get/update/put atomic into a txn
            user.is_hidden = False
            user.put()
    elif not _logged_in_user_has_permission_for(email):
        # TODO(csilvers): turn this into a 403 somewhere
        raise IndexError('User "%s" not found; did you specify' " the full email address?" % email)
    else:
        # You can only create a new user under one of the app-listed domains.
        try:
            app_settings = models.AppSettings.get()
        except ValueError:
            # TODO(csilvers): do this instead:
            #                 /admin/settings?redirect_to=user_setting
            return None

        domain = email.split("@")[-1]
        allowed_domains = app_settings.domains
        if domain not in allowed_domains:
            # TODO(csilvers): turn this into a 403 somewhere
            raise RuntimeError(
                "Permission denied: "
                "This app is for users from %s."
                " But you are from %s." % (" or ".join(allowed_domains), domain)
            )

        # Set the user defaults based on the global app defaults.
        user = models.User(
            created=_TODAY_FN(),
            email=email,
            uses_markdown=app_settings.default_markdown,
            private_snippets=app_settings.default_private,
            wants_email=app_settings.default_email,
        )
        if put_new_user:
            db.put(user)
            db.get(user.key())  # ensure db consistency for HRD
    return user
Example #20
0
def index_view(request):
    """
    View for the index page

    :type request: Request
    :param request: The pyramid request object
    """

    user = util.get_user(request)
    users_tasks = util.get_assigned_tasks(user.id)
    return dict(
            title = "index",
            user = user,
            u_tasks = users_tasks,)
Example #21
0
File: main.py Project: daisy/lion
 def index(self):
     """Show the links for the main menu"""
     user = util.get_user(self.session)
     if user == None:
         self.session.warn("No user logged in for this session.")
         e = errorpage.ErrorPage(self.session, "Login error")
         return e.index()
     else:
         self.user = user["users.realname"]
         self.language = user["languages.langname"]
         self.session.execute_query("""SELECT addldocsuri, addldocsdesc FROM
             application WHERE appid="%s" """ % self.appid)
         self.addldocsuri, self.addldocsdesc = self.session.cursor.fetchone()
         self.translate_mnemonics, self.translate_accelerators = \
             keys.get_keyboard_translation_flags(self.session)
         return self.respond()
Example #22
0
 def put_from_message(cls, message):
     entity = None
     
     if hasattr(message, 'id') and message.id != None:
         entity = ndb.Key('Todo',message.id).get()
         entity.text = message.text
         entity.is_done = True if message.is_done == 'true' else False
     else:
         entity = cls(
             user_email=get_user().email(),
             text=message.text,
             is_done=True if message.is_done == 'true' else False
         )
         
     entity.put()
     
     return entity
Example #23
0
    def index(self, view, id_anchor=""):
        """Show the big table of translate-able items"""
        self.last_view = view
        user = util.get_user(self.session)
        if user == None:
            e = errorpage.ErrorPage(self.session, "Login error")
            return e.index()
        self.user = user
        self.language = user["languages.langname"]
        self.view_description = VIEW_DESCRIPTIONS[view]
        self.form, self.count = self.make_table(view, self.pagenum)
        self.targetid = id_anchor
        # calculate the num pages for the base class
        self.total_num_pages = self.get_total_num_pages()
        self.warnings = self.get_all_warnings()
        self.translate_mnemonics, self.translate_accelerators = keys.get_keyboard_translation_flags(self.session)

        return self.respond()
Example #24
0
 def POST(self):
     user = users.get_current_user()
     d = web.input()
     f = profile_form(
         nickname=d.nickname,
         first_name=d.first_name,
         middle_name=d.middle_name,
         last_name=d.last_name,
         city=d.city,
         state=d.state,
         postal_code=d.postal_code,
         country=d.country,
         bio=d.bio,
     )
     if not f.validate():
         return t.render(
             util.data(
                 form=f,
                 title="Edit Profile",
                 instructions="""Please enter whatever information you feel comfortable
         sharing. (Please note that your information is not shared.public until you
         grant us permission to share it in your Preferences)""",
             )
         )
     else:
         e = util.get_user(user=user)
         if e.nickname:
             e.nickname = f.nickname.data
             db.put(e)
         e.bio.first_name = f.first_name.data or ""
         e.bio.middle_name = f.middle_name.data or ""
         e.bio.last_name = f.last_name.data or ""
         e.bio.city = f.city.data or ""
         e.bio.state = f.state.data or ""
         e.bio.postal_code = f.postal_code.data or ""
         e.bio.country = f.country.data or ""
         e.bio.bio = f.bio.data or ""
         e.bio.put()
         mdel(key=user.user_id(), namespace="profile_data")
         raise web.seeother("/profile")
Example #25
0
 def get_user(self):
     """Return the user for this outline."""
     if self.__user is None:
         return util.get_user()
     else:
         return self.__user
Example #26
0
if not os.path.isdir(pg_data):
    os.mkdir(pg_data)

## SVCUSER ###########################################
svcuser = ""
curr_user = ""

if util.get_platform() == "Linux":
    svcuser = args.svcuser
    if util.is_admin():
        if svcuser == "":
            svcuser = "******"
    else:
        if svcuser > "":
            fatal_error("ERROR: --svcuser cannot be specified if not root")
        svcuser = util.get_user()
        curr_user = svcuser

## PASSWD #############################################
is_password = False
pgpass_file = pg_home + os.sep + ".pgpass"
if args.pwfile:
    pgpass_file = args.pwfile
    if not os.path.isfile(pgpass_file):
        fatal_error("Error: Invalid --pwfile")

if os.path.isfile(pgpass_file):
    is_password = True
    file = open(pgpass_file, 'r')
    line = file.readline()
    pg_password = line.rstrip()
Example #27
0
        fatal_error("ERROR: datadir not empty - " + pg_data)
else:
    os.mkdir(pg_data)

## SVCUSER ###########################################
svcuser = ""
curr_user = ""
if util.get_platform() == "Linux":
    svcuser = args.svcuser
    if util.is_admin():
        if svcuser == "":
            svcuser = "******"
    else:
        if svcuser > "":
            fatal_error("ERROR: --svcuser cannot be specified if not root")
        svcuser = util.get_user()
        curr_user = svcuser

## PASSWD #############################################
is_password = False
pgpass_file = pg_home + os.sep + ".pgpass"
if args.pwfile:
    pgpass_file = args.pwfile
    if not os.path.isfile(pgpass_file):
        fatal_error("Error: Invalid --pwfile")

if os.path.isfile(pgpass_file):
    is_password = True
    file = open(pgpass_file, 'r')
    line = file.readline()
    pg_password = line.rstrip()
Example #28
0
 def get_data(self):
     self.get_field(type_to_fields["photos"])
     self.update({"from" : get_user(self.fb, self["from"]["id"])})
     return self
Example #29
0
def info(p_json, p_home, p_repo, print_flag=True):
    import os

    p_user = util.get_user()
    p_is_admin = util.is_admin()

    this_os = ""
    this_uname = str(platform.system())
    host_ip = util.get_host_ip()
    wmic_path = os.getenv(
        "SYSTEMROOT",
        "") + os.sep + "System32" + os.sep + "wbem" + os.sep + "wmic"
    if this_uname == "Windows":
        import psutil
        host_display = os.getenv('LOGONSERVER',
                                 '') + '\\' + os.getenv('COMPUTERNAME')
        system_cpu_cores = os.getenv('NUMBER_OF_PROCESSORS', '1')
        os_arch = os.getenv('PROCESSOR_ARCHITECTURE', '')
        cpu_model = check_output_wmic([wmic_path, "cpu", "get", "name"])
        ## system_memory_in_gb ######################################
        m = psutil.virtual_memory().total
        mem_bytes = int(m)
        system_memory_in_kbytes = mem_bytes / 1024.0
        system_memory_in_gb = str(mem_bytes / (1024.0**3))
    else:
        os_arch = util.getoutput("uname -m")
        HOST = util.get_host_short()
        host_display = "{0} {1}".format(HOST, host_ip)

    ## Check the OS & Resources ########################################
    plat = util.get_os()
    if this_uname == "Darwin":
        system_memory_in_bytes = int(
            util.getoutput("/usr/sbin/sysctl hw.memsize | awk '{print $2}'"))
        system_memory_in_kbytes = system_memory_in_bytes / 1024
        system_memory_in_gb = system_memory_in_bytes / 1024 / 1024 / 1024
        system_cpu_cores = int(
            util.getoutput(
                "/usr/sbin/sysctl hw.physicalcpu | awk '{print $2}'"))
        cpu_model = util.getoutput(
            "/usr/sbin/sysctl -n machdep.cpu.brand_string")
        prod_name = util.getoutput("sw_vers -productName")
        prod_version = util.getoutput("sw_vers -productVersion")
        this_os = prod_name + " " + prod_version
    elif this_uname == "Linux":
        system_memory_in_kbytes = int(
            util.getoutput("cat /proc/meminfo | awk '/MemTotal/ {print $2}'"))
        system_memory_in_gb = system_memory_in_kbytes / 1024.0 / 1024.0
        system_cpu_cores = int(
            util.getoutput(
                "egrep -c 'processor([[:space:]]+):.*' /proc/cpuinfo"))
        cpu_model = util.getoutput(
            "grep 'model name' /proc/cpuinfo | head -1 | cut -d':' -f2")
        if os.path.exists("/etc/redhat-release"):
            this_os = util.getoutput("cat /etc/redhat-release")
        elif os.path.exists("/etc/system-release"):
            this_os = util.getoutput("cat /etc/system-release")
        elif os.path.exists("/etc/lsb-release"):
            this_os = util.getoutput(
                "cat /etc/lsb-release | grep DISTRIB_DESCRIPTION | cut -d= -f2 | tr -d '\"'"
            )
    elif this_uname == "Windows":
        caption = check_output_wmic([wmic_path, "os", "get", "caption"])
        svcpack = check_output_wmic(
            [wmic_path, "os", "get", "servicepackmajorversion"])
        if svcpack == "0":
            this_os = caption
        else:
            this_os = caption + ", SP " + svcpack

    round_mem = util.pretty_rounder(float(system_memory_in_gb), 1)
    mem = str(round_mem) + " GB"

    cores = str(system_cpu_cores) + " x"

    cpu = cpu_model.strip()
    cpu = cpu.replace("(R)", "")
    cpu = cpu.replace("(TM)", "")
    cpu = cpu.replace(" CPU ", " ")

    os = this_os.replace(" release ", " ")
    os = os.replace(" (Final)", "")

    arch = os_arch.replace("x86_64", "x64")
    arch = arch.replace("AMD64", "x64")

    ver = util.get_pgc_version()
    [last_update_utc, last_update_local,
     unique_id] = util.read_hosts('localhost')
    if last_update_local:
        last_upd_dt = datetime.strptime(last_update_local, "%Y-%m-%d %H:%M:%S")
        time_diff = int(
            util.timedelta_total_seconds(datetime.now() - last_upd_dt))
        last_update_readable = util.get_readable_time_diff(str(time_diff),
                                                           precision=2)

    versions_sql = util.get_versions_sql()

    if p_json:
        infoJsonArray = []
        infoJson = {}
        infoJson['version'] = ver
        infoJson['home'] = p_home
        infoJson['user'] = p_user
        infoJson['host'] = host_display
        infoJson['host_short'] = util.get_host_short()
        infoJson['host_long'] = util.get_host()
        infoJson['host_ip'] = util.get_host_ip()
        infoJson['os'] = unicode(str(os),
                                 sys.getdefaultencoding(),
                                 errors='ignore').strip()
        infoJson['platform'] = unicode(str(plat),
                                       sys.getdefaultencoding(),
                                       errors='ignore').strip()
        infoJson['arch'] = arch
        infoJson['mem'] = round_mem
        infoJson['cores'] = system_cpu_cores
        infoJson['cpu'] = cpu
        infoJson['last_update_utc'] = last_update_utc
        if last_update_local:
            infoJson['last_update_readable'] = last_update_readable
        infoJson['unique_id'] = unique_id
        infoJson['repo'] = p_repo
        infoJson['versions_sql'] = versions_sql
        infoJson['system_memory_in_kb'] = system_memory_in_kbytes
        infoJson['python_ver'] = python_ver
        infoJson['python_exe'] = python_exe
        if pip_ver != 'None':
            infoJson['pip_ver'] = pip_ver
        infoJsonArray.append(infoJson)
        if print_flag:
            print(json.dumps(infoJsonArray, sort_keys=True, indent=2))
            return
        else:
            return infoJson

    if p_is_admin:
        admin_display = " (Admin)"
    else:
        admin_display = ""

    print(style_start + ("#" * 70) + style_end)
    print(style_start + "#             PGC: " + style_end + "v" + ver + "  " +
          p_home)
    print(style_start + "#     User & Host: " + style_end + p_user +
          admin_display + "  " + host_display)
    print(style_start + "#        Platform: " + style_end + plat + " | " +
          os.rstrip())
    if pip_ver != "None":
        print(style_start + "#          Python: " + style_end + python_ver +
              " | " + python_exe)
    else:
        print(style_start + "#          Python: " + style_end + "v" +
              python_ver + " | " + python_exe)
    print(style_start + "#        Hardware: " + style_end + mem + ", " +
          cores + " " + cpu)

    default_repo = "https://s3.amazonaws.com/pgcentral"
    if p_repo != default_repo:
        print(style_start + "#        Repo URL: " + style_end + p_repo)

    if versions_sql == "versions.sql":
        pass
    else:
        print(style_start + "#    Versions SQL: " + style_end + versions_sql)
    if not last_update_local:
        last_update_local = "None"
    print(style_start + "#     Last Update: " + style_end +
          str(last_update_local))
    print(style_start + ("#" * 70) + style_end)
Example #30
0
 def save_todo(self, request):
     get_user() #check auth
     
     todo = Todo.put_from_message(request)
     
     return todo.to_message()
Example #31
0
[email protected]

setpassword.py

Prompts for password and stores encryption key and encrypted password.

"""

import util
import getpass

# Get configuration directories

util.get_directories()

# Get Oracle user name

util.get_user()

# Prompt for password for Oracle user name

password = getpass.getpass('Enter password for ' + util.my_oracle_user + ': ')

# Save encryption key

util.save_key()

# Save encrypted password

util.save_oracle_password(password)
import sys
import os

from fabric.api import sudo, hosts, env, task, run, cd, roles
from fabric.decorators import runs_once
from fabric.operations import put
from fabric.contrib.files import exists, contains

from util import get_nodes, get_user, get_password

env.user = get_user()
env.password = get_password()
env.warn_only = True

nodes = get_nodes()

env.roledefs.update({
    'nodes': nodes
})

widget_file = "/home/andrew/work/applications/head/widget.rb"
template_file = "/home/andrew/work/applications/head/template.file"


@task
@roles('nodes')
def apt_install(pkg):
    apt_update()
    sudo("apt-get -q -y install %s" % pkg)

setpassword.py

Prompts for password and stores encryption key and encrypted password.

"""

import util
import getpass

# Get configuration directories

util.get_directories()

# Get Oracle user name

util.get_user()

# Prompt for password for Oracle user name
    
password=getpass.getpass('Enter password for '+util.my_oracle_user+': ')

# Save encryption key

util.save_key()

# Save encrypted password

util.save_oracle_password(password)

Example #34
0
def info(p_json, p_home, p_repo, print_flag=True):
    import os, commands

    p_user = util.get_user()
    p_is_admin = util.is_admin()

    this_os = ""
    this_uname = str(platform.system())
    host_ip = util.get_host_ip()
    wmic_path = os.getenv(
        "SYSTEMROOT",
        "") + os.sep + "System32" + os.sep + "wbem" + os.sep + "wmic"
    if this_uname == "Windows":
        import psutil
        host_display = os.getenv('LOGONSERVER',
                                 '') + '\\' + os.getenv('COMPUTERNAME')
        system_cpu_cores = os.getenv('NUMBER_OF_PROCESSORS', '1')
        os_arch = os.getenv('PROCESSOR_ARCHITECTURE', '')
        cpu_model = subprocess.check_output([wmic_path, "cpu", "get",
                                             "name"]).strip().split("\n")[1]
        ## system_memory_in_gb ######################################
        m = psutil.virtual_memory().total
        mem_bytes = int(m)
        system_memory_in_gb = mem_bytes / (1024.0**3)
    else:
        os_arch = commands.getoutput("uname -m")
        HOST = util.get_host_short()
        host_display = HOST + " " + host_ip

    ## Check the OS & Resources ########################################
    plat = util.get_os()
    if this_uname == "Darwin":
        system_memory_in_bytes = int(
            commands.getoutput(
                "/usr/sbin/sysctl hw.memsize | awk '{print $2}'"))
        system_memory_in_gb = system_memory_in_bytes / 1024 / 1024 / 1024
        system_cpu_cores = int(
            commands.getoutput(
                "/usr/sbin/sysctl hw.physicalcpu | awk '{print $2}'"))
        cpu_model = commands.getoutput(
            "/usr/sbin/sysctl -n machdep.cpu.brand_string")
        prod_name = commands.getoutput("sw_vers -productName")
        prod_version = commands.getoutput("sw_vers -productVersion")
        this_os = prod_name + " " + prod_version
    elif this_uname == "Linux":
        system_memory_in_mb = int(
            commands.getoutput("free -m | awk '/Mem:/ {print $2}'"))
        system_memory_in_gb = system_memory_in_mb / 1024.0
        system_cpu_cores = int(
            commands.getoutput(
                "egrep -c 'processor([[:space:]]+):.*' /proc/cpuinfo"))
        cpu_model = commands.getoutput(
            "grep 'model name' /proc/cpuinfo | head -1 | cut -d':' -f2")
        if os.path.exists("/etc/redhat-release"):
            this_os = commands.getoutput("cat /etc/redhat-release")
        elif os.path.exists("/etc/system-release"):
            this_os = commands.getoutput("cat /etc/system-release")
        elif os.path.exists("/etc/lsb-release"):
            this_os = commands.getoutput(
                "cat /etc/lsb-release | grep DISTRIB_DESCRIPTION | cut -d= -f2 | tr -d '\"'"
            )
    elif this_uname == "Windows":
        caption_result = subprocess.check_output(
            [wmic_path, "os", "get", "caption"])
        try:
            caption = str(caption_result).strip().split("\n")[1]
        except UnicodeDecodeError as e:
            caption = unicode(caption_result,
                              sys.getdefaultencoding(),
                              errors='ignore').strip().split("\n")[1]
        svcpack_result = subprocess.check_output(
            [wmic_path, "os", "get", "servicepackmajorversion"])
        try:
            svcpack = str(svcpack_result).strip().split("\n")[1]
        except UnicodeDecodeError as e:
            svcpack = unicode(svcpack_result,
                              sys.getdefaultencoding(),
                              errors='ignore').strip().split("\n")[1]
        if svcpack == "0":
            this_os = caption
        else:
            this_os = caption + ", SP " + svcpack

    round_mem = util.pretty_rounder(system_memory_in_gb, 1)
    mem = str(round_mem) + " GB"

    cores = str(system_cpu_cores) + " x"

    cpu = cpu_model.strip()
    cpu = cpu.replace("(R)", "")
    cpu = cpu.replace("(TM)", "")
    cpu = cpu.replace(" CPU ", " ")

    os = this_os.replace(" release ", " ")
    os = os.replace(" (Final)", "")

    arch = os_arch.replace("x86_64", "x64")
    arch = arch.replace("AMD64", "x64")

    ver = util.get_pgc_version()
    [interval, last_update_utc, next_update_utc,
     unique_id] = util.read_hosts('localhost')

    versions_sql = util.get_versions_sql()

    if p_json:
        infoJsonArray = []
        infoJson = {}
        infoJson['version'] = ver
        infoJson['home'] = p_home
        infoJson['user'] = p_user
        infoJson['host'] = host_display
        infoJson['host_short'] = util.get_host_short()
        infoJson['host_long'] = util.get_host()
        infoJson['host_ip'] = util.get_host_ip()
        infoJson['os'] = unicode(str(os),
                                 sys.getdefaultencoding(),
                                 errors='ignore').strip()
        infoJson['platform'] = unicode(str(plat),
                                       sys.getdefaultencoding(),
                                       errors='ignore').strip()
        infoJson['arch'] = arch
        infoJson['mem'] = round_mem
        infoJson['cores'] = system_cpu_cores
        infoJson['cpu'] = cpu
        infoJson['interval'] = interval
        infoJson['last_update_utc'] = last_update_utc
        infoJson['next_update_utc'] = next_update_utc
        infoJson['unique_id'] = unique_id
        infoJson['repo'] = p_repo
        infoJson['versions_sql'] = versions_sql
        infoJsonArray.append(infoJson)
        if print_flag:
            print(json.dumps(infoJsonArray, sort_keys=True, indent=2))
            return
        else:
            return infoJson

    if p_is_admin:
        admin_display = " (Admin)"
    else:
        admin_display = ""

    print(style_start + ("#" * 75) + style_end)
    print(style_start + "#             PGC: " + style_end + "v" + ver + "  " +
          p_home)
    print(style_start + "#     User & Host: " + style_end + p_user +
          admin_display + "  " + host_display)
    print(style_start + "#   Platform & Os: " + style_end + plat + "  " + os)
    print(style_start + "#        Hardware: " + style_end + mem + ", " +
          cores + " " + cpu)
    print(style_start + "#        Repo URL: " + style_end + p_repo)
    if versions_sql == "versions.sql":
        pass
    else:
        print(style_start + "#    Versions SQL: " + style_end + versions_sql)
    print(style_start + "# Last Update UTC: " + style_end +
          str(last_update_utc))
    if interval:
        print(style_start + "# Update Interval: " + style_end + str(interval))
        print(style_start + "# Next Update UTC: " + style_end +
              str(next_update_utc))
    print(style_start + ("#" * 75) + style_end)