Ejemplo n.º 1
0
Archivo: main.py Proyecto: Banta/voicex
class Mungano:
	def __init__(self):
		self.mc = ModelController()
		self.v = VoiceXTransport(auth= config.MUNGANO_AUTH)


	def init_callback(self):
		self.v.set_callback(callback = self.msg_new)


	def show_help(self, msg, phone_num):
		help_text = "Mungano Help! To subscribe : #sub phone_numbers (comma separated), To send an immediate alert: #alert msg, To set an alarm: #alarm delay_time msg, To view your subscription list: #view"
		if(not msg):
			pass
		elif('sub' in msg):
			help_text = "Help for #sub : #sub phone_numbers (comma separated)"
		elif('alert' in msg):
			help_text = "Help for #alert : #alert msg"
		elif('alarm' in msg):
			help_text = "Help for #alarm : #alarm delay_time msg"
		elif('view' in msg):
			help_text = "Help for #view : #view"
		else:
			pass			
		self.v.sms(phone_num, help_text)



	def handle_alert(self, msg_data, phone_num):	
		sub = self.mc.find_subscription(phone_num)
		if(sub):
			self.alert(sub, "alert from %s: %s" %(phone_num, msg_data))
		else:		
			res = 'No subscription found for phone number: %s' %(phone_num)
	
	
	def handle_alarm(self, msg_data, phone_num):
		try:
			tokens = msg_data.strip().split(" ", 1)
			delay = float(tokens[0])
			msg = tokens[1]
			sub = self.mc.find_subscription(phone_num)
			mungano.tasks.delayed_sms.delay(self.v, sub.sub_list, "alarm (%s minutes): %s. copy sent to: %s" %(str(delay), str(msg), sub.sub_list), delay)
		except Exception, e:
			print "handle_alarm: ", e
			self.show_help(msg_data, phone_num)
			return
Ejemplo n.º 2
0
Archivo: main.py Proyecto: Banta/voicex
	def __init__(self):
		self.mc = ModelController()
		self.v = VoiceXTransport(auth= config.MUNGANO_AUTH)
