Skip to content

Commit 876e7d4

Browse files
author
d_dd
committed
Work on rin server
1 parent 558555e commit 876e7d4

File tree

6 files changed

+151
-22
lines changed

6 files changed

+151
-22
lines changed

cyClient.py

+46-12
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ def __init__(self):
2121
self.queueMediaList = deque()
2222
self.canBurst = False
2323
self.lastQueueTime = time.time() - 20 #TODO
24+
self.nowPlayingMedia = None
2425
### Need to imporve this regex, it matches non-videos
2526
# ie https://www.youtube.com/feed/subscriptions
2627
self.ytUrl = re.compile(
@@ -159,16 +160,20 @@ def _cyCall_chatMsg(self, fdict):
159160
if msg.startswith('$'):
160161
command = msg.split()[0][1:]
161162
clog.debug('received command %s from %s' % (command, username), sys)
162-
args = tuple(msg.split()[1:])
163+
argsList = msg.split(' ', 1)
164+
if len(argsList) == 2:
165+
args = argsList[1]
166+
else:
167+
args = None
163168
thunk = getattr(self, '_com_%s' % (command,), None)
164169
if thunk is not None:
165-
thunk(username, msg)
170+
thunk(username, args)
166171

167-
def _com_vocadb(self, username, msg):
172+
def _com_vocadb(self, username, args):
168173
if not vdb:
169174
return
170175
try:
171-
songId = int(msg.split()[1])
176+
songId = int(args)
172177
except IndexError:
173178
clog.error('(_com_vocadb) Index Error by %s' % username, sys)
174179
return
@@ -194,17 +199,15 @@ def parseTitle(self, command):
194199
shortMsg = command[:tBeg-3] + command[tEnd+1:]
195200
return command[tBeg:tEnd], shortMsg
196201

197-
def _com_add(self, username, msg):
202+
def _com_add(self, username, args):
198203
rank = self._getRank(username)
199-
clog.info('rank is %s' % rank, 'RANK')
200204
if not rank:
201205
return
202206
elif rank < 2:
203207
maxAdd = 5
204208
else:
205209
maxAdd = 20
206-
clog.info(msg, sys)
207-
args = msg[len('$add '):]
210+
clog.info(args, sys)
208211
clog.info(args, 'sent to parseTitle')
209212
title, arguments = self.parseTitle(args)
210213
args = arguments.split()
@@ -255,10 +258,41 @@ def _com_add(self, username, msg):
255258
self.getRandMedia(args.sample, args.number, args.user, isRegistered,
256259
title, args.temporary, args.next)
257260

258-
def _com_omit(self, username, msg):
261+
def _com_omit(self, username, args):
262+
rank = self._getRank(username)
263+
clog.info('(_com_omit) %s' % args)
264+
if rank < 2 or not self.nowPlayingMedia:
265+
return
266+
parsed = self._omit_args(args)
267+
if not parsed:
268+
self.doSendChat('Invalid parameters.')
269+
elif parsed:
270+
mType, mId = parsed
271+
d = database.flagMedia(2, mType, mId)
272+
d.addCallback(lambda res: clog.info(res, sys))
273+
274+
def _omit_args(self, args):
275+
if not args:
276+
mType, mId, mTitle = self.nowPlayingMedia
277+
return mType, mId
278+
elif args:
279+
if ',' in args:
280+
argl = args.split(',')
281+
elif ' ' in args:
282+
argl = args.split()
283+
else:
284+
return 'yt', args
285+
try:
286+
return argl[1], argl[0]
287+
except(IndexError):
288+
return False
289+
290+
def _com_unomit(self, username, msg):
259291
rank = self._getRank(username)
260-
if rank < 2:
292+
if rank < 2 or not self.nowPlayingMedia:
261293
return
294+
mType, mId, mTitle = self.nowPlayingMedia
295+
database.unflagMedia(2, mType, mId)
262296

263297
def _getRank(self, username):
264298
try:
@@ -540,11 +574,11 @@ def dbErr(self, err):
540574
clog.error('(dbErr): %s' % err.value, sys)
541575

542576
def _cyCall_changeMedia(self, fdict):
543-
# set self.nowPlaying
577+
# set self.nowPlayingMedia
544578
mType = fdict['args'][0]['type']
545579
mId = fdict['args'][0]['id']
546580
mTitle = fdict['args'][0]['title']
547-
self.nowPlaying = (mType, mId, mTitle) # these are unicode
581+
self.nowPlayingMedia = (mType, mId, mTitle) # these are unicode
548582
# everything has to be encoded to utf-8 or it errors
549583
s = mTitle.encode('utf-8') + ' (%s, %s)' % (mType.encode('utf-8'),
550584
mId.encode('utf-8'))

database.py

+4
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,10 @@ def addByUserAdd(nameLower, registered, words, limit):
239239
clog.info(binds, 'sql')
240240
return query(sql, binds)
241241

242+
def getMediaById(mediaId):
243+
sql = 'SELECT * FROM Media WHERE mediaId=?'
244+
return query(sql, (mediaId,))
245+
242246
dbpool = adbapi.ConnectionPool('sqlite3', 'data.db', check_same_thread=False,
243247
cp_max=1) # one thread max; avoids db locks
244248
dbpool.runInteraction(turnOnFK)

ext/rinception.py

+68-8
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,83 @@
11
""" Server for steam-bot """
22
from twisted.internet import protocol, reactor
3+
from twisted.protocols.basic import LineReceiver
34
from tools import clog
5+
import database
6+
import json
47

58
sys = 'RinServer'
69

7-
class Messenger(protocol.Protocol):
10+
class LineReceiverFactory(protocol.Factory):
11+
def buildProtocol(self, addr):
12+
clog.info('(buildProtocol) Building protocol', sys)
13+
return LineReceiver(self)
814

15+
class LineReceiver(LineReceiver):
16+
917
def __init__(self, factory):
1018
self.factory = factory
1119

1220
def connectionMade(self):
13-
self.transport.write('Hi Rin!! -from Yukari\r\n')
21+
#self.sendLine('Hi Rin!! -from Yukari')
1422
clog.info('(connectionMade) Connection established', sys)
1523

16-
def dataReceived(self, data): # echo
17-
self.transport.write(data)
24+
def lineReceived(self, line):
25+
clog.info(line, sys)
26+
d = checkLine(line)
27+
if not d:
28+
clog.error('at linerec')
29+
return # if it's not a proper JSON don't reply
30+
request = self.parseDict(d)
31+
if request:
32+
callType, args = request
33+
thunk = getattr(self, '_rin_%s' % (callType,), None)
34+
if thunk is not None:
35+
thunk(args)
36+
elif thunk is None:
37+
response = {'callType': None, 'result': 'badname'}
38+
self.sendLineAndLog(json.dumps(response))
39+
else:
40+
clog.error('no request')
1841

19-
class MessengerFactory(protocol.Factory):
42+
43+
def _rin_mediaById(self, args):
44+
if 'mediaId' not in args:
45+
response = {'callType': 'mediaById', 'result': 'badargs'}
46+
self.sendLineAndLog(json.dumps(response))
47+
return
48+
mediaId = args['mediaId']
49+
d = database.getMediaById(mediaId)
50+
d.addCallback(self.sendOneMedia, args)
2051

21-
def buildProtocol(self, addr):
22-
clog.info('(buildProtocol) Building protocol', sys)
23-
return Messenger(self)
52+
def sendOneMedia(self, res, args):
53+
if res:
54+
mRow = res[0]
55+
mediaDict = {'mediaId': mRow[0], 'type': mRow[1], 'id': mRow[2],
56+
'dur': mRow[3], 'title': mRow[4], 'flag': mRow[5]}
57+
response = {'callType': 'mediaById', 'result':'ok',
58+
'resource': mediaDict}
59+
else:
60+
response = {'callType': 'mediaById', 'result':'nomatch',
61+
'args': args}
62+
self.sendLineAndLog(json.dumps(response))
63+
64+
def sendError(self, callType):
65+
errorDict = {'callType':callType, 'result':'error'}
66+
self.sendLineAndLog(json.dumps(errorDict))
67+
68+
def parseDict(self, d):
69+
if 'callType' not in d or 'args' not in d:
70+
return False
71+
callType = d['callType']
72+
args = d['args']
73+
return (callType, args)
74+
75+
def sendLineAndLog(self, line):
76+
clog.debug(line)
77+
self.sendLine(line)
78+
79+
def checkLine(line):
80+
try:
81+
return json.loads(line)
82+
except(ValueError):
83+
return False

ext/rinsight.py

+13
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,26 @@
22
from twisted.internet import reactor
33
from twisted.internet.protocol import Protocol, ClientCreator
44
#from tools import clog
5+
import json
56

67
sys = 'RinClient'
78

89

910
class Prot(Protocol):
11+
def connectionMade(self):
12+
req = {'callType':'mediaById', 'args':{'mediaId':99}}
13+
reqs = json.dumps(req) + '\r\n'
14+
reactor.callLater(1, self.transport.write, reqs)
15+
1016
def dataReceived(self, data):
17+
print type(data)
1118
print data
19+
try:
20+
print json.loads(data)
21+
except(ValueError):
22+
print 'could not parse %s' % data
23+
# reactor.callLater(1, self.transport.write,'t')
24+
# reactor.callLater(1, self.transport.write,'\r\n')
1225

1326

1427
c = ClientCreator(reactor, Prot)

test_cyClientMisc.py

+18
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import unittest
22
from cyClient import CyProtocol
3+
from ext.rinception import Lr
34

45
class TestParseAdd(unittest.TestCase):
56

@@ -25,5 +26,22 @@ def test(self):
2526
title = self.prot.parseTitle(command)
2627
self.assertEqual(title, (None, '-n 2'))
2728

29+
class TestParseDict(unittest.TestCase):
30+
31+
def setUp(self):
32+
self.rec = Lr(None)
33+
34+
def test(self):
35+
requestd = {"callType":"mediaById", "args":{"mediaId":123}}
36+
req = self.rec.parseDict(requestd)
37+
callType, args = req
38+
self.assertEqual(callType, 'mediaById')
39+
self.assertEqual(args, {'mediaId':123})
40+
###
41+
requestd = {"calltype":"mediaById", "args":{"mediaId":123}}
42+
req = self.rec.parseDict(requestd)
43+
self.assertEqual(req, False)
44+
2845
if __name__ == '__main__':
2946
unittest.main()
47+
#request = '{"callType":"mediaById", "args":"{"mediaId":123}}'

yukari.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from ircClient import IrcProtocol, IrcFactory
22
from cyClient import CyProtocol, WsFactory
3-
from ext.rinception import Messenger, MessengerFactory
3+
from ext.rinception import LineReceiver, LineReceiverFactory
44
from ext.apiserver import GetMedia
55
from twisted.web.server import Site
66
from conf import config
@@ -67,7 +67,7 @@ def ircConnect(self):
6767
def rinstantiate(self, port):
6868
""" Start server for Rin (steam-bot) """
6969
clog.info('(rinstantiate) Starting server for Rin', sys)
70-
self.rinFactory = MessengerFactory()
70+
self.rinFactory = LineReceiverFactory()
7171
reactor.listenTCP(18914, self.rinFactory)
7272

7373
def recIrcMsg(self, user, channel, msg):

0 commit comments

Comments
 (0)