def searchYoutube(self, msg): m = self.ytUrl.search(msg) if m: ytId = m.group(6) clog.debug('(searchYoutube) matched: %s' % ytId, sys) d = apiClient.requestYtApi(ytId) d.addCallbacks(self.doSendChat, self.errYtInfo)
def _com_np(self, yuka, username, args, source): offset = parse_arg_for_offset(args) try: cy = yuka.wsFactory.prot except(AttributeError): clog.warning('No cytube instance.', syst) return i = cy.getIndexFromUid(cy.nowPlayingUid) clog.debug('np+0 index is {}'.format(i), syst) if i is None: return else: i = i + offset if not cy.playlist[i:i+1]: # out of bounds clog.warning('Request out of bounds.', syst) return media = cy.playlist[i]['media'] title = media['title'].encode('utf8') url = make_media_url(media['type'], media['id']) if offset > 0: plus_minus = '+{}'.format(offset) elif offset < 0: # str(negative_int) already includes '-' sign plus_minus = '{}'.format(offset) else: plus_minus = '' msg = '[np{}]: {} {}'.format(plus_minus, title, url) yuka.reply(msg, source, username)
def _insertQueue(txn, mediaId, userId, timeNow, flag): sql = 'INSERT INTO Queue VALUES (DEFAULT, %s, %s, %s, %s)' binds = (mediaId, userId, timeNow, flag) clog.debug('(insertQueue) binds: %s, %s, %s, %s' % (mediaId, userId, timeNow, flag), sys) txn.execute(sql, binds) return [txn.lastrowid]
def popQueue(self): clog.debug('(popQueue) sending chat from IRC chat queue', sys) self.bucketToken -= 1 msg, action = self.chatQueue.popleft() self.logSay(self.channelName, msg, action) if not self.throttleLoop.running: self.throttleLoop.start(2, now=False)
def logProcess(self, user, msg, flag): timeNow = getTime() nickname = user.split('!')[0] i = user.find('~') j = user.find('@') username = user[i+1:j] host = user[j+1:] if nickname in self.nickdict: keyId = self.nickdict[nickname]['keyId'] if keyId is None: # a callback for the keyId must already be registered clog.error('(logProcess) key None for user %s' % nickname, sys) dd = self.nickdict[nickname]['deferred'] dd.addCallback(self.logChat, 3, timeNow, msg, flag) if keyId: d = self.logChat(keyId, 3, timeNow, msg, flag) else: self.nickdict[nickname] = {'keyId': None, 'deferred': None} clog.debug('(logProcess) added %s to nickdict' % nickname, sys) values = (nickname.lower(), username, host, nickname, 0) d = database.queryIrcuser(nickname.lower(), username, host) d.addCallback(self.cbQueryIrcuser, values) d.addCallback(self.cacheKey, nickname) d.addCallback(self.logChat, 3, timeNow, msg, flag) #dd = self.queryOrAddUser(nickname, username, host) #dd.addCallback(self.logChat, 3, timeNow, msg, flag) self.nickdict[nickname]['deferred'] = d
def unflagUser(flag, nameLower, isRegistered): clog.debug( 'Removing flag %s to %s, %s' % (bin(flag), nameLower, isRegistered), sys) sql = 'UPDATE CyUser SET flag=(flag|?) WHERE nameLower=? AND registered=?' binds = (~flag, nameLower, isRegistered) return operate(sql, binds)
def _insertSong(txn, res, lastUpdate): clog.debug('(insertSong)', sys) sql = 'INSERT OR REPLACE INTO Song VALUES (?, ?, ?)' data, songId = res binds = (songId, data, lastUpdate) txn.execute(sql, binds) return [txn.lastrowid]
def _ppm_subscribeLike(self, cy, username, args, source): clog.debug('Received subscribeLike from %s' % username, syst) if username in cy.userdict: cy.userdict[username]['subscribeLike'] = True # send value for current media if username in self.currentLikes: msg = '%%%%%s' % self.currentLikes[username] cy.doSendPm(msg, username)
def _insertQueue(txn, mediaId, userId, timeNow, flag): sql = 'INSERT INTO Queue VALUES (?, ?, ?, ?, ?)' binds = (None, mediaId, userId, timeNow, flag) clog.debug( '(insertQueue) binds: %s, %s, %s, %s' % (mediaId, userId, timeNow, flag), sys) txn.execute(sql, binds) return [txn.lastrowid]
def processBody(self, body): clog.debug('(processBody) Received session string %s ' % body, sys) msg = body.split(',') sid = msg[0][:msg[0].find(':')] ws = 'ws://%s:%s/socket.io/1/websocket/%s/' % (config['Cytube']['url'], int(config['Cytube']['port']), sid) return ws
def sumPoints(self, res, username, isRegistered): # sample res [(True, [(420,)]), (True, [(258.7464,)])] # [(True, [(0,)]), (True, [(None,)])] # no add/queue, no userinoutrow clog.debug('(sumPoints %s)' % res, syst) try: points = res[0][1][0][0] + res[1][1][0][0] except (TypeError): points = res[0][1][0][0] return points
def cbMakeWsUrl(self, response, secure=True): """ response : string json of server """ if not response: return clog.debug(response) servers = json.loads(response) return servers['url']+'?v=6&encoding=json'
def cbGetPage(response, callback): if response.code == 200: clog.debug('Received OK response: %s' % response.code, syst) d = readBody(response) d.addCallback(callback) return d else: clog.error('Received bad response: %s' % response.code, syst) return defer.fail(response)
def checkMedia(self, res, mType, mId): if mType == 'yt': self.ytq.append(mId) d = task.deferLater(reactor, 1 * (len(self.ytq)-1), self.collectYtQueue, mId) clog.debug('(checkMedia) Length of ytq %s' % len(self.ytq), sys) return d else: return defer.succeed('EmbedOk') # TODO
def setNewProfile(self, res, currentRow, nextRow): clog.debug('(setNewProfile) %s' % res, syst) name = config['Cytube']['username'] password = config['Cytube']['password'] text = res[0][1] imgurl = res[0][2] d = cyProfileChange.changeProfileInfo(text, imgurl) d.addCallback(self.setProfileFlags, currentRow, nextRow) return d
def sumPoints(self, res, username, isRegistered): # sample res [(True, [(420,)]), (True, [(258.7464,)])] # [(True, [(0,)]), (True, [(None,)])] # no add/queue, no userinoutrow clog.debug('(sumPoints %s)' % res, syst) try: points = res[0][1][0][0] + res [1][1][0][0] except(TypeError): points = res[0][1][0][0] return points
def queryVocaDbInfo(mType, mId): clog.debug('(queryVocaDbInfo)', sys) sql = ('SELECT CyUser.nameOriginal, MediaSong.mediaId, Song.songId, ' 'MediaSong.method, Song.data FROM CyUser, MediaSong, Song WHERE ' 'MediaSong.songId=Song.songId AND CyUser.userId=MediaSong.userId ' 'AND MediaSong.mediaId = (SELECT mediaId FROM Media WHERE type=? ' 'AND id=?)') binds = (mType, mId) return query(sql, binds)
def queryVocaDbInfo(mType, mId): clog.debug('(queryVocaDbInfo)', sys) sql = ('SELECT CyUser.nameOriginal, MediaSong.mediaId, Song.songId, ' 'MediaSong.method, Song.data FROM CyUser, MediaSong, Song WHERE ' 'MediaSong.songId=Song.songId AND CyUser.userId=MediaSong.userId ' 'AND MediaSong.mediaId = (SELECT mediaId FROM Media WHERE type=%s ' 'AND id=%s)') binds = (mType, mId) return query(sql, binds)
def setNewProfile(self, res, currentRow, nextRow): clog.debug('(setNewProfile) %s' % res, sys) name = config['Cytube']['username'] password = config['Cytube']['password'] text = res[0][1] imgurl = res[0][2] d = cyProfileChange.changeProfileInfo(text, imgurl) d.addCallback(self.setProfileFlags, currentRow, nextRow) return d
def queryResult(res): """ Returns single row (list) from a query. If None, returns NoRowException. """ if not res: #clog.debug('(queryResult) No match found', sys) return defer.fail(NoRowException) else: clog.debug('(queryResult) match found %s' % res, sys) return defer.succeed(res[0])
def getIndexFromUid(self, uid): """ Return video index of self.playlist given an UID """ try: media = (i for i in self.playlist if i['uid'] == uid).next() index = self.playlist.index(media) clog.debug('(getIndexFromUid) Looking up uid %s, index is %s' % (uid, index), sys) return index except StopIteration as e: clog.error('(getIndexFromUid) media UID %s not found' % uid, sys)
def addToken(self): if self.bucketToken < 13: clog.debug('(addToken) +1, token: %s' % self.bucketToken, sys) self.bucketToken += 1 if self.underSpam and self.bucketToken > 10: self.underSpam = False self.say(self.channelName, '[Resuming relay from Cytube.]') self.factory.handle.sendToCy('[Resuming relay to IRC.]', modflair=True)
def recCyMsg(self, source, user, msg, needProcessing, action=False): if self.inIrcChan and user != self.cyName and source != 'pm': clog.debug('recCyMsg: %s' % msg, sys) if not action: cleanMsg = '(%s) %s' % (user, msg) else: cleanMsg = '( * %s) %s' % (user, msg) self.sendToIrc(cleanMsg) if needProcessing and not action and self.cy: self.processCommand(source, user, msg, prot=self.wsFactory.prot)
def addToken(self): if self.bucketToken < self.bucketTokenMax: clog.debug('(addToken) +1, token: %s' % self.bucketToken, sys) self.bucketToken += 1 if self.underSpam and self.bucketToken > 10: self.underSpam = False self.say(self.channelName, '[Resuming relay from Cytube.]') self.factory.handle.sendToCy('[Resuming relay to IRC.]', modflair=True) elif self.bucketToken == self.bucketTokenMax: self.throttleLoop.stop()
def addToPlaylist(self, item, afterUid): if afterUid == 'prepend': index = 0 else: index = self.getIndexFromUid(afterUid) self.playlist.insert(index + 1, item) # I want to print media['title'] but depending on the terminal # it fails to encode some characters (usually symbols) clog.debug('(addToPlaylist) Inserting uid %s %s after index %s' % (item['uid'], item['media']['title'].encode('utf-8'), index), sys)
def removeUser(self, res, username): clog.debug('(removeUser) Removing user', sys) try: if not self.userdict[username]['inChannel']: del self.userdict[username] clog.debug('(removeUser) deleted %s' % username, sys) else: clog.error('(removeUser) skipping: user %s in channel' % username, sys) except(KeyError): clog.error('(removeUser) Failed: user %s not in userdict' % username, sys) return KeyError
def queryOrAddUser(self, nickname, username, host): clog.debug('(queryOrAddUser) Quering %s:%s:%s' % (nickname, username, host), sys) d = database.dbQuery(('userId', 'flag'), 'ircUser', nickLower=nickname.lower(), username=username, host=host) d.addCallback(database.queryResult) values = (None, nickname.lower(), username, host, nickname, 0) d.addErrback(database.dbInsertReturnLastRow, 'ircUser', *values) clog.debug('(queryOrAddUser) Adding %s' % username, sys) d.addErrback(self.dbErr) d.addCallback(self.cacheKey, nickname) d.addErrback(self.dbErr) return d
def irc_RPL_NAMREPLY(self, prefix, params): channel = params[2].lower() nicklist = params[3].split(' ') if channel not in self._namescallback: return n = self._namescallback[channel][1] n += nicklist clog.debug('(irc_RPL_NAMREPLY) nicklist:%s' % nicklist, sys) if channel == self.channelName: self.nicklist = nicklist
def _bulkQueryMediaSong(txn, playlist): clog.debug('(_queryBulkMediaSong)', sys) songlessMedia = [] for media in playlist: sql = ('SELECT songId FROM MediaSong WHERE mediaId IS' ' (SELECT mediaId FROM Media WHERE type=? AND id=?)') txn.execute(sql, media) row = txn.fetchone() if not row: songlessMedia.append(media) clog.info(songlessMedia, sys) return songlessMedia
def youtubeDesc(res, mType, mId, timeNow): """Return a deferred of a Youtube API query""" if res[0] == 0: # no match clog.debug(('(youtubeDesc) No Youtube id match. Will attemp to retrieve' 'and parse description %s') % res, syst) d = apiClient.requestYtApi(mId, 'desc') d.addCallback(searchYtDesc, mType, mId, timeNow) d.addErrback(errNoIdInDesc) return d else: # pass-through the with method 0, results return defer.succeed((0, res[0]))
def irc_RPL_ENDOFNAMES(self, prefix, params): channel = params[1].lower() if channel not in self._namescallback: return callbacks, namelist = self._namescallback[channel] for cb in callbacks: cb.callback(namelist) del self._namescallback[channel] clog.debug('(irc_RPL_ENDOFNAMES) prefix::%s, params %s.' % (prefix, params), sys)
def _bulkQueryMediaSong(txn, playlist): clog.debug('(_queryBulkMediaSong)', sys) songlessMedia = [] for media in playlist: sql = ('SELECT songId FROM MediaSong WHERE mediaId IS' ' (SELECT mediaId FROM Media WHERE type=? AND id=?)') binds = (media[1], media[2]) txn.execute(sql, binds) row = txn.fetchone() if not row: songlessMedia.append(binds) clog.info(songlessMedia, '[database] bulkquerymedia') return songlessMedia
def youtubeDesc(res, mType, mId, timeNow): """Return a deferred of a Youtube API query""" if res[0] == 0: # no match clog.debug( ('(youtubeDesc) No Youtube id match. Will attemp to retrieve' 'and parse description %s') % res, syst) d = apiClient.requestYtApi(mId, 'desc') d.addCallback(searchYtDesc, mType, mId, timeNow) d.addErrback(errNoIdInDesc) return d else: # pass-through the with method 0, results return defer.succeed((0, res[0]))
def _cyCall_userLeave(self, fdict): username = fdict['args'][0]['name'] if not username: return # when anon leaves, might be sync bug self.userdict[username]['inChannel'] = False d = self.userdict[username]['deferred'] clog.debug('_cyCall_userLeave) user %s has left. Adding callbacks' % username, sys) leftUser = self.userdict[username] d.addCallback(self.clockUser, leftUser, int(time.time())) d.addErrback(self.dbErr) d.addCallback(self.removeUser, username) d.addErrback(self.dbErr)
def connectCy(self, startresults): if not startresults[0][0]: clog.error('Failed to retrieve server socket.io configuration') self.restartConnection() else: sioClientConfig = json.loads(startresults[0][1]) host = config['Cytube']['domain'] s = sioClientConfig['servers'][1]['url'] ws = 'ws://{0}/socket.io/?transport=websocket'.format( s[s.find('//') + 2:]) clog.debug('(cySocketIo) Cytube ws uri: %s' % ws, sys) self.wsFactory = WsFactory(ws) self.wsFactory.handle = self connectWS(self.wsFactory)
def irc_RPL_ENDOFNAMES(self, prefix, params): channel = params[1].lower() if channel not in self._namescallback: return callbacks, namelist = self._namescallback[channel] for cb in callbacks: cb.callback(namelist) del self._namescallback[channel] clog.debug( '(irc_RPL_ENDOFNAMES) prefix::%s, params %s.' % (prefix, params), sys)
def onMessage(self, msg, binary): if binary: msg = zlib.decompress(msg).decode('utf-8') clog.debug('Binary received: {0} bytes'.format(len(msg))) #self.log.debug(u"{msg!s}", msg=msg) msg = json.loads(msg) op = msg.get('op') data = msg.get('d') seq = msg.get('s') t = msg.get('t') self.log.debug(u"Received a Discord Gateway frame: {op!s}", op=op) if seq: self.factory.session['seq'] = seq if op == self.HEARTBEAT: heartbeat_interval_seconds = data['heartbeat_interval'] / 1000.0 self.laters.append(reactor.callLater(heartbeat_interval_seconds, self.beatHeart)) elif op == self.HEARTBEAT_ACK: # self.log.debug('Received HEARTBEAT_ACK') return elif op == self.INVALID_SESSION: # wait 5 seconds before sending OP2 IDENTIFY self.log.error('Received OP 9 INVALID SESSION - maybe ' 'we are reconnected too soon. ' 'Will send IDENTIFY in 5 seconds.') reactor.callLater(5.0, self.identify) elif op == self.HELLO: # start the heartbeat loop self.heart_beat_interval = data['heartbeat_interval'] self.heart_beat_loop = task.LoopingCall(self.beatHeart) self.heart_beat_loop.start(self.heart_beat_interval/1000.0, now=True) self.loops.append(self.heart_beat_loop) if self.factory.session.get('session_id'): self.resume() else: self.identify() elif op == self.DISPATCH: self.dispatch(t, data)
def recCyMsg(self, source, user, msg, needProcessing, action=False): if user == self.cyName: return if self.inIrcChan and user != self.cyName and source != 'pm': clog.debug('recCyMsg: %s' % msg, syst) if not action: cleanMsg = '(%s) %s' % (user, msg) else: cleanMsg = '( * %s) %s' % (user, msg) self.sendToIrc(cleanMsg) if self.discordRestEnabled: self.dcr.onMessage(source, user, msg, action) if needProcessing and not action and self.cy: self.processCommand(source, user, msg, prot=self.wsFactory.prot)
def _cyCall_chatMsg(self, fdict): if not self.receivedChatBuffer: return args = fdict['args'][0] timeNow = round(time.time(), 2) username = args['username'] msg = tools.unescapeMsg(args['msg']) chatCyTime = round((args['time'])/1000.0, 2) if 'modflair' in args['meta']: modflair = args['meta']['modflair'] else: modflair = None if username == '[server]': keyId = 2 elif username in self.userdict: keyId = self.userdict[username]['keyId'] if keyId: self.unloggedChat.append((None, keyId, timeNow, chatCyTime, msg, modflair, 0)) if time.time() - self.lastChatLogTime < 3: self.cancelChatLog() self.dChat = reactor.callLater(3, self.bulkLogChat, self.unloggedChat) else: self.cancelChatLog() self.bulkLogChat(self.unloggedChat) self.lastChatLogTime = time.time() else: assert keyId is None chatArgs = (timeNow, chatCyTime, msg, modflair, 0) self.userdict[username]['deferred'].addCallback(self.deferredChat, chatArgs) if username != config['Cytube']['username'] and username != '[server]': # comment line below for test. #TODO make proper test self.factory.handle.recCyMsg(username, msg) self.searchYoutube(msg) # check for commands if msg.startswith('$'): command = msg.split()[0][1:] clog.debug('received command %s from %s' % (command, username), sys) args = tuple(msg.split()[1:]) thunk = getattr(self, '_com_%s' % (command,), None) if thunk is not None: thunk(username, msg)
def searchYtDesc(jsonResponse, mType, mId, timeNow): items = jsonResponse['items'] if not items: clog.error('searchYtDesc: no video found', syst) return defer.fail(Exception('No video found')) desc = items[0]['snippet']['description'] m = nicoMatch.search(desc) if m: nicoId = m.group(0) clog.debug(nicoId, 'searchYtDesc') d = requestApiByPv('NicoNico', nicoId, timeNow) d.addCallback(nicoAcquire) d.addCallback(database.insertMediaSongPv, mType, mId, 1, timeNow) return d else: database.insertMediaSongPv(0, mType, mId, 1, timeNow) return defer.fail(Exception('No NicoId in Description found'))
def queryOrAddUser(self, nickname, username, host): clog.debug( '(queryOrAddUser) Quering %s:%s:%s' % (nickname, username, host), sys) d = database.dbQuery(('userId', 'flag'), 'ircUser', nickLower=nickname.lower(), username=username, host=host) d.addCallback(database.queryResult) values = (None, nickname.lower(), username, host, nickname, 0) d.addErrback(database.dbInsertReturnLastRow, 'ircUser', *values) clog.debug('(queryOrAddUser) Adding %s' % username, sys) d.addErrback(self.dbErr) d.addCallback(self.cacheKey, nickname) d.addErrback(self.dbErr) return d
def processVdbJson(body): clog.info("(processVdbJson) Received reply from VocaDB", syst) clog.debug("(processVdbJson) %s" % body, syst) body = body.decode("UTF-8") try: pbody = json.loads(body) except (ValueError): return defer.fail(None) try: if "message" in pbody: clog.error(pbody["message"], syst) except (TypeError): # body is null (pbody is None) clog.error("(processVdbJson) null from Vocadb", syst) return defer.succeed(0) songId = pbody["id"] return defer.succeed((body, songId))
def logProcess(self, user, msg, flag): timeNow = getTime() nickname = user.split('!')[0] i = user.find('~') j = user.find('@') username = user[i + 1:j] host = user[j + 1:] if nickname in self.nickdict: keyId = self.nickdict[nickname]['keyId'] if keyId is None: # a callback for the keyId must already be registered clog.error('(logProcess) key None for user %s' % nickname, sys) dd = self.nickdict[nickname]['deferred'] dd.addCallback(self.logChat, 3, timeNow, msg, flag) if keyId: d = self.logChat(keyId, 3, timeNow, msg, flag) else: self.nickdict[nickname] = {'keyId': None, 'deferred': None} clog.debug('(logProcess) added %s to nickdict' % nickname, sys) dd = self.queryOrAddUser(nickname, username, host) dd.addCallback(self.logChat, 3, timeNow, msg, flag) self.nickdict[nickname]['deferred'] = dd
def _com_reprint(self, cy, username, args, source): if not args or len(args) > 11 or not args.startswith('sm'): clog.debug('reprint - no args or bad args', syst) return # user must be rank at least rank 3 AND be on the allowed.txt list rank = cy._getRank(username) if rank < 2: clog.debug('not enough rank for $reprint', syst) return try: with open('connections/cytube/plugins/loaders/allowed.cfg') as f: allowed = f.read().lower().split() except (IOError): clog.error("Reprint cancelled - No allowed.txt found", syst) return if username.lower() not in allowed: clog.debug('not in allowed.txt for $reprint', syst) return try: if cy.reprint is False: clog.debug('cy.reprint is False', syst) return elif self.reprint == 'IP': cy.doSendChat('[reprint] Busy with another request.', toIrc=False) return except (AttributeError): cy.reprint = True path = 'connections/cytube/plugins/loaders' try: d = json.load(open('%s/videos.json' % path)) except (IOError, ValueError): #No file, #not a JSON clog.error('Error loading file "videos.json"', syst) return if args in d: cy.doSendChat('[reprint] This video has already been reprinted', toIrc=False) return p = ReprintProtocol(self, cy) clog.warning('Spawning Reprint process!', syst) subprocess = reactor.spawnProcess(p, sys.executable, [ 'python', 'reprinter.py', '--smid', args, '--user', config['reprinter']['nicoid'], '--pass', config['reprinter']['nicopass'] ], os.environ, path)
def _com_add(self, cy, username, args, source): """Parse $add command arguments and pass to callback. Called by $add. Requirements: Source: Cytube chat Rank: non-guest """ if source != 'chat': return rank = cy._getRank(username) if not rank: return elif rank < 2: maxAdd = 5 else: maxAdd = 20 if args is None: args = '-n 3' #clog.info(args, syst) title, arguments = self.parseTitle(args) args = arguments.split() # shortcut in case people want to $add # # of course this can't be combined with other args try: num = int(args[0]) args = ['-n', str(num)] except (ValueError, IndexError): pass parser = argparse.ArgumentParser() parser.add_argument('-s', '--sample', default='queue', choices=('queue', 'q', 'add', 'a', 'like', 'l')) parser.add_argument('-u', '--user', default='Anyone') parser.add_argument('-g', '--guest', default=False, type=bool) parser.add_argument('-n', '--number', default=3, type=int) parser.add_argument('-a', '--artist', default='') #TODO parser.add_argument('-T', '--temporary', default=False, type=bool) parser.add_argument('-N', '--next', default=False, type=bool) parser.add_argument('-o', '--omit', default=False, type=bool) # Yukari removes last 100 rows of queue from the media sample # set recent to True to disable this behavior parser.add_argument('-r', '--recent', default=False, type=bool) parser.add_argument('-z', '--tag', default='') try: args = parser.parse_args(args) except (SystemExit): cy.doSendChat('Invalid arguments.') return args.number = min(args.number, maxAdd) if rank < 2: args.omit = False info = ( 'Quantity:%s, sample:%s, user:%s, guest:%s, temp:%s, ' 'pos:%s, title:%s, include ommited:%s, recent:%s, tag:%s' % (args.number, args.sample, args.user, args.guest, args.temporary, args.next, title, args.omit, args.recent, args.tag)) #self.doSendChat(reply) clog.debug('(_com_add) %s' % info, syst) isRegistered = not args.guest if args.next: args.next = 'next' else: args.next = 'end' args.user = args.user.lower() if args.user == 'anyone': args.user = None if args.tag: #cap at 10 songs...getting songs by tag is expensive and slow! args.number = min(args.number, 10) d = self.getVocadbMedia((cy.doAddMedia, args.temporary, args.next), args.number, args.tag) else: d = self.getRandMedia(args.sample, args.number, args.user, isRegistered, title, args.recent) d.addCallback(self.addSearchResults, cy, args.temporary, args.next)
def sendLineAndLog(self, line): clog.debug(line, sys) self.sendLine(line)
def action(self, user, channel, data): clog.debug('action %s by %s' % (data, user), sys) self.factory.handle.recIrcMsg(user, channel, data, modifier='action') flag = 2 #action self.logProcess(user, data, flag)
def queryMediaSongRow(mType, mId): clog.debug('(queryMediaSongData)', sys) sql = ('SELECT * FROM MediaSong WHERE mediaId IS' ' (SELECT mediaId FROM Media WHERE type=? AND id=?)') binds = (mType, mId) return query(sql, binds)
def cbFindCsrf(body): csrf = body[body.find('_csrf', 1500) + 14:body.find('_csrf', 1500) + 50] clog.debug('csrf is %s' % csrf, syst) return csrf
def nicoAcquire(res): clog.debug('nicoAcquire %s' % res, syst) if res[0] == 0: # no match clog.debug('(youtubeDesc) No Nico id match.', syst) return defer.succeed((1, res[0]))
def unflagMedia(flag, mType, mId): clog.debug('Removing flag %s to %s, %s' % (bin(flag), mType, mId), sys) sql = 'UPDATE media SET flag=(flag&?) WHERE type=? AND id=?' binds = (~flag, mType, mId) return operate(sql, binds)