Ejemplo n.º 3
0
class VoiceX:
	def __init__(self, auth):
		logger.debug('__init__')
		self.mc = ModelController()
		self.v = VoiceXTransport(auth = auth)

	
	# only for testing (polling mode)
	def init_callback(self):
		logger.debug('init_callback')
		self.v.set_callback(callback = self.msg_new)


	def show_help(self, msg, phone_num):
		logger.debug('show_help')
		help_text = "Welcome to VoiceX! Commands: register name, unregister name, post msg, view post-id, delete post-id, search query, reply post-id msg, follow @name/#tag, unfollow @name/#tag"
		if(not msg):
			pass
		elif('unregister' in msg):
			help_text = "Help for unregister : unregister name. Example: unregister voicex"
		elif('register' in msg):
			help_text = "Help for register : register name. Example: register voicex"
		elif('post' in msg):
			help_text = "Help for post : post message. Example (simple post): post hello world. Example (tagged post): post voicex is free #voicex. Example (anonymous post): post voicex is free #anon"
		elif('search' in msg):
			help_text = "Help for search : search search-keywords. Example: search kenya election"
		elif('view' in msg):
			help_text = "Help for view : view post-id. Example: view 1"
		elif('delete' in msg):
			help_text = "Help for delete : delete post-id. Example: delete 1"
		elif('reply' in msg):
			help_text = "Help for reply : reply post-id reply-msg. Example (private reply): reply 1 welcome to voicex. Example (public reply): reply 1 welcome to voicex #public. Example (anonymous reply): reply 1 welcome to voicex #anon"
		elif('follow' in msg):
			help_text = "Help for follow : follow @name/#tag. Example: follow @voicex or follow #election"
		elif('unfollow' in msg):
			help_text = "Help for unfollow : unfollow @name/#tag. Example: unfollow @voicex or unfollow #election."
		else:
			pass			
		self.v.sms(phone_num, help_text)

	
	
	def register(self, name, phone_num):
		logger.debug('register')
		res = self.mc.add_account(name , phone_num)
		if(res['status']):
			self.v.sms(phone_num, 'Successfully registered %s with %s.' %(name, phone_num))
		else:
			self.v.sms(phone_num, res['code'])
	
	
	def unregister(self, name, phone_num):
		logger.debug('unregister')
		res = self.mc.delete_account(name , phone_num)	
		if(res['status']):
			self.v.sms(phone_num, 'Unregistered %s' %(name))
		else:
			self.v.sms(phone_num, res['code'])
	

	
	def post(self, text, phone_num):
		logger.debug('post')				
		res = self.mc.insert_post(phone_num, text);
		if(res['status']):
			post_id = res['val']	
			self.v.sms(phone_num, 'Msg successfully posted. To view the post, text -- view %s' %(str(post_id)))
			self.notify_followers(phone_num, text, post_id)
		else:
			self.v.sms(phone_num, res['code'])


	def notify_followers(self, phone_num, msg, post_id):
		logger.debug('notify_followers')
		tags = [tag.strip().lower() for tag in msg.split() if tag.startswith("#")]
		res_find = self.mc.find_account(phone_num)
		account = 'anonymous'
		if(res_find['status'] and ('#anon' not in tags)):
			account = res_find['val'].name
			tags.append('@'+account)
		
		res_following = self.mc.find_following(tags)
		text = "From: @%s (Post ID: %s): %s" %(account, post_id, msg)
		if(res_following['status']):
			follow_list = res_following['val']
			if(len(follow_list) == 0 ):
				return
			recipients = ','.join(follow_list)
			self.v.sms(recipients, text)
		else:
			self.v.sms(phone_num, res['code'])



	def delete(self, post_id, phone_num):
		logger.debug('delete')
		res = self.mc.delete_post(post_id)
		if(res['status']):
			self.v.sms(phone_num, "Post ID:(%s) has been successfully deleted!" %(post_id))
		else:
			self.v.sms(phone_num, res['code'])



	def view(self, post_id, phone_num):
		logger.debug('view')
		res = self.mc.find_post(post_id)
		if(res['status']):
			post = res['val']
			out = post.post
			posts = Post.objects.filter(reply_to = post, public = True)
			for p in posts:
				out =  out + "[Comment (ID:%s): %s]" %(str(p.id), p.post)
			self.v.sms(phone_num, out)
		else:		
			self.v.sms(phone_num, res['code'])
		



	def search(self, query, phone_num):
		logger.debug('search')
		res = self.mc.search_posts(query)
		if(res['status']):
			self.v.sms(phone_num, res['val'])
		else:
			self.v.sms(phone_num, res['code'])
		




	def reply(self, msg_data, phone_num):
		logger.debug('reply')
		tokens = msg_data.strip().split(" ", 1)
		tokens = filter(lambda x: x!='', map(lambda x: x.strip(), tokens))
		post_id = None
		reply_text = None
		try:
			post_id = str(int(tokens[0]))
			reply_text = tokens[1]
		except:
			self.show_help('reply', phone_num)
			return
		account = 'anonymous'
		tags = [tag.strip().lower() for tag in reply_text.split() if tag.startswith("#")]
		res_find_acc = self.mc.find_account(phone_num)
		if(res_find_acc['status'] and ('#anon' not in tags)):
			account = res_find_acc['val'].name
		reply_text = tokens[1]
		res_find = self.mc.find_post(post_id)
		if(res_find['status']):
			post = res_find['val']
			res_insert = {'status': False}
			if('#public' in tags):
				res_insert = self.mc.insert_reply(phone_num, reply_text, post, public=True)
			else:
				res_insert = self.mc.insert_reply(phone_num, reply_text, post)
			if(res_insert['status']):
				reply_id = str(res_insert['val'])
				self.v.sms(phone_num, "Your reply to post (ID:%s) has been successfully submitted!" %(post_id))
				reply_to  = post.phone
				self.v.sms(reply_to, "[Reply(ID:%s, From: @%s) to Post(ID:%s)] - %s" %(str(reply_id), account, str(post_id), reply_text))
			else:
				self.v.sms(phone_num, res_insert['code'])
		else:
			self.v.sms(phone_num, res_find['code'])
	


	def follow(self, tag, phone_num):
		logger.debug('follow')
		if(tag[0] not in ['#', '@']):
			self.v.sms(phone_num, "Invalid tag: '%s'. Valid tags are either hash-tags (start with '#'), or an account name (start with'@')." %(tag))
			return
		res = self.mc.add_following(tag.strip().lower(), phone_num)
		if(res['status']):
			self.v.sms(phone_num, 'You are now following %s.' %(tag))
		else:
			self.v.sms(phone_num, res['code'])
	
	
	def unfollow(self, name, phone_num):
		logger.debug('unfollow')
		res = self.mc.delete_following(name.strip().lower(), phone_num)
		if(res['status']):
			self.v.sms(phone_num, 'You are now not following %s.' %(name))
		else:
			self.v.sms(phone_num, res['code'])


	def parse(self, msg, phone_num):
		logger.debug('parse')
		try:
			msg_data = (msg.strip()).split(" ", 1)
			msg_data = map(lambda x: x.strip(), msg_data)
			cmd = msg_data[0].lower()
			text = None
			try:
				text = msg_data[1]
			except:
				pass
			
			if(not text):
				self.show_help(msg_data[0], phone_num)
				return
			
			if (cmd == "register"):
				self.register(text, phone_num)
			elif(cmd == "unregister"):
				self.unregister(text, phone_num)
			elif(cmd == "post"):
				self.post(text, phone_num)
			elif(cmd == "view"):
				self.view(text, phone_num)
			elif(cmd ==  "search"):
				self.search(text, phone_num)
			elif(cmd == "delete"):
				self.delete(text, phone_num)
			elif(cmd == "reply"):
				self.reply(text, phone_num)
			elif(cmd == "follow"):
				self.follow(text, phone_num)
			elif(cmd == "unfollow"):
				self.unfollow(text, phone_num)
			elif(cmd == "help"):
				try:
					self.show_help(msg_data[1], phone_num)
				except:
					self.show_help(None, phone_num)
			else:
				self.v.sms(phone_num, "Unknown command: '%s'. Text 'help' to get the list of commands." %(cmd))
		except Exception, e:
			logger.exception('parse')
