added coba
[p2prfd.git] / observer.py
blobcdf274690d9b977bf01074222a948941190c51b0
1 import cgi
2 import hashlib
3 import http_helper
4 import httplib
5 import random
6 import socket
7 import sys
8 import threading
9 import urllib
10 import urlparse
12 import twisted.internet.reactor
13 import twisted.web.resource
14 import twisted.web.server
16 import entangled_network
18 class ObserverResource(twisted.web.resource.Resource):
19 isLeaf = True
20 trees = {}
21 last_name = 0
22 names = {}
23 def node_pic(self, node, tree):
24 if node:
25 name = self.names[node]
26 retu = name
27 left_node = None
28 right_node = None
29 if node in tree['child_left']: left_node = tree['child_left'][node]
30 if node in tree['child_right']: right_node = tree['child_right'][node]
31 left_pic = self.node_pic(left_node, tree)
32 right_pic = self.node_pic(right_node, tree)
33 lefts = left_pic.split('\n')
34 retu += '-' + lefts[0] + '\n'
35 for line in lefts[1:]:
36 retu += ' |' + line + '\n'
37 pass
38 rights = right_pic.split('\n')
39 retu += ' -' + rights[0] + '\n'
40 for line in rights[1:]:
41 retu += ' ' + line + '\n'
42 pass
43 return retu
44 else:
45 return '00'
46 def tree_pic(self, tree):
47 root = tree['root']
48 return self.node_pic(root, tree)
49 pass
50 def add_name(self, node):
51 if node and not (node in self.names):
52 self.last_name += 1
53 self.names[node] = '%02d' % self.last_name
54 pass
55 def render_GET(self, request):
56 queries = request.args
57 print 'queries = %s' % repr(queries)
58 action = None
59 if 'action' in queries: action = queries['action'][0]
60 if action == 'new_root':
61 feed_url = queries['rss'][0]
62 root = eval(queries['root'][0])
63 self.add_name(root)
64 if feed_url in self.trees:
65 pass
66 else:
67 self.trees[feed_url] = {'root': None, 'child_left': {}, 'child_right': {}}
68 self.trees[feed_url]['root'] = root
69 pass
70 elif action == 'adopt_child':
71 parent = eval(queries['parent'][0]);
72 child = eval(queries['child'][0]);
73 feed_url = queries['rss'][0]
74 loc = queries['loc'][0]
75 self.add_name(parent)
76 self.add_name(child)
77 if loc == 'left':
78 self.trees[feed_url]['child_left'][parent] = child
79 pass
80 elif loc == 'right':
81 self.trees[feed_url]['child_right'][parent] = child
82 pass
83 pass
84 else:
85 rss = None
86 if 'rss' in queries: rss = queries['rss'][0]
87 if rss:
88 if rss in self.trees: return self.tree_pic(self.trees[rss])
89 else: return 'tree for %s not found' % rss
90 pass
91 result = {}
92 return repr(result)
93 pass
94 rsrc = ObserverResource()
95 site = twisted.web.server.Site(rsrc)
96 twisted.internet.reactor.listenTCP(9501, site)
97 twisted.internet.reactor.run()