forked from FirmanKurniawan/Python-Projects
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
568 lines (463 loc) · 16.6 KB
/
Copy pathclient.py
File metadata and controls
568 lines (463 loc) · 16.6 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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
# -*- coding: utf-8 -*-
"""
line.client
~~~~~~~~~~~
LineClient for sending and receiving message from LINE server.
:copyright: (c) 2014 by Taehoon Kim.
:license: BSD, see LICENSE for more details.
"""
import re
import requests
import sys
from api import LineAPI
from models import LineGroup, LineContact, LineRoom, LineMessage
from curve.ttypes import TalkException, ToType, OperationType, Provider
reload(sys)
sys.setdefaultencoding("utf-8")
EMAIL_REGEX = re.compile(r"[^@]+@[^@]+\.[^@]+")
def check_auth(func):
def wrapper_check_auth(*args, **kwargs):
if args[0]._check_auth():
return func(*args, **kwargs)
return wrapper_check_auth
class LineClient(LineAPI):
profile = None
contacts = []
rooms = []
groups = []
def __init__(self, id=None, password=None, authToken=None, is_mac=True, com_name="carpedm20"):
"""Provide a way to communicate with LINE server.
:param id: `NAVER id` or `LINE email`
:param password: LINE account password
:param authToken: LINE session key
:param is_mac: (optional) os setting
:param com_name: (optional) name of your system
>>> client = LineClient("carpedm20", "xxxxxxxxxx")
Enter PinCode '9779' to your mobile phone in 2 minutes
>>> client = LineClient("carpedm20@gmail.com", "xxxxxxxxxx")
Enter PinCode '7390' to your mobile phone in 2 minutes
>>> client = LineClient(authToken="xxx ... xxx")
True
"""
LineAPI.__init__(self)
if not (authToken or id and password):
msg = "id and password or authToken is needed"
self.raise_error(msg)
if is_mac:
os_version = "10.9.4-MAVERICKS-x64"
user_agent = "DESKTOP:MAC:%s(%s)" % (os_version, self.version)
app = "DESKTOPMAC\t%s\tMAC\t%s" % (self.version, os_version)
else:
os_version = "5.1.2600-XP-x64"
user_agent = "DESKTOP:WIN:%s(%s)" % (os_version, self.version)
app = "DESKTOPWIN\t%s\tWINDOWS\t%s" % (self.version, os_version)
if com_name:
self.com_name = com_name
self._headers['User-Agent'] = user_agent
self._headers['X-Line-Application'] = app
if authToken:
self.authToken = self._headers['X-Line-Access'] = authToken
self.tokenLogin()
#self.ready()
else:
if EMAIL_REGEX.match(id):
self.provider = Provider.LINE # LINE
else:
self.provider = Provider.NAVER_KR # NAVER
self.id = id
self.password = password
self.is_mac = is_mac
self.login()
self.ready()
self.revision = self._getLastOpRevision()
self.getProfile()
try:
self.refreshGroups()
except: pass
try:
self.refreshContacts()
except: pass
try:
self.refreshActiveRooms()
except: pass
@check_auth
def getProfile(self):
"""Get `profile` of LINE account"""
self.profile = LineContact(self, self._getProfile())
return self.profile
def getContactByName(self, name):
"""Get a `contact` by name
:param name: name of a `contact`
"""
for contact in self.contacts:
if name == contact.name:
return contact
return None
def getContactById(self, id):
"""Get a `contact` by id
:param id: id of a `contact`
"""
for contact in self.contacts:
if contact.id == id:
return contact
if self.profile:
if self.profile.id == id:
return self.profile
return None
def getContactOrRoomOrGroupById(self, id):
"""Get a `contact` or `room` or `group` by its id
:param id: id of a instance
"""
return self.getContactById(id)\
or self.getRoomById(id)\
or self.getGroupById(id)
@check_auth
def refreshGroups(self):
"""Refresh groups of LineClient"""
self.groups = []
self.addGroupsWithIds(self._getGroupIdsJoined())
self.addGroupsWithIds(self._getGroupIdsInvited(), False)
@check_auth
def addGroupsWithIds(self, group_ids, is_joined=True):
"""Refresh groups of LineClient"""
new_groups = self._getGroups(group_ids)
self.groups += [LineGroup(self, group, is_joined) for group in new_groups]
self.groups.sort()
@check_auth
def refreshContacts(self):
"""Refresh contacts of LineClient """
contact_ids = self._getAllContactIds()
contacts = self._getContacts(contact_ids)
self.contacts = [LineContact(self, contact) for contact in contacts]
self.contacts.sort()
@check_auth
def findAndAddContactByUserid(self, userid):
"""Find and add a `contact` by userid
:param userid: user id
"""
try:
contact = self._findAndAddContactsByUserid(userid)
except TalkException as e:
self.raise_error(e.reason)
contact = contact.values()[0]
for c in self.contacts:
if c.id == contact.mid:
self.raise_error("%s already exists" % contact.displayName)
return
c = LineContact(self, contact)
self.contacts.append(c)
self.contacts.sort()
return c
@check_auth
def _findAndAddContactByPhone(self, phone):
"""Find and add a `contact` by phone number
:param phone: phone number (unknown format)
"""
try:
contact = self._findAndAddContactsByPhone(phone)
except TalkException as e:
self.raise_error(e.reason)
contact = contact.values()[0]
for c in self.contacts:
if c.id == contact.mid:
self.raise_error("%s already exists" % contact.displayName)
return
c = LineContact(self, contact)
self.contacts.append(c)
self.contacts.sort()
return c
@check_auth
def _findAndAddContactByEmail(self, email):
"""Find and add a `contact` by email
:param email: email
"""
try:
contact = self._findAndAddContactsByEmail(email)
except TalkException as e:
self.raise_error(e.reason)
contact = contact.values()[0]
for c in self.contacts:
if c.id == contact.mid:
self.raise_error("%s already exists" % contact.displayName)
return
c = LineContact(self, contact)
self.contacts.append(c)
self.contacts.sort()
return c
@check_auth
def _findContactByUserid(self, userid):
"""Find a `contact` by userid
:param userid: user id
"""
try:
contact = self._findContactByUserid(userid)
except TalkException as e:
self.raise_error(e.reason)
return LineContact(self, contact)
@check_auth
def refreshActiveRooms(self):
"""Refresh active chat rooms"""
start = 1
count = 50
self.rooms = []
while True:
channel = self._getMessageBoxCompactWrapUpList(start, count)
for box in channel.messageBoxWrapUpList:
if box.messageBox.midType == ToType.ROOM:
room = LineRoom(self, self._getRoom(box.messageBox.id))
self.rooms.append(room)
if len(channel.messageBoxWrapUpList) == count:
start += count
else:
break
@check_auth
def createGroupWithIds(self, name, ids=[]):
"""Create a group with contact ids
:param name: name of group
:param ids: list of contact ids
"""
try:
group = LineGroup(self, self._createGroup(name, ids))
self.groups.append(group)
return group
except Exception as e:
self.raise_error(e)
return None
@check_auth
def createGroupWithContacts(self, name, contacts=[]):
"""Create a group with contacts
:param name: name of group
:param contacts: list of contacts
"""
try:
contact_ids = []
for contact in contacts:
contact_ids.append(contact.id)
group = LineGroup(self, self._createGroup(name, contact_ids))
self.groups.append(group)
return group
except Exception as e:
self.raise_error(e)
return None
def getGroupByName(self, name):
"""Get a group by name
:param name: name of a group
"""
for group in self.groups:
if name == group.name:
return group
return None
def getGroupById(self, id):
"""Get a group by id
:param id: id of a group
"""
for group in self.groups:
if group.id == id:
return group
return None
@check_auth
def inviteIntoGroup(self, group, contacts=[]):
"""Invite contacts into group
:param group: LineGroup instance
:param contacts: LineContact instances to invite
"""
contact_ids = [contact.id for contact in contacts]
self._inviteIntoGroup(group.id, contact_ids)
def acceptGroupInvitation(self, group):
"""Accept a group invitation
:param group: LineGroup instance
"""
if self._check_auth():
try:
self._acceptGroupInvitation(group.id)
return True
except Exception as e:
self.raise_error(e)
return False
@check_auth
def leaveGroup(self, group):
"""Leave a group
:param group: LineGroup instance to leave
"""
try:
self._leaveGroup(group.id)
self.groups.remove(group)
return True
except Exception as e:
self.raise_error(e)
return False
@check_auth
def createRoomWithIds(self, ids=[]):
"""Create a chat room with contact ids"""
try:
room = LineRoom(self, self._createRoom(ids))
self.rooms.append(room)
return room
except Exception as e:
self.raise_error(e)
return None
@check_auth
def createRoomWithContacts(self, contacts=[]):
"""Create a chat room with contacts"""
try:
contact_ids = []
for contact in contacts:
contact_ids.append(contact.id)
room = LineRoom(self, self._createRoom(contact_ids))
self.rooms.append(room)
return room
except Exception as e:
self.raise_error(e)
return None
def getRoomById(self, id):
"""Get a room by id
:param id: id of a room
"""
for room in self.rooms:
if room.id == id:
return room
return None
@check_auth
def inviteIntoRoom(self, room, contacts=[]):
"""Invite contacts into room
:param room: LineRoom instance
:param contacts: LineContact instances to invite
"""
contact_ids = [contact.id for contact in contacts]
self._inviteIntoRoom(room.id, contact_ids)
@check_auth
def leaveRoom(self, room):
"""Leave a room
:param room: LineRoom instance to leave
"""
try:
self._leaveRoom(room.id)
self.rooms.remove(room)
return True
except Exception as e:
self.raise_error(e)
return False
@check_auth
def sendMessage(self, message, seq=0):
"""Send a message
:param message: LineMessage instance to send
"""
try:
return self._sendMessage(message, seq)
except TalkException as e:
self.updateAuthToken()
try:
return self._sendMessage(message, seq)
except Exception as e:
self.raise_error(e)
return False
@check_auth
def getMessageBox(self, id):
"""Get MessageBox by id
:param id: `contact` id or `group` id or `room` id
"""
try:
messageBoxWrapUp = self._getMessageBoxCompactWrapUp(id)
return messageBoxWrapUp.messageBox
except:
return None
@check_auth
def getRecentMessages(self, messageBox, count):
"""Get recent message from MessageBox
:param messageBox: MessageBox object
"""
id = messageBox.id
messages = self._getRecentMessages(id, count)
return self.getLineMessageFromMessage(messages)
@check_auth
def longPoll(self, count=50, debug=False):
"""Receive a list of operations that have to be processed by original
Line cleint.
:param count: number of operations to get from
:returns: a generator which returns operations
>>> for op in client.longPoll():
sender = op[0]
receiver = op[1]
message = op[2]
print "%s->%s : %s" % (sender, receiver, message)
"""
"""Check is there any operations from LINE server"""
OT = OperationType
try:
operations = self._fetchOperations(self.revision, count)
except EOFError:
return
except TalkException as e:
if e.code == 9:
self.raise_error("user logged in to another machine")
else:
return
for operation in operations:
if debug:
print operation
if operation.type == OT.END_OF_OPERATION:
pass
elif operation.type == OT.SEND_MESSAGE:
pass
elif operation.type == OT.RECEIVE_MESSAGE:
message = LineMessage(self, operation.message)
raw_sender = operation.message._from
raw_receiver = operation.message.to
sender = self.getContactOrRoomOrGroupById(raw_sender)
receiver = self.getContactOrRoomOrGroupById(raw_receiver)
# If sender is not found, check member list of group chat sent to
if sender is None:
try:
for m in receiver.members:
if m.id == raw_sender:
sender = m
break
except (AttributeError, TypeError):
pass
# If sender is not found, check member list of room chat sent to
if sender is None:
try:
for m in receiver.contacts:
if m.id == raw_sender:
sender = m
break
except (AttributeError, TypeError):
pass
if sender is None or receiver is None:
self.refreshGroups()
self.refreshContacts()
self.refreshActiveRooms()
sender = self.getContactOrRoomOrGroupById(raw_sender)
receiver = self.getContactOrRoomOrGroupById(raw_receiver)
if sender is None or receiver is None:
contacts = self._getContacts([raw_sender, raw_receiver])
if contacts:
if len(contacts) == 2:
sender = LineContact(self, contacts[0])
receiver = LineContact(self, contacts[1])
yield (sender, receiver, message)
elif operation.type in [ 60, 61 ]:
pass
else:
print "[*] %s" % OT._VALUES_TO_NAMES[operation.type]
print operation
self.revision = max(operation.revision, self.revision)
def createContactOrRoomOrGroupByMessage(self, message):
if message.toType == ToType.USER:
pass
elif message.toType == ToType.ROOM:
pass
elif message.toType == ToType.GROUP:
pass
def getLineMessageFromMessage(self, messages=[]):
"""Change Message objects to LineMessage objects
:param messges: list of Message object
"""
return [LineMessage(self, message) for message in messages]
def _check_auth(self):
"""Check if client is logged in or not"""
if self.authToken:
return True
else:
msg = "you need to login"
self.raise_error(msg)