Ejemplo n.º 4
0
	def __init__(self, auth):
		logger.debug('__init__')
		self.mc = ModelController()
		self.v = VoiceXTransport(auth = auth)
Ejemplo n.º 5
0
class Mungano:
	def __init__(self):
		self.mc = ModelController()
		self.v = VoiceXTransport(transport=config.GV, auth= config.GV_MUNGANO_AUTH)


	def init_callback(self):
		self.v.set_callback(callback = self.msg_new)


	def show_help(self, msg, phone_num):
		help_text = "Welcome to Mungano! To subscribe : #sub phone_numbers_separated_by_a_comma, To send an immediate alert: #alert, To send delayed alert: #alarm delay_time_in_minutes msg, To view your subscription list: #view, To override your old subscription with a new list: #sub new_list_of_phone_numbers_separated_by_a_comma"
		if(not msg):
			pass
		elif('sub' in msg):
			help_text = "Help for #sub : #sub phone_numbers_separated_by_a_comma"
		elif('alert' in msg):
			help_text = "Help for #alert : #alert message"
		elif('alarm' in msg):
                        help_text = "Help for #alarm : #alarm delay-in-minutes message"
		elif('view' in msg):
			help_text = "Help for #view : #view"
		else:
			pass			
		self.v.sms(phone_num, help_text)



	def handle_alert(self, msg_data, phone_num):	
		sub = self.mc.find_subscription(phone_num)
		if(sub):
			self.alert(sub, "alert from %s: %s" %(phone_num, msg_data))
		else:		
			res = 'No subscription found for phone number: %s' %(phone_num)
		
        def handle_alarm(self, msg_data, phone_num):
		try:
			tokens = msg_data.strip().split(" ", 1)
                        delay = float(tokens[0])
                        msg = tokens[1]
			sub = self.mc.find_subscription(phone_num)
                        mungano.tasks.delayed_sms.delay(self.v, sub.sub_list, "alarm (%s minutes): %s. copy sent to: %s" %(str(delay), str(msg), sub.sub_list), delay)
                except:
                        self.getHelp(msg_data, phone_num)
                        return

	def alert(self, sub, msg):
		self.v.sms(sub.sub_list, msg)


	def view(self, phone_num):	
		sub = self.mc.find_subscription(phone_num)
		if(sub):
			res = 'subscribed numbers: ' + str(sub.sub_list)
		else:		
			res = 'No subscription found for phone number: %s' %(phone_num)
		self.v.sms(phone_num, res)


	def subscribe(self, sub_list, phone_num):
		if(self.mc.update_subscription(sub_list, phone_num)):
			self.v.sms(phone_num, 'alert subscription updated successfully for %s.' %(phone_num))
		else:
			self.v.sms(phone_num, 'error occured while updating the alert subscription for %s.' %(phone_num))


	def parse(self, msg, phone_num):
		try:
			msg_data = (msg.strip()).split(" ", 1)
			msg_data = map(lambda x: x.strip(), msg_data)
			if (msg_data[0] == "#sub"):
				self.subscribe(msg_data[1], phone_num)
			elif(msg_data[0] == "#view"):
				self.view(phone_num)
			elif(msg_data[0] == "#alert"):
				self.handle_alert(msg_data[1], phone_num)
			elif (msg_data[0] == "#alarm"):
				self.handle_alarm(msg_data[1], phone_num)
			elif(msg_data[0] == "#help"):
				self.show_help(msg, phone_num)
			else:
				self.show_help(msg, phone_num)
		except Exception, e:
			print "parse: ", e
			self.show_help(msg, phone_num)
