Permalink
Browse files

Desktop: Photo security app. Takes images from web cam on receipt of …

…command from mobile and sends back to it. Request protocol command implemented (request handler and response generator).
  • Loading branch information...
1 parent 7b5338a commit fcf11e4f7db327e4a5df7654f6c0a76e27f7f1c0 @Bhagyashree-Mandora committed Jan 16, 2012
@@ -0,0 +1,14 @@
+class Device():
+
+ #device_name = "no"
+
+ def __init__(self,name):
+ #print name
+ self.device_name = name
+ print self.device_name
+
+ def register():
+ pass
+
+ def set_name(newname):
+ device_name = newname
@@ -0,0 +1,257 @@
+import cmd
+import locale
+import os
+import pprint
+import shlex
+import sys
+import pkg_resources
+from dropbox import session
+
+from dropbox import client, rest
+
+import ast
+import json
+# XXX Fill in your consumer key and secret below
+# You can find these at http://www.dropbox.com/developers/apps
+APP_KEY = 'iypm3vb6d6vxha0'
+APP_SECRET = 'e1kq1rhpwu6dfhx'
+ACCESS_TYPE = 'dropbox' # should be 'dropbox' or 'app_folder' as configured for your app
+
+def command(login_required=True):
+ """a decorator for handling authentication and exceptions"""
+ def decorate(f):
+ def wrapper(self, args):
+ if login_required and not self.sess.is_linked():
+ self.stdout.write("Please 'login' to execute this command\n")
+ return
+
+ try:
+ return f(self, *args)
+ except TypeError, e:
+ self.stdout.write(str(e) + '\n')
+ except rest.ErrorResponse, e:
+ msg = e.user_error_msg or str(e)
+ self.stdout.write('Error: %s\n' % msg)
+
+ wrapper.__doc__ = f.__doc__
+ return wrapper
+ return decorate
+
+class DropboxTerm(cmd.Cmd):
+ def __init__(self, app_key, app_secret):
+ cmd.Cmd.__init__(self)
+ self.sess = StoredSession(app_key, app_secret, access_type=ACCESS_TYPE)
+ self.api_client = client.DropboxClient(self.sess)
+ self.current_path = ''
+ self.prompt = "Dropbox> "
+
+ self.sess.load_creds()
+
+ @command()
+ def do_ls(self):
+ """list files in current remote directory"""
+ resp = self.api_client.metadata(self.current_path)
+
+ if 'contents' in resp:
+ for f in resp['contents']:
+ name = os.path.basename(f['path'])
+ encoding = locale.getdefaultlocale()[1]
+ self.stdout.write(('%s\n' % name).encode(encoding))
+
+ @command()
+ def do_cd(self, path):
+ """change current working directory"""
+ if path == "..":
+ self.current_path = "/".join(self.current_path.split("/")[0:-1])
+ else:
+ self.current_path += "/" + path
+
+ @command(login_required=False)
+ def do_login(self):
+ """log in to a Dropbox account"""
+ try:
+ self.sess.link()
+ except rest.ErrorResponse, e:
+ self.stdout.write('Error: %s\n' % str(e))
+
+ @command()
+ def do_logout(self):
+ """log out of the current Dropbox account"""
+ self.sess.unlink()
+ self.current_path = ''
+
+ @command()
+ def do_cat(self, path):
+ """display the contents of a file"""
+ f = self.api_client.get_file(self.current_path + "/" + path)
+ self.stdout.write(f.read())
+ self.stdout.write("\n")
+
+ @command()
+ def do_write(self, message):
+ """Write message to ourfile.txt"""
+ f =self.api_client.put_file("mobileread",message,True)
+ self.stdout.write("\nmessage sent\n")
+
+ @command()
+ def do_listen(self):
+ """LISTEN TO FILE ourfile.txt"""
+ import re
+ while 1:
+ self.stdout.write("\nListening....")
+ f = self.api_client.get_file("mobileread")
+ message=f.read()
+ if message<>" " and message<> "":
+ self.stdout.write("Change Found\nMessage is:")
+ self.stdout.write(message)
+ #run_command(message)
+ if(re.match("open",message)):
+ self.stdout.write("\nopen command found so opening browser.")
+ os.system("google-chrome "+ message[(message.find("open ")+5):])
+ self.stdout.write("\ndeleting contents of ourfile.txt....")
+ self.api_client.put_file("mobileread"," ",True)
+ else:
+ self.stdout.write("No change found.")
+ f.close()
+
+ @command()
+ def do_mkdir(self, path):
+ """create a new directory"""
+ self.api_client.file_create_folder(self.current_path + "/" + path)
+
+ @command()
+ def do_rm(self, path):
+ """delete a file or directory"""
+ self.api_client.file_delete(self.current_path + "/" + path)
+
+ @command()
+ def do_mv(self, from_path, to_path):
+ """move/rename a file or directory"""
+ self.api_client.file_move(self.current_path + "/" + from_path,
+ self.current_path + "/" + to_path)
+
+ @command()
+ def do_account_info(self):
+ """display account information"""
+ f = self.api_client.account_info()
+ pprint.PrettyPrinter(indent=2).pprint(f)
+
+ @command()
+ def do_exit(self):
+ """exit"""
+ return True
+
+ @command()
+ def do_put(self, from_path, to_path):
+ """
+ Copy local file to Dropbox
+
+ Examples:
+ Dropbox> put ~/test.txt dropbox-copy-test.txt
+ """
+ from_file = open(os.path.expanduser(from_path))
+
+ self.api_client.put_file(self.current_path + "/" + to_path, from_file)
+
+ @command()
+ def do_help(self):
+ # Find every "do_" attribute with a non-empty docstring and print
+ # out the docstring.
+ all_names = dir(self)
+ cmd_names = []
+ for name in all_names:
+ if name[:3] == 'do_':
+ cmd_names.append(name[3:])
+ cmd_names.sort()
+ for cmd_name in cmd_names:
+ f = getattr(self, 'do_' + cmd_name)
+ if f.__doc__:
+ self.stdout.write('%s: %s\n' % (cmd_name, f.__doc__))
+#if it is a command perform the task
+ def run_command(self,command):
+
+ pass
+
+ # the following are for command line magic and aren't Dropbox-related
+ def emptyline(self):
+ pass
+
+ def do_EOF(self, line):
+ self.stdout.write('\n')
+ return True
+
+ def parseline(self, line):
+ parts = shlex.split(line)
+ if len(parts) == 0:
+ return None, None, line
+ else:
+ return parts[0], parts[1:], line
+
+
+class StoredSession(session.DropboxSession):
+ """a wrapper around DropboxSession that stores a token to a file on disk"""
+ TOKEN_FILE = "token_store.txt"
+
+ def load_creds(self):
+ try:
+ stored_creds = open(self.TOKEN_FILE).read()
+ self.set_token(*stored_creds.split('|'))
+ print "[loaded access token]"
+ except IOError:
+ pass # don't worry if it's not there
+
+ def write_creds(self, token):
+ f = open(self.TOKEN_FILE, 'w')
+ f.write("|".join([token.key, token.secret]))
+ f.close()
+
+ def delete_creds(self):
+ os.unlink(self.TOKEN_FILE)
+
+ def link(self):
+ request_token = self.obtain_request_token()
+ url = self.build_authorize_url(request_token)
+ print "url:", url
+ print "Please authorize in the browser. After you're done, press enter."
+ raw_input()
+
+ self.obtain_access_token(request_token)
+ self.write_creds(self.token)
+
+ def unlink(self):
+ self.delete_creds()
+ session.DropboxSession.unlink(self)
+
+def main():
+ if APP_KEY == '' or APP_SECRET == '':
+ exit("You need to set your APP_KEY and APP_SECRET!")
+ term = DropboxTerm(APP_KEY, APP_SECRET)
+ #term.cmdloop()
+
+ #stdout.write("\nListening....")
+ f = term.api_client.get_file("mobileread")
+ message = f.read()
+
+ if message<>" " and message<> "":
+ list1 = json.loads(message)
+ #i = list1.index(list1[-1])
+
+ fob=open('mwrite' , 'r')
+ xyz = fob.read()
+ fob.close()
+
+ uvw = ast.literal_eval(xyz)
+ list1.append(uvw[0])
+ json_obj1 = json.dumps(list1)
+
+ fob = open('mwrite','w')
+ fob.write(json_obj1)
+ fob.close()
+
+ fob=open('mwrite' , 'r')
+ term.do_write(fob)
+ fob.close()
+
+
+if __name__ == '__main__':
+ main()
@@ -0,0 +1,21 @@
+import pickle
+
+class Handler:
+
+ def __init__(self,json_data):
+
+ # unpickle the object corresponding to the command in json object.
+ # The file name of the pickle is the same as command.
+ # The pickled object holds the program to be executed on receipt of the json object.
+ print json_data['command']
+ cmd = json_data['command'] + '.pkl'
+ print cmd
+ pkl_file = open(cmd, 'rb')
+ obj = pickle.load(pkl_file)
+ pkl_file.close()
+
+ # Reinitialise (reassign) the object with the new values in the json.
+ obj.__init__(json_data)
+ obj.OnReceive()
+ #obj.OnReceive(obj.data_str)
+ #obj.write(obj.data_str)
@@ -0,0 +1,33 @@
+import json
+import dropbox_api
+
+class Crafting:
+
+ """def SEND(self, data_str):
+ json_obj = json.dumps([{"sender": "Desktop" , "reciever": "mobile", "command" : "sendSMS","data": data_str}])
+
+ fob=open('mwrite' ,'w')
+ fob.write(json_obj)
+ fob.close()
+
+ dropbox_api.main()
+
+ """
+ def createjsobj(self, data_str):
+ json_obj = json.dumps(data_str)
+
+ fob=open('mwrite' ,'w')
+ fob.write(json_obj)
+ fob.close()
+
+ dropbox_api.main()
+
+
+ def input_json_data(self,json_data):
+ self.data_str = json_data
+ print self.data_str
+ self.createjsobj(self.data_str)
+
+
+# decoded = json.loads(data_string)
+ #print 'DECODED:', decoded
@@ -0,0 +1,47 @@
+import json
+import pynotify
+import handler
+
+
+class Parsing:
+
+ """message_data = [{"sender": "my laptop","receiver": "my mobile", "command": "takephoto","req_id":"123","data":{"content": "Hi...string!!", "date": "27", "sender": "ME", "time": "4:30"}}]"""
+
+ def parse_js_obj(self,message_data):
+ print message_data
+ self.decoded = json.loads(message_data)
+ print 'DECODED:', self.decoded
+ print self.decoded[0]['data']
+
+ # write in a file to cache data
+ fob = open('dwrite' ,'w')
+ for item in self.decoded:
+ fob.write("%s\n" % item)
+ fob.close()
+
+ # desktop notification
+ pynotify.init("Hello world")
+ Hello=pynotify.Notification("Message Received!","You have an unread message..","dialog-information")
+ Hello.show()
+ pynotify.uninit()
+
+ # A call to an handler class to pass the received message to the appropriate class object to run
+ handle = handler.Handler(self.decoded[0])
+
+
+
+
+def main():
+
+ message_data = '[{"sender": "my laptop","receiver": "my mobile", "command": "takephoto","data":{"requestId":"123","content": "Hi...string!!", "date": "27", "sender": "ME", "time": "4:30"}}]'
+ print 'done 2...'
+ parse = Parsing()
+ parse.parse_js_obj(message_data)
+ #gtk.main()
+
+
+if __name__ == "__main__":
+ print 'done 3...'
+ #msread = msgread()
+ main()
+
Oops, something went wrong.

0 comments on commit fcf11e4

Please sign in to comment.