summaryrefslogtreecommitdiff
path: root/scripts/status_script.py
blob: 1686069833b36d5a444d015cce02fde12af6a866 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#!/usr/bin/env python

from urllib.request import urlopen
import json
import time
import os.path
from os import rename
from credentials import *
from twitter import *
from datetime import datetime

SEPARATOR = ' - '
DATE_MSG = 'Last change was on'

STATES = ["closed", "open", "unknown"]
STATE_IMAGE = "status-{0}.png"
MESSAGES = ['OH NOEZ! sublab is now closed.' + SEPARATOR + DATE_MSG + ' ',
            'YAY! sublab is now open' + SEPARATOR + DATE_MSG + ' ',
            "DAMN SON! Current status of @sublab couldn't be retrieved" + ' ']
STATE_MESSAGE = dict(zip(STATES, MESSAGES))

STATEFILE = os.path.join('/', 'tmp', 'sublab-doorstatus.last')

CSS = '''
         #statusimage {
         background: url(../img/{0}) ;
         height: 40px;
         width: 40px;
         margin: 5px;
         }'''


class SublabStatus(object):

    def __init__(self):
        self.json = None
        self.door = None
        self.state = STATES[2]
        self.old_state = None
        self.last_change = None

        # read file with last state
        try:
            with open(STATEFILE, 'r') as state_file:
                self.old_state = state_file.readline().rstrip()
                self.last_change = state_file.readline().rstrip()
        except Exception:
            self.save_statefile()
            exit()

    def update(self):
        # read current state
        try:
            self.fetch_state()
        except:
            return
        self.update_state()
        self.save_statefile()
        self.update_css()
        self.tweet_state()


    def update_state(self):
        if self.door.get('ts') + 120 < time.time():
            return

        if not self.door.get('value'): # lock == True => door is open, lock == False ==> door is closed
            self.status = STATES[1] # open
        else:
            self.status = STATES[0] # closed


    def fetch_state(self):
        if not self.json :
            try:
                with urlopen('http://[2a02:238:f02a:9800:caa0:30ff:feb4:2185]/') as response:
                     self.json = json.loads(response.readall().decode('utf-8'))
            except IOError:
                with urlopen('http://beaglebone.local.sublab.org/') as response:
                    self.json = json.loads(response.readall().decode('utf-8'))
            self.door = self.json.get('door.lock')


    def save_statefile(self):
        now = datetime.now().strftime("%c")
        with open(STATEFILE, 'w') as state_file:
            state_file.write(self.state + '\n' + now + '\n')


    def update_css(self):
        path = os.path.realpath(os.path.dirname(__file__))
        css_path = os.path.join(path, '..', 'public', 'css', 'sublab.status.css')
        css_path_new = css_path + '.new'

        with open(path_new, 'w') as css_file:
            css_file.write(CSS.format(STATE_IMAGE(self.state)))
        os.rename(css_path_new, path)


    def tweet_state(self):
        tweet = STATE_MESSAGE[self.state] + self.last_change
        if len(tweet) <= 140:
            t = Twitter(auth=OAuth(token,
                        token_key,
                        con_secret,
                        con_secret_key))
            t.statuses.update(status=tweet)
        else:
            raise ValueError("Tweet too long: {0}".format(tweet))


if __name__ == '__main__':

    s = SublabStatus()
    s.update()