Ejemplo n.º 6
0
	def __init__(self):
		self.mc = ModelController()
		self.v = VoiceXTransport(transport=config.GV, auth= config.GV_VOICEX_AUTH)
Ejemplo n.º 7
0
class VoiceX:
	def __init__(self):
		self.mc = ModelController()
		self.v = VoiceXTransport(transport=config.GV, auth= config.GV_VOICEX_AUTH)


	def init_callback(self):
		self.v.set_callback(callback = self.msg_new)


	def show_help(self, msg, phone_num):
		help_text = "Welcome to VoiceX! To commands: #register name, #unregister name, #post msg, #view post-id, #delete post-id, #search query, #reply post-id msg, #comment post-id comment, #follow name, #unfollow name"
		if(not msg):
			pass
		elif('register' in msg):
			help_text = "Help for #register : #register name"
		elif('unregister' in msg):
			help_text = "Help for #unregister : #unregister name"
		elif('post' in msg):
			help_text = "Help for #post : #post msg"
		elif('search' in msg):
			help_text = "Help for #search : #search keywords"
		elif('view' in msg):
			help_text = "Help for #view : #view post-id"
		elif('delete' in msg):
			help_text = "Help for #delete : #delete post-id"
		elif('reply' in msg):
			help_text = "Help for #reply : #reply post-id reply-msg"
		elif('comment' in msg):
			help_text = "Help for #comment : #comment post-id comment"
		elif('follow' in msg):
			help_text = "Help for #follow : #follow name"
		elif('unfollow' in msg):
			help_text = "Help for #unfollow : #unfollow name"
		else:
			pass			
		self.v.sms(phone_num, help_text)

	
	
	def register(self, name, phone_num):	
		if(self.mc.add_account(name , phone_num)):
			self.v.sms(phone_num, 'Account created successfully.')
		else:
			self.v.sms(phone_num, 'Error occurred while creating the account.')
	
	
	def unregister(self, name, phone_num):	
		if(self.mc.delete_account(name , phone_num)):
			self.v.sms(phone_num, 'Account deleted successfully.')
		else:
			self.v.sms(phone_num, 'Error occurred while deleting the account.')
	

	
	def post(self, text, phone_num):				
		post_id = self.mc.insert_post(phone_num, text);
		if(post_id >= 0):		
			self.v.sms(phone_num, 'Msg successfully posted. To view the post, text #view ' + str(post_id))
			self.notify_followers(phone_num, text, post_id)
		else:
			self.v.sms(phone_num, "Error occurred while posting the Msg.")


	def notify_followers(self, phone_num, msg, post_id):
		account = self.mc.find_account(phone_num)
		if(not account):
			return
		follow_list = self.mc.find_following(account)
		text = "From: %s (Post ID: %s): %s" %(account.name, post_id, msg)
		if(len(follow_list)>0):
			recipients = ','.join(follow_list)
			self.v.sms(recipients, text)



	def delete(self, post_id, phone_num):
		if(self.mc.delete_post(post_id)):
			self.v.sms(phone_num, "Post ID:(" + post_id + ") has been successfully deleted!")
		else:
			self.v.sms(phone_num, "Couldn't delete post (ID:" + post_id+")")



	def view(self, post_id, phone_num):	
		post = self.mc.find_post(post_id)
		if(post):
			res = post.post
			posts = Post.objects.filter(reply_to = post, public = True)
			for p in posts:
				res =  res + "[Comment (ID:" + str(p.id) + "): " + p.post + "] "
		else:		
			res = 'No post found with id: ' + post_id
		self.v.sms(phone_num, res)



	def search(self, query, phone_num):
		res = self.mc.search_posts(query)
		if(not res):
			res = 'No matching results found.' 
		self.v.sms(phone_num, res)




	def reply(self, msg_data, phone_num):
		tokens = msg_data.strip().split(" ", 1)
		tokens = filter(lambda x: x!='', map(lambda x: x.strip(), tokens))
		post_id = None
		reply_text = None
		try:
			post_id = str(int(tokens[0]))
			reply_text = tokens[1]
		except:
			self.getHelp(msg_data, phone_num)
			return
			
		try:
			reply_text = tokens[1]
			post = self.mc.find_post(post_id)
			if(post):
				reply_id = str(self.mc.insert_reply(phone_num, reply_text, post))
				if(reply_id > 0):
					self.v.sms(phone_num, 'Your reply to post (ID:' + post_id + ") has been successfully submitted!")
					reply_to  = post.phone
					self.v.sms(reply_to, "New Reply (ID:" +reply_id+") : " + reply_text +".")
			else:
				self.v.sms(phone_num, 'No post found with ID: ' + post_id)
		except:
			self.v.sms(phone_num, 'Error occurred while replying to post (ID:' + post_id+")")



	def comment(self, msg_data, phone_num):
		tokens = msg_data.strip().split(" ", 1)
                tokens = filter(lambda x: x!='', map(lambda x: x.strip(), tokens))
		post_id = None
		comment_text = None
		try:
			post_id = str(int(tokens[0]))
			comment_text = tokens[1]
		except:
			self.getHelp(msg_data, phone_num)
			return
					
		try:			
			post = self.mc.find_post(post_id)
			if(post):
				comment_id = self.mc.insert_reply(phone_num, comment_text, post, public = True)
				if(comment_id > 0):
					self.v.sms(phone_num, 'Your comment to post (ID:' + post_id + ") has been successfully submitted!")
					reply_to  = post.phone
					self.v.sms(reply_to, "New comment to post (ID:" +post_id+"): " + comment_text +".")
			else:
				self.v.sms(phone_num, 'No post found with ID: ' + post_id)
		except:
			self.v.sms(phone_num, 'Error occurred while adding comment to post (ID:' + post_id+")")


	def follow(self, name, phone_num):
		if(self.mc.add_following(name, phone_num)):
			self.v.sms(phone_num, 'You are now following %s.' %(name))
		else:
			self.v.sms(phone_num, 'Error occurred while adding the follow list for %s.' %(name))
	
	
	def unfollow(self, name, phone_num):
		if(self.mc.delete_following(name, phone_num)):
			self.v.sms(phone_num, 'You are now not following %s.' %(name))
		else:
			self.v.sms(phone_num, 'Error occurred while removing the follow list for %s.' %(name))


	def parse(self, msg, phone_num):
		try:
			msg_data = (msg.strip()).split(" ", 1)
			msg_data = map(lambda x: x.strip(), msg_data)
			if (msg_data[0] == "#register"):
				self.register(msg_data[1], phone_num)
			elif(msg_data[0] == "#unregister"):
				self.unregister(msg_data[1], phone_num)
			elif(msg_data[0] == "#post"):
				self.post(msg_data[1], phone_num)
			elif(msg_data[0] == "#view"):
				self.view(msg_data[1], phone_num)
			elif(msg_data[0] ==  "#search"):
				self.search(msg_data[1], phone_num)
			elif(msg_data[0] == "#delete"):
				self.delete(msg_data[1], phone_num)
			elif(msg_data[0] == "#reply"):
				self.reply(msg_data[1], phone_num)
			elif(msg_data[0] == "#comment"):
				self.comment(msg_data[1], phone_num)
			elif(msg_data[0] == "#follow"):
				self.follow(msg_data[1], phone_num)
			elif(msg_data[0] == "#unfollow"):
				self.unfollow(msg_data[1], phone_num)
			elif(msg_data[0] == "#help"):
				self.show_help(msg_data[1], phone_num)
			else:
				self.show_help(msg, phone_num)
		except Exception, e:
			print "parse: ", e
			self.show_help(msg, phone_num)
