Skip to content

Instantly share code, notes, and snippets.

@averrin
Last active August 29, 2015 14:22
Show Gist options
  • Save averrin/5bd5905c15760515025d to your computer and use it in GitHub Desktop.
Save averrin/5bd5905c15760515025d to your computer and use it in GitHub Desktop.
attendance + trackstudio tracker
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from lxml import html
from datetime import datetime, timedelta
averageTimePath = '//*[@id="wrapper"]/div/div[3]/div[3]/div'
def fetchAttendance():
os.system("/bin/rm /home/user/.temp.html")
os.system("/bin/bash /home/user/get_attendance.sh > /home/user/.temp.html")
def getOffset():
page = html.fromstring(open("/home/user/.temp.html", "r").read())
cells = page.xpath("descendant-or-self::*/*[name() = 'td' and (position() = 2) and (not(not(*) and not(normalize-space())))]/text()")
avg = getAverage()
avg = avg[0] * 60 + avg[1]
norm = (8*60 + 15) * len(cells)
current = avg * (len(cells) - 1)
offset = norm - current
return divmod(offset, 60)
def getAverage():
page = html.fromstring(open("/home/user/.temp.html", "r").read())
a = page.xpath('//*[@id="wrapper"]/div/div[3]/div[3]/div/text()')[1].strip()
h, m = list(map(lambda x: int(x[:-1]), a.split(' ')))
return h, m
def getTime(crazy=False, ret_delta=False):
page = html.fromstring(open("/home/user/.temp.html", "r").read())
enter = page.xpath("descendant-or-self::*/*[name() = 'td' and (position() = 2) and (not(not(*) and not(normalize-space())))]/text()")[-1].strip()
enter = list(map(int, enter.split(":")))
now = datetime.now()
enter = datetime.today() + timedelta(hours=enter[0], minutes=enter[1])
if crazy:
ideal = getOffset()
else:
ideal = (8, 0)
ideal = enter + timedelta(hours=ideal[0], minutes=ideal[1])
delta = ideal - now
h, r = divmod(delta.seconds, 3600)
m, s = divmod(r, 60)
ts = "%s:%s" % (h, (m if m > 9 else '0%s' % m))
if ret_delta:
td = delta - timedelta(hours=now.hour, minutes=now.minute)
return ts, ':'.join(str(td).split(':')[:2])
return ts
if __name__ == '__main__':
fetchAttendance()
cmd = "/usr/bin/kalarm -t %s '%s'" % (getTime(), u'МоТно ΠΈΠ΄Ρ‚ΠΈ Π΄ΠΎΠΌΠΎΠΉ! ВрСмя Ρ‚ΠΎΠ»ΡŒΠΊΠΎ Π½Π΅ Π·Π°Π±ΡƒΠ΄ΡŒ ΠΏΡ€ΠΎΡΡ‚Π°Π²ΠΈΡ‚ΡŒ.')
os.system(cmd.encode("utf8"))
cmd = "/usr/bin/kalarm -t %s '%s'" % (getTime(True), u'Надо ΠΈΠ΄Ρ‚ΠΈ Π΄ΠΎΠΌΠΎΠΉ! ВрСмя Ρ‚ΠΎΠ»ΡŒΠΊΠΎ Π½Π΅ Π·Π°Π±ΡƒΠ΄ΡŒ ΠΏΡ€ΠΎΡΡ‚Π°Π²ΠΈΡ‚ΡŒ.')
os.system(cmd.encode("utf8"))
curl 'http://attendance.developonbox.ru/' -H 'Pragma: no-cache' -H 'Accept-Encoding: gzip, deflate, sdch' -H 'Accept-Language: en-GB,en;q=0.8,en-US;q=0.6,ru;q=0.4' -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.95 Safari/537.36' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' -H 'Referer: http://attendance.developonbox.ru/' -H 'Cookie: remember_token=XXX; _attendance_sphinx_session=XXX' -H 'Connection: keep-alive' -H 'Cache-Control: no-cache' --compressed -L --silent
#!/bin/bash
curl "https://ts.developonbox.ru/!/personalprofile/time/list_persons.rjs?$1" \
-H 'Pragma: no-cache' -H 'Accept-Encoding: gzip, deflate, sdch' -H 'Accept-Language: en-GB,en;q=0.8,en-US;q=0.6,ru;q=0.4' \
-H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36' \
-H 'Accept: application/json, text/javascript, */*; q=0.01' -H 'Referer: https://ts.developonbox.ru/personalprofile/' -H 'X-Requested-With: XMLHttpRequest' \
-H 'Connection: keep-alive' -H 'Cache-Control: no-cache' --compressed --silent \
-H 'Cookie: summaryby=category%3Bstatus%3Bpriority%3Bassignee; msgsortorder=asc; ts-session443=XXX; ts-session80=XXX; appVersion=130704a; showtreelinks=false; nPanel=Tree'
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from lxml import html
from datetime import datetime, timedelta
import json
from termcolor import colored
from attendance import getTime, fetchAttendance
import time
today = datetime.today()
yesterday = today - timedelta(days=1)
tomorrow = today + timedelta(days=1)
def fetchRoute():
if os.path.isfile('/home/user/.route.json'):
delta = datetime.today() - datetime.fromtimestamp(os.path.getmtime('/home/user/.route.json'))
else:
delta = timedelta(hours=1)
if delta > timedelta(minutes=5):
os.system("/bin/rm /home/user/.route.json")
os.system("/bin/bash /home/user/get_route.sh > /home/user/.route.json")
with open('/home/user/.route.json', 'r') as f:
content = f.read()[29:-2]
return content
def weekRange(date):
year, week, dow = date.isocalendar()
if dow == 1:
start_date = date
else:
start_date = date - timedelta(dow)
end_date = start_date + timedelta(6)
return (start_date, end_date)
def getTSTime(type, date_from, date_to):
if os.path.isfile('/home/user/.temp.%s.json' % type):
delta = datetime.today() - datetime.fromtimestamp(os.path.getmtime('/home/user/.temp.%s.json' % type))
else:
delta = timedelta(hours=1)
if delta > timedelta(minutes=5):
os.system('rm /home/user/.temp.%s.json' % type)
args = "view=person&date_sel=%(type)s&date_from=%(date_from)s&date_to=%(date_to)s&person_id=ff8081814b013c91014b07627518628e&complete=true" % {
"type": type,
"date_from": date_from,
"date_to": date_to
}
os.system(
"/bin/bash /home/user/get_time.sh '%s' > /home/user/.temp.%s.json" % (args, type))
answer = json.load(open('/home/user/.temp.%s.json' % type, "r"))
return answer
def getYesterdayTime():
return getTSTime("yesterday", yesterday.strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d"))
def getTodayTime():
return getTSTime("today", today.strftime("%Y-%m-%d"), tomorrow.strftime("%Y-%m-%d"))
def getThisWeekTime():
week = weekRange(today)
return getTSTime("thisweek", week[0].strftime("%Y-%m-%d"), week[1].strftime("%Y-%m-%d"))
def getPrevWeekTime():
week = weekRange(today - timedelta(days=7))
return getTSTime("thisweek", week[0].strftime("%Y-%m-%d"), week[1].strftime("%Y-%m-%d"))
print('')
today = datetime.today()
print(" πŸ“† Today: %s" % today.strftime("%d %b %a"))
delta = datetime.today() - datetime.fromtimestamp(os.path.getmtime('/home/user/.temp.html'))
if delta > timedelta(hours=2):
fetchAttendance()
print('')
t, delta = getTime(ret_delta=True)
if delta.startswith('-'):
delta = 'Go home NOW!'
else:
delta += ' left'
print(" 🏠 Home time: %s (%s)" % (t, delta))
t, delta = getTime(True, ret_delta=True)
if delta.startswith('-'):
delta = 'Go home NOW!'
else:
delta += ' left'
print(" πŸ• Ideal home time: %s (%s)" % (t, delta))
try:
route = fetchRoute()
while not route.strip():
route = fetchRoute()
route = json.loads(route)
duration = route['data']['features'][0]['properties']['RouteMetaData']['Duration']['text']
duration = duration.encode('utf8')
print(' πŸš— Route to home: %s' % duration)
print('')
except:
pass
answer = getPrevWeekTime()
if answer:
reported = answer[0]['reported_time']
if reported < 40:
print(" ❗ Prev week reported: %s / 40 hours" % reported)
else:
print(" ❗ No time reported Prev week!")
answer = getYesterdayTime()
_, _, dow = yesterday.isocalendar()
if answer:
reported = answer[0]['reported_time']
if reported < 8:
print(" ❗ Yesterday reported: %s / 8 hours" % reported)
elif dow < 5:
print(" ❗ No time reported Yesterday!")
answer = getTodayTime()
if answer:
reported = answer[0]['reported_time']
if reported < 8:
print(" Today reported: %s / 8 hours" % reported)
else:
print(' Nice work! Reported: %s hours' % reported)
else:
print(" β€Ό No time reported Today!")
answer = getThisWeekTime()
_, _, dow = today.isocalendar()
if answer:
reported = answer[0]['reported_time']
if reported:
if reported < dow * 8:
print(" This week reported: %s / %s hours" % (reported, dow * 8))
elif dow > 1:
print(" ❗ No time reported This week!")
# print("=" * 32)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment