-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy paththimbl.py
More file actions
executable file
·232 lines (173 loc) · 6.43 KB
/
thimbl.py
File metadata and controls
executable file
·232 lines (173 loc) · 6.43 KB
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
'''thimbl.py - Command-line python tools '''
import cStringIO
import datetime
import json
import pdb
import optparse
import os
import re
import subprocess
import sys
import time
#################################################################
def writeln(text):
print text
#################################################################
class Data:
def __init__(self):
self.load_cache()
#print self.data
#pdb.set_trace()
self.whoami = self.data['me']
self.me = self.data['plans'][self.whoami]
def __cache_filename(self):
'Return the name of the cache file that stores all of the data'
thimbldir = os.path.expanduser('~/.config/thimbl')
try: os.makedirs(thimbldir)
except OSError: pass # don't worry if directory already exists
thimblfile = os.path.join(thimbldir, 'data1.jsn')
return thimblfile
def load_cache(self):
'Load the data file'
thimblfile = self.__cache_filename()
if os.path.isfile(thimblfile):
self.data = load(thimblfile)
else:
self.setup()
def save_cache(self):
cache_file = self.__cache_filename()
save(self.data, cache_file)
def fetch(self, wout = writeln):
'''Retrieve all the plans of the people I am following'''
for following in self.me['following']:
address = following['address']
if address == self.data['me']:
wout("Stop fingering yourself!")
continue
wout('Fingering ' + address)
try:
plan = finger_user(address)
wout("OK")
except AttributeError:
wout('Failed. Skipping')
continue
#print "DEBUG:", plan
self.data['plans'][address] = plan
wout('Finished')
def follow(self, nick, address):
self.me['following'].append( { 'nick' : nick, 'address' : address } )
def post(self, text):
'Create a message. Remember to publish() it'
timefmt = time.strftime('%Y%m%d%H%M%S', time.gmtime())
message = { 'time' : timefmt, 'text' : text }
self.me['messages'].append(message)
def post_file(self, filename):
'Create a post from the text in a file'
text = file(filename, 'r').read()
self.post(text)
def prmess(self, wout = writeln):
'Print messages in reverse chronological order'
# accumulate messages
messages = []
for address in self.data['plans'].keys():
plan = self.data['plans'][address]
if not plan.has_key('messages'): continue
for msg in plan['messages']:
msg['address'] = address
messages.append(msg)
messages.sort(key = lambda x: x['time'])
# print messages
for msg in messages:
# format time
t = str(msg['time'])
tlist = map(int, [t[:4], t[4:6], t[6:8], t[8:10], t[10:12], t[12:14]])
tstruct = apply(datetime.datetime, tlist)
ftime = tstruct.strftime('%Y-%m-%d %H:%M:%S')
text = '{0} {1}\n{2}\n\n'.format(ftime, msg['address'], msg['text'])
wout(text)
def following(self):
'Who am I following?'
followees = self.me['following']
followees.sort(key = lambda x: x['nick'])
for f in followees:
print '{0:5} {1}'.format(f['nick'], f['address'])
def setup(self, values = None):
def create(address, bio, name, website, mobile, email):
'Create data given user information'
properties = {'website' : website, 'mobile' : mobile, 'email' : email }
plan = { 'address' : address, 'name' : name, 'messages' : [],
'replies' : {},'following' : [], 'properties' : properties}
data = { 'me' : address, 'plans' : { address : plan }}
return data
if not values:
values = ["me@example.com", "I am not a number", "6", "www.example.com", "TBD", "me@example.com"]
self.data = apply(create, values)
def unfollow(self, address):
'Remove an address from someone being followed'
def func(f): return not (f['address'] == address)
new_followees = filter(func, self.me['following'])
self.me['following'] = new_followees
def __del__(self):
#print "Data exit"
self.save_cache()
save(self.me, os.path.expanduser('~/.plan'))
#################################################################
def finger_user(user_name):
'''Try to finger a user, and convert the returned plan into a dictionary
E.g. j = finger_user("dk@telekommunisten.org")
print j['bio']
'''
args = ['finger', user_name]
p = subprocess.Popen(args, stdout=subprocess.PIPE)
output = p.communicate()[0]
m = re.search('^.*?Plan:\s*(.*)', output, re.M + re.S)
raw = m.group(1)
j = json.loads(raw)
return j
def save(data, filename):
'Save data to a file as a json file'
j = json.dumps(data)
file(filename, 'w').write(j)
def load(filename):
'Load data from a json file'
s = file(filename, 'r').read()
return json.loads(s)
def main():
#parser.add_option("-f", "--file", dest="filename",
#help="write report to FILE", metavar="FILE")
#parser.add_option("-q", "--quiet",
#action="store_false", dest="verbose", default=True,
#help="don't print status messages to stdout")
#parser.add_option
num_args = len(sys.argv) - 1
if num_args < 1 :
print "No command specified. Try help"
return
d = Data()
cmd = sys.argv[1]
if cmd =='fetch':
d.fetch()
elif cmd == 'follow':
d.follow(sys.argv[2], sys.argv[3])
elif cmd == 'following':
d.following()
elif cmd == 'help':
print "Sorry, not much help at the moment"
elif cmd == 'post':
d.post(sys.argv[2])
elif cmd == 'print':
d.prmess()
elif cmd == 'read':
d.fetch()
d.prmess()
elif cmd == 'setup':
d.setup(sys.argv[2:])
elif cmd == 'stdin':
text = sys.stdin.read()
d.post(text)
elif cmd == 'unfollow':
d.unfollow(sys.argv[2])
else:
print "Unrecognised command: ", cmd
if __name__ == "__main__":
main()