Ejemplo n.º 8
0
 def __init__(self, auth):
     logger.debug('__init__')
     self.mc = ModelController()
     self.v = VoiceXTransport(auth=auth)
Ejemplo n.º 9
0
class VoiceX:
    def __init__(self, auth):
        logger.debug('__init__')
        self.mc = ModelController()
        self.v = VoiceXTransport(auth=auth)

    # only for testing (polling mode)
    def init_callback(self):
        logger.debug('init_callback')
        self.v.set_callback(callback=self.msg_new)

    def show_help(self, msg, phone_num):
        logger.debug('show_help')
        help_text = "Welcome to VoiceX! Commands: register name, unregister name, post msg, view post-id, delete post-id, search query, reply post-id msg, follow @name/#tag, unfollow @name/#tag"
        if (not msg):
            pass
        elif ('register' in msg):
            help_text = "Help for register : register name. Example: register voicex"
        elif ('unregister' in msg):
            help_text = "Help for unregister : unregister name. Example: unregister voicex"
        elif ('post' in msg):
            help_text = "Help for post : post message. Example (simple post): post hello world. Example (tagged post): post voicex is free #voicex. Example (anonymous post): post voicex is free #anon"
        elif ('search' in msg):
            help_text = "Help for search : search search-keywords. Example: search kenya election"
        elif ('view' in msg):
            help_text = "Help for view : view post-id. Example: view 1"
        elif ('delete' in msg):
            help_text = "Help for delete : delete post-id. Example: delete 1"
        elif ('reply' in msg):
            help_text = "Help for reply : reply post-id reply-msg. Example (private reply): reply 1 welcome to voicex. Example (public reply): reply 1 welcome to voicex #public. Example (anonymous reply): reply 1 welcome to voicex #anon"
        elif ('follow' in msg):
            help_text = "Help for follow : follow @name/#tag. Example: follow @voicex or follow #election"
        elif ('unfollow' in msg):
            help_text = "Help for unfollow : unfollow @name/#tag. Example: unfollow @voicex or unfollow #election."
        else:
            pass
        self.v.sms(phone_num, help_text)

    def register(self, name, phone_num):
        logger.debug('register')
        res = self.mc.add_account(name, phone_num)
        if (res['status']):
            self.v.sms(
                phone_num,
                'Successfully registered %s with %s.' % (name, phone_num))
        else:
            self.v.sms(phone_num, res['code'])

    def unregister(self, name, phone_num):
        logger.debug('unregister')
        res = self.mc.delete_account(name, phone_num)
        if (res['status']):
            self.v.sms(phone_num, 'Unregistered %s' % (name))
        else:
            self.v.sms(phone_num, res['code'])

    def post(self, text, phone_num):
        logger.debug('post')
        res = self.mc.insert_post(phone_num, text)
        if (res['status']):
            post_id = res['val']
            self.v.sms(
                phone_num,
                'Msg successfully posted. To view the post, text -- view %s' %
                (str(post_id)))
            self.notify_followers(phone_num, text, post_id)
        else:
            self.v.sms(phone_num, res['code'])

    def notify_followers(self, phone_num, msg, post_id):
        logger.debug('notify_followers')
        tags = [
            tag.strip().lower() for tag in msg.split() if tag.startswith("#")
        ]
        res_find = self.mc.find_account(phone_num)
        account = 'anonymous'
        if (res_find['status'] and ('#anon' not in tags)):
            account = res_find['val'].name
            tags.append('@' + account)

        res_following = self.mc.find_following(tags)
        text = "From: @%s (Post ID: %s): %s" % (account, post_id, msg)
        if (res_following['status']):
            follow_list = res_following['val']
            if (len(follow_list) == 0):
                return
            recipients = ','.join(follow_list)
            self.v.sms(recipients, text)
        else:
            self.v.sms(phone_num, res['code'])

    def delete(self, post_id, phone_num):
        logger.debug('delete')
        res = self.mc.delete_post(post_id)
        if (res['status']):
            self.v.sms(
                phone_num,
                "Post ID:(%s) has been successfully deleted!" % (post_id))
        else:
            self.v.sms(phone_num, res['code'])

    def view(self, post_id, phone_num):
        logger.debug('view')
        res = self.mc.find_post(post_id)
        if (res['status']):
            post = res['val']
            out = post.post
            posts = Post.objects.filter(reply_to=post, public=True)
            for p in posts:
                out = out + "[Comment (ID:%s): %s]" % (str(p.id), p.post)
            self.v.sms(phone_num, out)
        else:
            self.v.sms(phone_num, res['code'])

    def search(self, query, phone_num):
        logger.debug('search')
        res = self.mc.search_posts(query)
        if (res['status']):
            self.v.sms(phone_num, res['val'])
        else:
            self.v.sms(phone_num, res['code'])

    def reply(self, msg_data, phone_num):
        logger.debug('reply')
        tokens = msg_data.strip().split(" ", 1)
        tokens = filter(lambda x: x != '', map(lambda x: x.strip(), tokens))
        post_id = None
        reply_text = None
        try:
            post_id = str(int(tokens[0]))
            reply_text = tokens[1]
        except:
            self.show_help('reply', phone_num)
            return
        account = 'anonymous'
        tags = [
            tag.strip().lower() for tag in reply_text.split()
            if tag.startswith("#")
        ]
        res_find_acc = self.mc.find_account(phone_num)
        if (res_find_acc['status'] and ('#anon' not in tags)):
            account = res_find_acc['val'].name
        reply_text = tokens[1]
        res_find = self.mc.find_post(post_id)
        if (res_find['status']):
            post = res_find['val']
            res_insert = {'status': False}
            if ('#public' in tags):
                res_insert = self.mc.insert_reply(phone_num,
                                                  reply_text,
                                                  post,
                                                  public=True)
            else:
                res_insert = self.mc.insert_reply(phone_num, reply_text, post)
            if (res_insert['status']):
                reply_id = str(res_insert['val'])
                self.v.sms(
                    phone_num,
                    "Your reply to post (ID:%s) has been successfully submitted!"
                    % (post_id))
                reply_to = post.phone
                self.v.sms(
                    reply_to, "[Reply(ID:%s, From: @%s) to Post(ID:%s)] - %s" %
                    (str(reply_id), account, str(post_id), reply_text))
            else:
                self.v.sms(phone_num, res_insert['code'])
        else:
            self.v.sms(phone_num, res_find['code'])

    def follow(self, tag, phone_num):
        logger.debug('follow')
        if (tag[0] not in ['#', '@']):
            self.v.sms(
                phone_num,
                "Invalid tag: '%s'. Valid tags are either hash-tags (start with '#'), or an account name (start with'@')."
                % (tag))
            return
        res = self.mc.add_following(tag.strip().lower(), phone_num)
        if (res['status']):
            self.v.sms(phone_num, 'You are now following %s.' % (tag))
        else:
            self.v.sms(phone_num, res['code'])

    def unfollow(self, name, phone_num):
        logger.debug('unfollow')
        res = self.mc.delete_following(name.strip().lower(), phone_num)
        if (res['status']):
            self.v.sms(phone_num, 'You are now not following %s.' % (name))
        else:
            self.v.sms(phone_num, res['code'])

    def parse(self, msg, phone_num):
        logger.debug('parse')
        try:
            msg_data = (msg.strip()).split(" ", 1)
            msg_data = map(lambda x: x.strip(), msg_data)
            cmd = msg_data[0].lower()
            text = None
            try:
                text = msg_data[1]
            except:
                pass

            if (not text):
                self.show_help(msg_data[0], phone_num)
                return

            if (cmd == "register"):
                self.register(text, phone_num)
            elif (cmd == "unregister"):
                self.unregister(text, phone_num)
            elif (cmd == "post"):
                self.post(text, phone_num)
            elif (cmd == "view"):
                self.view(text, phone_num)
            elif (cmd == "search"):
                self.search(text, phone_num)
            elif (cmd == "delete"):
                self.delete(text, phone_num)
            elif (cmd == "reply"):
                self.reply(text, phone_num)
            elif (cmd == "follow"):
                self.follow(text, phone_num)
            elif (cmd == "unfollow"):
                self.unfollow(text, phone_num)
            elif (cmd == "help"):
                try:
                    self.show_help(msg_data[1], phone_num)
                except:
                    self.show_help(None, phone_num)
            else:
                self.v.sms(
                    phone_num,
                    "Unknown command: '%s'. Text 'help' to get the list of commands."
                    % (cmd))
        except Exception, e:
            logger.exception('parse')