Advertisement
Guest User

Untitled

a guest
Feb 4th, 2017
391
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 34.47 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3.    line.client
  4.    ~~~~~~~~~~~
  5.  
  6.    LineClient for sending and receiving message from LINE server.
  7.  
  8.    :copyright: (c) 2014 by Taehoon Kim.
  9.    :license: BSD, see LICENSE for more details.
  10. """
  11. import re
  12. import requests
  13. import sys
  14. import MySQLdb
  15. from api import LineAPI
  16. from models import LineGroup, LineContact, LineRoom, LineMessage
  17. from curve.ttypes import TalkException, ToType, OperationType, Provider
  18. reload(sys)
  19. sys.setdefaultencoding("utf-8")
  20.  
  21. EMAIL_REGEX = re.compile(r"[^@]+@[^@]+\.[^@]+")
  22.  
  23. def check_auth(func):
  24.     def wrapper_check_auth(*args, **kwargs):
  25.         if args[0]._check_auth():
  26.             return func(*args, **kwargs)
  27.     return wrapper_check_auth
  28.  
  29. class LineClient(LineAPI):
  30.     profile  = None
  31.     contacts = []
  32.     rooms    = []
  33.     groups   = []
  34.  
  35.     def __init__(self, id=None, password=None, authToken=None, is_mac=True, com_name="w0rmTech Sec - Protects your groups since 2016."):
  36.         """Provide a way to communicate with LINE server.
  37.  
  38.        :param id: `NAVER id` or `LINE email`
  39.        :param password: LINE account password
  40.        :param authToken: LINE session key
  41.        :param is_mac: (optional) os setting
  42.        :param com_name: (optional) name of your system
  43.  
  44.        >>> client = LineClient("carpedm20", "xxxxxxxxxx")
  45.        Enter PinCode '9779' to your mobile phone in 2 minutes
  46.        >>> client = LineClient("carpedm20@gmail.com", "xxxxxxxxxx")
  47.        Enter PinCode '7390' to your mobile phone in 2 minutes
  48.        >>> client = LineClient(authToken="xxx ... xxx")
  49.        True
  50.        """
  51.         LineAPI.__init__(self)
  52.  
  53.         if not (authToken or id and password):
  54.             msg = "id and password or authToken is needed"
  55.             self.raise_error(msg)
  56.  
  57.         if is_mac:
  58.             os_version = "10.9.4-MAVERICKS-x64"
  59.             user_agent = "DESKTOP:MAC:%s(%s)" % (os_version, self.version)
  60.             app = "DESKTOPMAC\t%s\tMAC\t%s" % (self.version, os_version)
  61.         else:
  62.             os_version = "5.1.2600-XP-x64"
  63.             user_agent = "DESKTOP:WIN:%s(%s)" % (os_version, self.version)
  64.             app = "DESKTOPWIN\t%s\tWINDOWS\t%s" % (self.version, os_version)
  65.  
  66.         if com_name:
  67.             self.com_name = com_name
  68.  
  69.         self._headers['User-Agent']         = user_agent
  70.         self._headers['X-Line-Application'] = app
  71.  
  72.         if authToken:
  73.             self.authToken = self._headers['X-Line-Access'] = authToken
  74.  
  75.             self.tokenLogin()
  76.             #self.ready()
  77.         else:
  78.             if EMAIL_REGEX.match(id):
  79.                 self.provider = Provider.LINE # LINE
  80.             else:
  81.                 self.provider = Provider.NAVER_EU # NAVER
  82.  
  83.             self.id = id
  84.             self.password = password
  85.             self.is_mac = is_mac
  86.  
  87.             self.login()
  88.             self.ready()
  89.  
  90.         self.revision = self._getLastOpRevision()
  91.         self.getProfile()
  92.  
  93.         try:
  94.             self.refreshGroups()
  95.         except: pass
  96.  
  97.         try:
  98.             self.refreshContacts()
  99.         except: pass
  100.  
  101.         try:
  102.             self.refreshActiveRooms()
  103.         except: pass
  104.  
  105.     @check_auth
  106.     def getProfile(self):
  107.         """Get `profile` of LINE account"""
  108.         self.profile = LineContact(self, self._getProfile())
  109.  
  110.         return self.profile
  111.  
  112.     def getContactByName(self, name):
  113.         """Get a `contact` by name
  114.        
  115.        :param name: name of a `contact`
  116.        """
  117.         for contact in self.contacts:
  118.             if name == contact.name:
  119.                 return contact
  120.  
  121.         return None
  122.  
  123.     def getContactById(self, id):
  124.         """Get a `contact` by id
  125.        
  126.        :param id: id of a `contact`
  127.        """
  128.         for contact in self.contacts:
  129.             if contact.id == id:
  130.                 return contact
  131.         if self.profile:
  132.             if self.profile.id == id:
  133.                 return self.profile
  134.  
  135.         return None
  136.  
  137.     def getContactOrRoomOrGroupById(self, id):
  138.         """Get a `contact` or `room` or `group` by its id
  139.  
  140.        :param id: id of a instance
  141.        """
  142.         return self.getContactById(id)\
  143.                 or self.getRoomById(id)\
  144.                 or self.getGroupById(id)
  145.  
  146.     @check_auth
  147.     def refreshGroups(self):
  148.         """Refresh groups of LineClient"""
  149.         self.groups = []
  150.  
  151.         self.addGroupsWithIds(self._getGroupIdsJoined())
  152.         self.addGroupsWithIds(self._getGroupIdsInvited(), False)
  153.  
  154.     @check_auth
  155.     def addGroupsWithIds(self, group_ids, is_joined=True):
  156.         """Refresh groups of LineClient"""
  157.         new_groups  = self._getGroups(group_ids)
  158.  
  159.         self.groups += [LineGroup(self, group, is_joined) for group in new_groups]
  160.  
  161.         self.groups.sort()
  162.  
  163.     @check_auth
  164.     def refreshContacts(self):
  165.         """Refresh contacts of LineClient """
  166.         contact_ids = self._getAllContactIds()
  167.         contacts    = self._getContacts(contact_ids)
  168.  
  169.         self.contacts = [LineContact(self, contact) for contact in contacts]
  170.  
  171.         self.contacts.sort()
  172.  
  173.     @check_auth
  174.     def findAndAddContactByUserid(self, userid):
  175.         """Find and add a `contact` by userid
  176.  
  177.        :param userid: user id
  178.        """
  179.         try:
  180.             contact = self._findAndAddContactsByUserid(userid)
  181.         except TalkException as e:
  182.             self.raise_error(e.reason)
  183.  
  184.         contact = contact.values()[0]
  185.  
  186.         for c in self.contacts:
  187.             if c.id == contact.mid:
  188.                 self.raise_error("%s already exists" % contact.displayName)
  189.                 return
  190.  
  191.         c = LineContact(self, contact.values()[0])
  192.         self.contacts.append(c)
  193.  
  194.         self.contacts.sort()
  195.         return c
  196.  
  197.     @check_auth
  198.     def _findContactByUserid(self, userid):
  199.         """Find a `contact` by userid
  200.  
  201.        :param userid: user id
  202.        """
  203.         try:
  204.             contact = self._findContactByUserid(userid)
  205.         except TalkException as e:
  206.             self.raise_error(e.reason)
  207.  
  208.         return LineContact(self, contact)
  209.  
  210.     @check_auth
  211.     def refreshActiveRooms(self):
  212.         """Refresh active chat rooms"""
  213.         start = 1
  214.         count = 50
  215.  
  216.         self.rooms = []
  217.  
  218.         while True:
  219.             channel = self._getMessageBoxCompactWrapUpList(start, count)
  220.  
  221.             for box in channel.messageBoxWrapUpList:
  222.                 if box.messageBox.midType == ToType.ROOM:
  223.                     room = LineRoom(self, self._getRoom(box.messageBox.id))
  224.                     self.rooms.append(room)
  225.  
  226.             if len(channel.messageBoxWrapUpList) == count:
  227.                 start += count
  228.             else:
  229.                 break
  230.  
  231.     def getGroupByName(self, name):
  232.         """Get a group by name
  233.        
  234.        :param name: name of a group
  235.        """
  236.         for group in self.groups:
  237.             if name == group.name:
  238.                 return group
  239.  
  240.         return None
  241.  
  242.     def getGroupById(self, id):
  243.         """Get a group by id
  244.        
  245.        :param id: id of a group
  246.        """
  247.         for group in self.groups:
  248.             if group.id == id:
  249.                 return group
  250.  
  251.         return None
  252.  
  253.     @check_auth
  254.     def inviteIntoGroup(self, group, contacts=[]):
  255.         """Invite contacts into group
  256.        
  257.        :param group: LineGroup instance
  258.        :param contacts: LineContact instances to invite
  259.        """
  260.         contact_ids = [contact.id for contact in contacts]
  261.         self._inviteIntoGroup(group.id, contact_ids)
  262.  
  263.     def acceptGroupInvitation(self, group):
  264.         """Accept a group invitation
  265.  
  266.        :param group: LineGroup instance
  267.        """
  268.         if self._check_auth():
  269.             try:
  270.                 self._acceptGroupInvitation(group.id)
  271.                 return True
  272.             except Exception as e:
  273.                 self.raise_error(e)
  274.                 return False
  275.  
  276.     @check_auth
  277.     def leaveGroup(self, group):
  278.         """Leave a group
  279.        
  280.        :param group: LineGroup instance to leave
  281.        """
  282.         try:
  283.             self._leaveGroup(group.id)
  284.             self.groups.remove(group)
  285.  
  286.             return True
  287.         except Exception as e:
  288.             self.raise_error(e)
  289.  
  290.             return False
  291.  
  292.     @check_auth
  293.     def leaveRoom(self, room):
  294.         """Leave a room
  295.        
  296.        :param room: LineRoom instance to leave
  297.        """
  298.         try:
  299.             self._leaveRoom(room.id)
  300.             self.rooms.remove(room)
  301.  
  302.             return True
  303.         except Exception as e:
  304.             self.raise_error(e)
  305.  
  306.             return False
  307.  
  308.     @check_auth
  309.     def sendMessage(self, message, seq=0):
  310.         """Send a message
  311.        
  312.        :param message: LineMessage instance to send
  313.        """
  314.         try:
  315.             return self._sendMessage(message, seq)
  316.         except TalkException as e:
  317.             self.updateAuthToken()
  318.             try:
  319.                 return self._sendMessage(message, seq)
  320.             except Exception as e:
  321.                 self.raise_error(e)
  322.  
  323.                 return False
  324.  
  325.     @check_auth
  326.     def getMessageBox(self, id):
  327.         """Get MessageBox by id
  328.  
  329.        :param id: `contact` id or `group` id or `room` id
  330.        """
  331.         try:
  332.             messageBoxWrapUp = self._getMessageBoxCompactWrapUp(id)
  333.  
  334.             return messageBoxWrapUp.messageBox
  335.         except:
  336.             return None
  337.  
  338.     @check_auth
  339.     def getRecentMessages(self, messageBox, count):
  340.         """Get recent message from MessageBox
  341.  
  342.        :param messageBox: MessageBox object
  343.        """
  344.         id = messageBox.id
  345.         messages = self._getRecentMessages(id, count)
  346.    
  347.         return self.getLineMessageFromMessage(messages)
  348.  
  349.     @check_auth
  350.     def longPoll(self, count=50, debug=False):
  351.         global kickinfo
  352.         global whitelist
  353.         """Receive a list of operations that have to be processed by original
  354.        Line cleint.
  355.  
  356.        :param count: number of operations to get from
  357.        :returns: a generator which returns operations
  358.  
  359.        >>> for op in client.longPoll():
  360.                sender   = op[0]
  361.                receiver = op[1]
  362.                message  = op[2]
  363.                print "%s->%s : %s" % (sender, receiver, message)
  364.        """
  365.         """Check is there any operations from LINE server"""
  366.         OT = OperationType
  367.  
  368.         try:
  369.             operations = self._fetchOperations(self.revision, count)
  370.         except EOFError:
  371.             return
  372.         except TalkException as e:
  373.             if e.code == 9:
  374.                 self.raise_error("user logged in to another machine")
  375.             else:
  376.                 return
  377.  
  378.         for operation in operations:
  379.             #print operation
  380.             db = MySQLdb.connect(host="192.241.226.91",    
  381.                     user="mbot",        
  382.                     passwd="!__!LineBot!__!1337",
  383.                     db="controller")
  384.             cur = db.cursor()
  385.             if debug:
  386.                 print operation
  387.             if operation.type == OT.END_OF_OPERATION:
  388.                 pass
  389.             elif operation.type == OT.SEND_MESSAGE:
  390.                 pass
  391.             elif operation.type == OT.RECEIVE_MESSAGE:
  392.                 message    = LineMessage(self, operation.message)
  393.  
  394.                 raw_sender   = operation.message._from
  395.                 raw_receiver = operation.message.to
  396.  
  397.                 sender   = self.getContactOrRoomOrGroupById(raw_sender)
  398.                 receiver = self.getContactOrRoomOrGroupById(raw_receiver)
  399.  
  400.                 # If sender is not found, check member list of group chat sent to
  401.                 if sender is None:
  402.                     try:
  403.                         for m in receiver.members:
  404.                             if m.id == raw_sender:
  405.                                 sender = m
  406.                                 break
  407.                     except (AttributeError, TypeError):
  408.                         pass
  409.  
  410.                 # If sender is not found, check member list of room chat sent to
  411.                 if sender is None:
  412.                     try:
  413.                         for m in receiver.contacts:
  414.                             if m.id == raw_sender:
  415.                                 sender = m
  416.                                 break
  417.                     except (AttributeError, TypeError):
  418.                         pass
  419.  
  420.                 if sender is None or receiver is None:
  421.                     self.refreshGroups()
  422.                     self.refreshContacts()
  423.                     self.refreshActiveRooms()
  424.  
  425.                     sender   = self.getContactOrRoomOrGroupById(raw_sender)
  426.                     receiver = self.getContactOrRoomOrGroupById(raw_receiver)
  427.  
  428.                 if sender is None or receiver is None:
  429.                     contacts = self._getContacts([raw_sender, raw_receiver])
  430.                     if contacts:
  431.                         if len(contacts) == 2:
  432.                             sender = LineContact(self, contacts[0])
  433.                             receiver = LineContact(self, contacts[1])
  434.                 yield (sender, receiver, message)
  435.             elif operation.type in [1,2,8,14,23,24,40,41,48,60,61]:
  436.                 pass
  437.             elif "NOTIFIED_INVITE_INTO_GROUP" in OT._VALUES_TO_NAMES[operation.type]:
  438.                 try:
  439.                     groupid = operation.param1
  440.                     inviterid = operation.param2
  441.                     invitedid = operation.param3
  442.                     invitedid = invitedid.split('\xle')
  443.                 except:
  444.                     pass
  445.                 if self.profile.id in invitedid:
  446.                     try:
  447.                         self.refreshGroups()
  448.                         data=cur.execute("Select * From admins Where uid='%s'"%(inviterid))
  449.                         if data ==1:
  450.                             self._acceptGroupInvitation(groupid)
  451.                         else:
  452.                             self._client.cancelGroupInvitation(0, groupid, inviterid)
  453.                     except Exception,e:
  454.                         print str(e)
  455.                 else:
  456.                     pass
  457.             elif "NOTIFIED_ACCEPT_GROUP_INVITATION" in OT._VALUES_TO_NAMES[operation.type]:
  458.                 kickinfo = operation
  459.                 m = re.search('param2=\'(.+?)\',', str(kickinfo))
  460.                 if m:
  461.                     kick = m.group(1)
  462.                     kickid = []
  463.                     kickid.append(kick);
  464.                 a = re.search('param1=\'(.+?)\',', str(kickinfo))
  465.                 if a:
  466.                     group = a.group(1)
  467.                     groupid = []
  468.                     groupid.append(group);
  469.                 try:
  470.                     group = self.getContactOrRoomOrGroupById(group)
  471.                     self._client.findAndAddContactsByMid(0, kick)
  472.                 except:
  473.                     pass
  474.             elif "NOTIFIED_INVITE_INTO_ROOM" in OT._VALUES_TO_NAMES[operation.type]:
  475.                 kickinfo = operation
  476.                 a = re.search('param1=\'(.+?)\',', str(kickinfo))
  477.                 if a:
  478.                     groupid = a.group(1)
  479.                     self._leaveRoom(groupid)
  480.             elif "NOTIFIED_KICKOUT_FROM_GROUP" in OT._VALUES_TO_NAMES[operation.type]:
  481.                 kickinfo = operation
  482.                 print kickinfo
  483.                 m = re.search('param2=\'(.+?)\',', str(kickinfo))
  484.                 if m:
  485.                     kick = m.group(1)
  486.                 a = re.search('param1=\'(.+?)\',', str(kickinfo))
  487.                 if a:
  488.                     group = a.group(1)
  489.                 z = re.search('param3=\'(.+?)\',', str(kickinfo))
  490.                 if z:
  491.                     invite = z.group(1)
  492.                 try:
  493.                     groupx = self.getContactOrRoomOrGroupById(group)
  494.                 except:
  495.                     pass
  496.                 try:
  497.                     data=cur.execute("Select * From admins Where uid='%s'"%(kick))
  498.                     if data ==1:
  499.                         pass
  500.                     else:
  501.                         self._client.kickoutFromGroup(0, group, [kick])
  502.                 except Exception,e:
  503.                     print str(e)
  504.                 try :
  505.                     self._client.findAndAddContactsByMid(0, invite)
  506.                 except Exception,e:
  507.                     print str(e)
  508.                 try :
  509.                     data=cur.execute("Select * From banlist Where uid='%s'"%(kick))
  510.                     if data ==1:
  511.                         pass
  512.                     else:
  513.                         self._client.inviteIntoGroup(0, group, [invite])
  514.                 except Exception,e:
  515.                     print str(e)
  516.             else:
  517.                 #print "[*] %s" % OT._VALUES_TO_NAMES[operation.type]
  518.                 #print operation
  519.                 pass
  520.  
  521.             self.revision = max(operation.revision, self.revision)
  522.  
  523.     def createContactOrRoomOrGroupByMessage(self, message):
  524.         if message.toType == ToType.USER:
  525.             pass
  526.         elif message.toType == ToType.ROOM:
  527.             pass
  528.         elif message.toType == ToType.GROUP:
  529.             pass
  530.  
  531.     def getLineMessageFromMessage(self, messages=[]):
  532.         """Change Message objects to LineMessage objects
  533.  
  534.        :param messges: list of Message object
  535.        """
  536.         return [LineMessage(self, message) for message in messages]
  537.  
  538.     def _check_auth(self):
  539.         """Check if client is logged in or not"""
  540.         if self.authToken:
  541.             return True
  542.         else:
  543.             msg = "you need to login"
  544.             self.raise_error(msg)
  545.  
  546. # -*- coding: utf-8 -*-
  547. """
  548.    line.client
  549.    ~~~~~~~~~~~
  550.  
  551.    LineClient for sending and receiving message from LINE server.
  552.  
  553.    :copyright: (c) 2014 by Taehoon Kim.
  554.    :license: BSD, see LICENSE for more details.
  555. """
  556. import re
  557. import requests
  558. import sys
  559. import MySQLdb
  560. from api import LineAPI
  561. from models import LineGroup, LineContact, LineRoom, LineMessage
  562. from curve.ttypes import TalkException, ToType, OperationType, Provider
  563.  
  564. reload(sys)
  565. sys.setdefaultencoding("utf-8")
  566.  
  567. EMAIL_REGEX = re.compile(r"[^@]+@[^@]+\.[^@]+")
  568.  
  569. def check_auth(func):
  570.     def wrapper_check_auth(*args, **kwargs):
  571.         if args[0]._check_auth():
  572.             return func(*args, **kwargs)
  573.     return wrapper_check_auth
  574.  
  575. class LineClient(LineAPI):
  576.     profile  = None
  577.     contacts = []
  578.     rooms    = []
  579.     groups   = []
  580.  
  581.     def __init__(self, id=None, password=None, authToken=None, is_mac=True, com_name="w0rmtech Inc."):
  582.         """Provide a way to communicate with LINE server.
  583.  
  584.        :param id: `NAVER id` or `LINE email`
  585.        :param password: LINE account password
  586.        :param authToken: LINE session key
  587.        :param is_mac: (optional) os setting
  588.        :param com_name: (optional) name of your system
  589.  
  590.        >>> client = LineClient("carpedm20", "xxxxxxxxxx")
  591.        Enter PinCode '9779' to your mobile phone in 2 minutes
  592.        >>> client = LineClient("carpedm20@gmail.com", "xxxxxxxxxx")
  593.        Enter PinCode '7390' to your mobile phone in 2 minutes
  594.        >>> client = LineClient(authToken="xxx ... xxx")
  595.        True
  596.        """
  597.         LineAPI.__init__(self)
  598.  
  599.         if not (authToken or id and password):
  600.             msg = "id and password or authToken is needed"
  601.             self.raise_error(msg)
  602.  
  603.         if is_mac:
  604.             os_version = "10.9.4-MAVERICKS-x64"
  605.             user_agent = "DESKTOP:MAC:%s(%s)" % (os_version, self.version)
  606.             app = "DESKTOPMAC\t%s\tMAC\t%s" % (self.version, os_version)
  607.         else:
  608.             os_version = "5.1.2600-XP-x64"
  609.             user_agent = "DESKTOP:WIN:%s(%s)" % (os_version, self.version)
  610.             app = "DESKTOPWIN\t%s\tWINDOWS\t%s" % (self.version, os_version)
  611.  
  612.         if com_name:
  613.             self.com_name = com_name
  614.  
  615.         self._headers['User-Agent']         = user_agent
  616.         self._headers['X-Line-Application'] = app
  617.  
  618.         if authToken:
  619.             self.authToken = self._headers['X-Line-Access'] = authToken
  620.  
  621.             self.tokenLogin()
  622.             #self.ready()
  623.         else:
  624.             if EMAIL_REGEX.match(id):
  625.                 self.provider = Provider.LINE # LINE
  626.             else:
  627.                 self.provider = Provider.NAVER_EU # NAVER
  628.  
  629.             self.id = id
  630.             self.password = password
  631.             self.is_mac = is_mac
  632.  
  633.             self.login()
  634.             self.ready()
  635.  
  636.         self.revision = self._getLastOpRevision()
  637.         self.getProfile()
  638.  
  639.         try:
  640.             self.refreshGroups()
  641.         except: pass
  642.  
  643.         try:
  644.             self.refreshContacts()
  645.         except: pass
  646.  
  647.         try:
  648.             self.refreshActiveRooms()
  649.         except: pass
  650.  
  651.     @check_auth
  652.     def getProfile(self):
  653.         """Get `profile` of LINE account"""
  654.         self.profile = LineContact(self, self._getProfile())
  655.  
  656.         return self.profile
  657.  
  658.     def getContactByName(self, name):
  659.         """Get a `contact` by name
  660.        
  661.        :param name: name of a `contact`
  662.        """
  663.         for contact in self.contacts:
  664.             if name == contact.name:
  665.                 return contact
  666.  
  667.         return None
  668.  
  669.     def getContactById(self, id):
  670.         """Get a `contact` by id
  671.        
  672.        :param id: id of a `contact`
  673.        """
  674.         for contact in self.contacts:
  675.             if contact.id == id:
  676.                 return contact
  677.         if self.profile:
  678.             if self.profile.id == id:
  679.                 return self.profile
  680.  
  681.         return None
  682.  
  683.     def getContactOrRoomOrGroupById(self, id):
  684.         """Get a `contact` or `room` or `group` by its id
  685.  
  686.        :param id: id of a instance
  687.        """
  688.         return self.getContactById(id)\
  689.                 or self.getRoomById(id)\
  690.                 or self.getGroupById(id)
  691.  
  692.     @check_auth
  693.     def refreshGroups(self):
  694.         """Refresh groups of LineClient"""
  695.         self.groups = []
  696.  
  697.         self.addGroupsWithIds(self._getGroupIdsJoined())
  698.         self.addGroupsWithIds(self._getGroupIdsInvited(), False)
  699.  
  700.     @check_auth
  701.     def addGroupsWithIds(self, group_ids, is_joined=True):
  702.         """Refresh groups of LineClient"""
  703.         new_groups  = self._getGroups(group_ids)
  704.  
  705.         self.groups += [LineGroup(self, group, is_joined) for group in new_groups]
  706.  
  707.         self.groups.sort()
  708.  
  709.     @check_auth
  710.     def refreshContacts(self):
  711.         """Refresh contacts of LineClient """
  712.         contact_ids = self._getAllContactIds()
  713.         contacts    = self._getContacts(contact_ids)
  714.  
  715.         self.contacts = [LineContact(self, contact) for contact in contacts]
  716.  
  717.         self.contacts.sort()
  718.  
  719.     @check_auth
  720.     def findAndAddContactByUserid(self, userid):
  721.         """Find and add a `contact` by userid
  722.  
  723.        :param userid: user id
  724.        """
  725.         try:
  726.             contact = self._findAndAddContactsByUserid(userid)
  727.         except TalkException as e:
  728.             self.raise_error(e.reason)
  729.  
  730.         contact = contact.values()[0]
  731.  
  732.         for c in self.contacts:
  733.             if c.id == contact.mid:
  734.                 self.raise_error("%s already exists" % contact.displayName)
  735.                 return
  736.  
  737.         c = LineContact(self, contact.values()[0])
  738.         self.contacts.append(c)
  739.  
  740.         self.contacts.sort()
  741.         return c
  742.  
  743.     @check_auth
  744.     def _findContactByUserid(self, userid):
  745.         """Find a `contact` by userid
  746.  
  747.        :param userid: user id
  748.        """
  749.         try:
  750.             contact = self._findContactByUserid(userid)
  751.         except TalkException as e:
  752.             self.raise_error(e.reason)
  753.  
  754.         return LineContact(self, contact)
  755.  
  756.     @check_auth
  757.     def refreshActiveRooms(self):
  758.         """Refresh active chat rooms"""
  759.         start = 1
  760.         count = 50
  761.  
  762.         self.rooms = []
  763.  
  764.         while True:
  765.             channel = self._getMessageBoxCompactWrapUpList(start, count)
  766.  
  767.             for box in channel.messageBoxWrapUpList:
  768.                 if box.messageBox.midType == ToType.ROOM:
  769.                     room = LineRoom(self, self._getRoom(box.messageBox.id))
  770.                     self.rooms.append(room)
  771.  
  772.             if len(channel.messageBoxWrapUpList) == count:
  773.                 start += count
  774.             else:
  775.                 break
  776.  
  777.     @check_auth
  778.     def getGroupByName(self, name):
  779.         """Get a group by name
  780.        
  781.        :param name: name of a group
  782.        """
  783.         for group in self.groups:
  784.             if name == group.name:
  785.                 return group
  786.  
  787.         return None
  788.  
  789.     def getGroupById(self, id):
  790.         """Get a group by id
  791.        
  792.        :param id: id of a group
  793.        """
  794.         for group in self.groups:
  795.             if group.id == id:
  796.                 return group
  797.  
  798.         return None
  799.  
  800.     @check_auth
  801.     def inviteIntoGroup(self, group, contacts=[]):
  802.         """Invite contacts into group
  803.        
  804.        :param group: LineGroup instance
  805.        :param contacts: LineContact instances to invite
  806.        """
  807.         contact_ids = [contact.id for contact in contacts]
  808.         self._inviteIntoGroup(group.id, contact_ids)
  809.  
  810.     def acceptGroupInvitation(self, group):
  811.         """Accept a group invitation
  812.  
  813.        :param group: LineGroup instance
  814.        """
  815.         if self._check_auth():
  816.             try:
  817.                 self._acceptGroupInvitation(group.id)
  818.                 return True
  819.             except Exception as e:
  820.                 self.raise_error(e)
  821.                 return False
  822.  
  823.     @check_auth
  824.     def leaveGroup(self, group):
  825.         """Leave a group
  826.        
  827.        :param group: LineGroup instance to leave
  828.        """
  829.         try:
  830.             self._leaveGroup(group.id)
  831.             self.groups.remove(group)
  832.  
  833.             return True
  834.         except Exception as e:
  835.             self.raise_error(e)
  836.  
  837.             return False
  838.  
  839.     @check_auth
  840.     def sendMessage(self, message, seq=0):
  841.         """Send a message
  842.        
  843.        :param message: LineMessage instance to send
  844.        """
  845.         try:
  846.             return self._sendMessage(message, seq)
  847.         except TalkException as e:
  848.             self.updateAuthToken()
  849.             try:
  850.                 return self._sendMessage(message, seq)
  851.             except Exception as e:
  852.                 self.raise_error(e)
  853.  
  854.                 return False
  855.  
  856.     @check_auth
  857.     def getMessageBox(self, id):
  858.         """Get MessageBox by id
  859.  
  860.        :param id: `contact` id or `group` id or `room` id
  861.        """
  862.         try:
  863.             messageBoxWrapUp = self._getMessageBoxCompactWrapUp(id)
  864.  
  865.             return messageBoxWrapUp.messageBox
  866.         except:
  867.             return None
  868.  
  869.     @check_auth
  870.     def getRecentMessages(self, messageBox, count):
  871.         """Get recent message from MessageBox
  872.  
  873.        :param messageBox: MessageBox object
  874.        """
  875.         id = messageBox.id
  876.         messages = self._getRecentMessages(id, count)
  877.    
  878.         return self.getLineMessageFromMessage(messages)
  879.  
  880.     @check_auth
  881.     def longPoll(self, count=50, debug=False):
  882.         global kickinfo
  883.         global whitelist
  884.         """Receive a list of operations that have to be processed by original
  885.        Line cleint.
  886.  
  887.        :param count: number of operations to get from
  888.        :returns: a generator which returns operations
  889.  
  890.        >>> for op in client.longPoll():
  891.                sender   = op[0]
  892.                receiver = op[1]
  893.                message  = op[2]
  894.                print "%s->%s : %s" % (sender, receiver, message)
  895.        """
  896.         """Check is there any operations from LINE server"""
  897.         OT = OperationType
  898.  
  899.         try:
  900.             operations = self._fetchOperations(self.revision, count)
  901.         except EOFError:
  902.             return
  903.         except TalkException as e:
  904.             if e.code == 9:
  905.                 self.raise_error("user logged in to another machine")
  906.             else:
  907.                 return
  908.  
  909.         for operation in operations:
  910.             #print operation
  911.             if debug:
  912.                 print operation
  913.             if operation.type == OT.END_OF_OPERATION:
  914.                 pass
  915.             elif operation.type == OT.SEND_MESSAGE:
  916.                 pass
  917.             elif operation.type == OT.RECEIVE_MESSAGE:
  918.                 message    = LineMessage(self, operation.message)
  919.  
  920.                 raw_sender   = operation.message._from
  921.                 raw_receiver = operation.message.to
  922.  
  923.                 sender   = self.getContactOrRoomOrGroupById(raw_sender)
  924.                 receiver = self.getContactOrRoomOrGroupById(raw_receiver)
  925.  
  926.                 # If sender is not found, check member list of group chat sent to
  927.                 if sender is None:
  928.                     try:
  929.                         for m in receiver.members:
  930.                             if m.id == raw_sender:
  931.                                 sender = m
  932.                                 break
  933.                     except (AttributeError, TypeError):
  934.                         pass
  935.  
  936.                 if str(message) == "None":
  937.                     #sticker
  938.                     pass
  939.  
  940.                 # If sender is not found, check member list of room chat sent to
  941.                 if sender is None:
  942.                     try:
  943.                         for m in receiver.contacts:
  944.                             if m.id == raw_sender:
  945.                                 sender = m
  946.                                 break
  947.                     except (AttributeError, TypeError):
  948.                         pass
  949.  
  950.                 if sender is None or receiver is None:
  951.                     self.refreshGroups()
  952.                     self.refreshContacts()
  953.                     self.refreshActiveRooms()
  954.  
  955.                     sender   = self.getContactOrRoomOrGroupById(raw_sender)
  956.                     receiver = self.getContactOrRoomOrGroupById(raw_receiver)
  957.  
  958.                 if sender is None or receiver is None:
  959.                     contacts = self._getContacts([raw_sender, raw_receiver])
  960.                     if contacts:
  961.                         if len(contacts) == 2:
  962.                             sender = LineContact(self, contacts[0])
  963.                             receiver = LineContact(self, contacts[1])
  964.                 yield (sender, receiver, message)
  965.             elif operation.type in [1,2,8,14,23,24,40,41,48,60,61]:
  966.                 pass
  967.             elif "NOTIFIED_INVITE_INTO_GROUP" in OT._VALUES_TO_NAMES[operation.type]:
  968.                 try:
  969.                     groupid = operation.param1
  970.                     inviterid = operation.param2
  971.                     invitedid = operation.param3
  972.                     invitedid = invitedid.split("\\x1e")
  973.                 except:
  974.                     pass
  975.                 if self.profile.id in invitedid:
  976.                     try:
  977.                         self.refreshGroups()
  978.                         data=cur.execute("Select * From admins Where uid='%s'"%(inviterid))
  979.                         if data ==1:
  980.                             self._acceptGroupInvitation(groupid)
  981.                         else:
  982.                             self._client.cancelGroupInvitation(0, groupid, inviterid)
  983.                     except Exception,e:
  984.                         print str(e)
  985.                 else:
  986.                     pass
  987.             elif "NOTIFIED_ACCEPT_GROUP_INVITATION" in OT._VALUES_TO_NAMES[operation.type]:
  988.                 kickinfo = operation
  989.                 m = re.search('param2=\'(.+?)\',', str(kickinfo))
  990.                 if m:
  991.                     kick = m.group(1)
  992.                     kickid = []
  993.                     kickid.append(kick);
  994.                 a = re.search('param1=\'(.+?)\',', str(kickinfo))
  995.                 if a:
  996.                     group = a.group(1)
  997.                     groupid = []
  998.                     groupid.append(group);
  999.                 try:
  1000.                     group = self.getContactOrRoomOrGroupById(group)
  1001.                     self._client.findAndAddContactsByMid(0, kick)
  1002.                 except:
  1003.                     pass
  1004.             elif "NOTIFIED_INVITE_INTO_ROOM" in OT._VALUES_TO_NAMES[operation.type]:
  1005.                 kickinfo = operation
  1006.                 a = re.search('param1=\'(.+?)\',', str(kickinfo))
  1007.                 if a:
  1008.                     groupid = a.group(1)
  1009.                     self._leaveRoom(groupid)
  1010.             elif "NOTIFIED_KICKOUT_FROM_GROUP" in OT._VALUES_TO_NAMES[operation.type]:
  1011.                 kickinfo = operation
  1012.                 print kickinfo
  1013.                 m = re.search('param2=\'(.+?)\',', str(kickinfo))
  1014.                 if m:
  1015.                     kick = m.group(1)
  1016.                 a = re.search('param1=\'(.+?)\',', str(kickinfo))
  1017.                 if a:
  1018.                     group = a.group(1)
  1019.                 z = re.search('param3=\'(.+?)\',', str(kickinfo))
  1020.                 if z:
  1021.                     invite = z.group(1)
  1022.                 try:
  1023.                     groupx = self.getContactOrRoomOrGroupById(group)
  1024.                 except:
  1025.                     pass
  1026.                 try:
  1027.                     data=cur.execute("Select * From admins Where uid='%s'"%(kick))
  1028.                     if data ==1:
  1029.                         pass
  1030.                     else:
  1031.                         self._client.kickoutFromGroup(0, group, [kick])
  1032.                 except Exception,e:
  1033.                     print str(e)
  1034.                 try :
  1035.                     self._client.findAndAddContactsByMid(0, invite)
  1036.                 except Exception,e:
  1037.                     print str(e)
  1038.                 try :
  1039.                     data=cur.execute("Select * From banlist Where uid='%s'"%(invite))
  1040.                     if data ==1:
  1041.                         pass
  1042.                     else:
  1043.                         self._client.inviteIntoGroup(0, group, [invite])
  1044.                 except Exception,e:
  1045.                     print str(e)
  1046.             else:
  1047.                 #print "[*] %s" % OT._VALUES_TO_NAMES[operation.type]
  1048.                 #print operation
  1049.                 pass
  1050.  
  1051.             self.revision = max(operation.revision, self.revision)
  1052.  
  1053.     def createContactOrRoomOrGroupByMessage(self, message):
  1054.         if message.toType == ToType.USER:
  1055.             pass
  1056.         elif message.toType == ToType.ROOM:
  1057.             pass
  1058.         elif message.toType == ToType.GROUP:
  1059.             pass
  1060.  
  1061.     def getLineMessageFromMessage(self, messages=[]):
  1062.         """Change Message objects to LineMessage objects
  1063.  
  1064.        :param messges: list of Message object
  1065.        """
  1066.         return [LineMessage(self, message) for message in messages]
  1067.  
  1068.     def _check_auth(self):
  1069.         """Check if client is logged in or not"""
  1070.         if self.authToken:
  1071.             return True
  1072.         else:
  1073.             msg = "you need to login"
  1074.             self.raise_error(msg)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement