示例#1
0
 def _cbCheckFlag(self, res):
     try:
         flag = res[0][0]
     except(IndexError): # Media not in database yet
         clog.warning('(_cbCheckFlag) New media, no flag returned', syst)
         flag = 0 # can't have been flagged yet
     return defer.succeed(flag)
示例#2
0
文件: vdbapi.py 项目: d-dd/Yukari
def requestPVByTagOffset(cbInfo, tag, offset):
    def localCb(res):
        try:
            pbody = json.loads(res[0])
        except(ValueError):
            return defer.fail(Exception('No video found'))
        
        if pbody.get('items') and pbody['items'][0] and pbody['items'][0]['pVs']:
            for pv in pbody['items'][0]['pVs']:
                # TODO: soundcloud, too
                if pv[u'service'] == "Youtube":
                    return [['yt', pv['pvId']]]

    agent = Agent(reactor)
    args = {'query': '',
            'onlyWithPvs': True,
            'pvServices': 'Youtube',
            'tagName': tag,
            'getTotalCount': False,
            'start': offset,
            'fields': 'Pvs',
            'maxResults': 1,
            }

    url = 'https://vocadb.net/api/songs?{}'.format(urllib.urlencode(args))
    url = url.encode('utf8')
    clog.warning('(requestSongByTagOffset) %s' % url, syst)
    d = agent.request('GET', url, Headers({'User-Agent':[UserAgentVdb]}))
    d.addCallback(readBody)
    d.addCallbacks(processVdbJsonForSongId, apiError)
    d.addCallback(localCb)
    return d
示例#3
0
文件: reprint.py 项目: d-dd/Yukari
 def connectionMade(self):
     self.pid = self.transport.pid
     clog.warning('Connected to Reprint process!', syst)
     self.cy.doSendChat('[reprint] Connected to reprint process. This may '
                        'take up to 30 minutes.', toIrc=False)
     self.output = ''
     self.cy.reprint = 'IP'
示例#4
0
文件: nowplaying.py 项目: d-dd/Yukari
    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)
示例#5
0
 def clientConnectionLost(self, connector, reason):
     clog.warning('(clientConnectionLost) Connection lost to Cyutbe. %s'
                  % reason, sys)
     if not self.handle.cyRestart:
         self.handle.doneCleanup('cy')
     else:
         #self.handle.cyPost() # reconnect
         self.handle.doneCleanup('cy')
示例#6
0
文件: ircClient.py 项目: d-dd/Yukari
 def checkServer(self):
     """ Tests periodically if the last PONG from the server was
         recent. Otherwise, treats it as a disconnect, and quits the
         connection. """
     pongAgo = round(time.time() - self.lastPong, 3)
     #clog.info('(checkServer) %d seconds since last PONG' % pongAgo, sys)
     if time.time() - self.lastPong > 35:
         clog.warning('No PONG response for over 35 seconds!', sys)
         self.quit(message='No server response...')
示例#7
0
 def connectionMade(self):
     self.pid = self.transport.pid
     clog.warning('Connected to Reprint process!', syst)
     self.cy.doSendChat(
         '[reprint] Connected to reprint process. This may '
         'take up to 30 minutes.',
         toIrc=False)
     self.output = ''
     self.cy.reprint = 'IP'
示例#8
0
 def checkServer(self):
     """ Tests periodically if the last PONG from the server was
         recent. Otherwise, treats it as a disconnect, and quits the
         connection. """
     pongAgo = round(time.time() - self.lastPong, 3)
     #clog.info('(checkServer) %d seconds since last PONG' % pongAgo, sys)
     if time.time() - self.lastPong > 35:
         clog.warning('No PONG response for over 35 seconds!', sys)
         self.quit(message='No server response...')
示例#9
0
def retryDatabase(error, operation, sql, binds, attempt):
    if attempt >= 5:
        clog.error(error.getBriefTraceback(),
                   'Reached max attempts: %s' % attempt)
        return
    clog.warning(error.getBriefTraceback(), 'retrying attempt: %s' % attempt)
    if operation == 'operate':
        return operate(sql, binds, attempt)
    elif operation == 'query':
        return query(sql, binds, attempt)
示例#10
0
def main():
    clog.error('test custom log', 'cLog tester')
    clog.warning('test custom log', 'cLog tester')

    yukari = Connections()
    yukari.startCytubeClient()
    yukari.ircConnect()
    reactor.callWhenRunning(createShellServer, yukari)
    reactor.addSystemEventTrigger('before', 'shutdown', yukari.cleanup)
    reactor.run()
示例#11
0
文件: database.py 项目: d-dd/Yukari
def retryDatabase(error, operation, sql, binds, attempt):
    if attempt >= 5:
        clog.error(error.getBriefTraceback(), 
                'Reached max attempts: %s' % attempt)
        return
    clog.warning(error.getBriefTraceback(), 'retrying attempt: %s' % attempt)
    if operation == 'operate':
        return operate(sql, binds, attempt)
    elif operation == 'query':
        return query(sql, binds, attempt)
示例#12
0
 def flagOrDelete(self, res, cy, mType, mId, title, uid):
     if res == 'EmbedOk':
         clog.info('%s EmbedOk' % title, syst)
         database.unflagMedia(0b1, mType, mId)
     elif res in ('Status503', 'Status403', 'Status404', 'NoEmbed','NoVid'):
         clog.warning('%s: %s' % (title, res), syst)
         cy.doDeleteMedia(uid)
         cy.uncache(mId)
         msg = 'Removing non-playable media %s' % title
         database.flagMedia(0b1, mType, mId)
         cy.sendCyWhisper(msg)
示例#13
0
文件: vdbapi.py 项目: zig-for/Yukari
def requestSongsByTag(cbInfo, quantity, tag):
    agent = Agent(reactor)
    url = 'http://vocadb.net/api/songs?query=&onlyWithPvs=true&pvServices=Youtube&preferAccurateMatches=false&nameMatchMode=Partial&tag=%s&getTotalCount=true&maxResults=0' % tag
    url = url.encode('utf8')
    clog.warning('(requestSongsByTag) %s' % url, syst)
    d = agent.request('GET', url, Headers({'User-Agent': [UserAgentVdb]}))
    d.addCallback(readBody)
    d.addCallbacks(processVdbJson, apiError)
    d.addCallbacks(
        partial(requestSongByTagCountCallback, cbInfo, quantity, tag))
    return d
示例#14
0
 def flagOrDelete(self, res, cy, mType, mId, title, uid):
     if res == 'EmbedOk':
         clog.info('%s EmbedOk' % title, syst)
         database.unflagMedia(0b1, mType, mId)
     elif res in ('Status503', 'Status403', 'Status404', 'NoEmbed',
                  'NoVid'):
         clog.warning('%s: %s' % (title, res), syst)
         cy.doDeleteMedia(uid)
         cy.uncache(mId)
         msg = 'Removing non-playable media %s' % title
         database.flagMedia(0b1, mType, mId)
         cy.sendCyWhisper(msg)
示例#15
0
文件: vdbapi.py 项目: zig-for/Yukari
def requestApiBySongId(res, songId, timeNow):
    """ Request video information from VocaDb API v2
    and save to the Song table """
    agent = Agent(reactor)
    url = 'http://vocadb.net/api/songs/%s?' % songId
    url += '&fields=artists,names&lang=romaji'
    clog.warning('(requestApiBySongId) %s' % url, syst)
    d = agent.request('GET', url, Headers({'User-Agent': [UserAgentVdb]}))
    d.addCallback(readBody)
    d.addCallbacks(processVdbJsonForSongId, apiError)
    d.addCallback(database.insertSong, timeNow)
    return d
示例#16
0
文件: poke.py 项目: d-dd/Yukari
 def yukariPoke(self, cy, username):
     # check if IRC messages were sent during wait time
     if not self.lastChatAtTimer == cy.factory.handle.lastIrcChat:
         clog.warning('(yukariPoke) Cancelling poke because there was irc'
                      ' chat activity', syst)
         return
     cy.sendCyWhisper('Yukari pokes %s...!' % username, modflair=True, 
                      toIrc=False)
     self.lastPoke = time.time()
     self.waitingPokeUser = username
     self.waitingPokeReply = time.time()
     self.stopTimer(cy)
示例#17
0
 def gotVocaInfo(self, result, cy, mType, mId):
     """ Called when requestSongByPv returns
     This is in case a setCurrent has already happened, while
     a song data is being requested. This resends the js with
     vocadb added """
     i = cy.getIndexFromUid(cy.nowPlayingUid)
     cType = cy.playlist[i]['media']['type']
     cId = cy.playlist[i]['media']['id']
     clog.warning(
         'gotVocaInfo: c:%s, %s m:%s,%s' % (cType, cId, mType, mId), syst)
     if (cType, cId) == (mType, mId):
         d = self._loadVocaDb(None, mType, mId)
         d.addCallback(self.emitJs, cy)
示例#18
0
 def doneCleanup(self, protocol):
     """ Fires the done deferred, which unpauses the shutdown sequence """
     # If the application is stuck after Ctrl+C due to a bug,
     # use telnet(manhole) to manually fire the 'done' deferred.
     clog.warning('(doneCleanup) CLEANUP FROM %s' % protocol, sys)
     if protocol == 'irc':
         self.irc = None
         clog.info('(doneCleanup) Done shutting down IRC.', sys)
     elif protocol == 'cy':
         self.cy = None
         clog.info('(doneCleanup) Done shutting down Cy.', sys)
     if not self.irc and not self.cy:
         self.done.callback(None)
示例#19
0
文件: poke.py 项目: zig-for/Yukari
 def yukariPoke(self, cy, username):
     # check if IRC messages were sent during wait time
     if not self.lastChatAtTimer == cy.factory.handle.lastIrcChat:
         clog.warning(
             '(yukariPoke) Cancelling poke because there was irc'
             ' chat activity', syst)
         return
     cy.sendCyWhisper('Yukari pokes %s...!' % username,
                      modflair=True,
                      toIrc=False)
     self.lastPoke = time.time()
     self.waitingPokeUser = username
     self.waitingPokeReply = time.time()
     self.stopTimer(cy)
示例#20
0
    def addQueue(self, msg):
        if not self.underSpam and self.bucketToken != 0:
            self.chatQueue.append(msg)
            self.popQueue()
        elif self.underSpam:
            clog.warning('(addQueue) chat is throttled', sys)
            return

        elif self.bucketToken == 0:
            clog.warning('(addQueue) blocking messages from CyTube', sys)
            msg = '[Hit throttle: Dropping messages %s.]'
            self.say(self.channelName, msg % 'from Cytube')
            self.factory.handle.sendToCy(msg % 'to IRC', modflair=True)
            self.underSpam = True
示例#21
0
    def _addQueue(self, msg, action):
        if not self.underSpam and self.bucketToken != 0:
            self.chatQueue.append((msg, action))
            self.popQueue()
        elif self.underSpam:
            clog.info('(_addQueue) chat is throttled', sys)
            return

        elif self.bucketToken == 0:
            clog.warning('(_addQueue) blocking messages from CyTube', sys)
            msg = '[Hit throttle: Dropping messages %s.]'
            self.say(self.channelName, msg % 'from Cytube')
            self.factory.handle.sendToCy(msg % 'to IRC', modflair=True)
            self.underSpam = True
示例#22
0
文件: snssms.py 项目: zig-for/Yukari
 def dbQuerySubAttemptRes(self, result, cy, username, rank, number):
     if not result: #user not in table yet
         d = self.dbWriteSubAttempt(cy, username, rank)
         d.addCallback(self.subscribeSms, cy, username, rank, number)
         return d
     else:
         if result[0][0] > 3:
             clog.warning('Too many subscribe attempts by %s.' % username,
                     syst)
             # too many attempts
             cy.doSendChat('Request denied: Too many previous attempts.',
                     'pm', username)
         else:
             self.subscribeSms(None, cy, username, rank, number)
示例#23
0
文件: vdbapi.py 项目: d-dd/Yukari
def requestApiBySongId(res, songId, timeNow):
    """ Request video information from VocaDb API v2
    and save to the Song table """
    agent = Agent(reactor)
    args = {'fields': 'Artists,Names', 
            'lang': 'romaji'}
    url = 'https://vocadb.net/api/songs/{}?{}'.format(songId, 
                                                     urllib.urlencode(args))

    clog.warning('(requestApiBySongId) %s' % url, syst)
    d = agent.request('GET', url, Headers({'User-Agent':[UserAgentVdb]}))
    d.addCallback(readBody)
    d.addCallbacks(processVdbJsonForSongId, apiError)
    d.addCallback(database.insertSong, timeNow)
    return d
示例#24
0
文件: vdbapi.py 项目: zig-for/Yukari
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.warning('(processVdbJson) null from Vocadb', syst)
        return defer.succeed(0)

    return defer.succeed((pbody))
示例#25
0
文件: vdbapi.py 项目: d-dd/Yukari
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.warning('(processVdbJson) null from Vocadb', syst)
        return defer.succeed(0)

    return defer.succeed((pbody))
示例#26
0
文件: tacfile.py 项目: d-dd/Yukari
 def doneCleanup(self, protocol):
     """ Fires the done deferred, which unpauses the shutdown sequence """
     # If the application is stuck after Ctrl+C due to a bug,
     # use telnet(manhole) to manually fire the 'done' deferred.
     clog.warning('(doneCleanup) CLEANUP FROM %s' % protocol, syst)
     if protocol == 'irc': 
         self.irc = None
         clog.info('(doneCleanup) Done shutting down IRC.', syst)
     elif protocol == 'cy':
         self.cy = None
         clog.info('(doneCleanup) Done shutting down Cy.', syst)
     elif protocol == 'dc':
         self.dc = None
         clog.info('(doneCleanup) Done shutting down Discord.', syst)
     if not self.irc and not self.cy and not self.dc:
         self.done.callback(None)
示例#27
0
文件: vdbapi.py 项目: zig-for/Yukari
def requestApiByPv(mType, mId, timeNow):
    """ Request song information by Youtube or NicoNico Id,
    and save data to Song table """
    agent = Agent(reactor)
    if mType == 'yt':
        service = 'Youtube'
    else:
        service = 'NicoNicoDouga'
    url = 'http://vocadb.net/api/songs?pvId=%s&pvService=%s' % (mId, service)
    url += '&fields=artists,names&lang=romaji'
    clog.warning('(requestApiByPv) %s' % url, syst)
    dd = agent.request('GET', str(url), Headers({'User-Agent':
                                                 [UserAgentVdb]}))
    dd.addCallback(readBody)
    dd.addCallbacks(processVdbJsonForSongId, apiError)
    dd.addCallback(database.insertSong, timeNow)
    return dd
示例#28
0
 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)
示例#29
0
文件: vdbapi.py 项目: d-dd/Yukari
def requestSongsByTag(cbInfo, quantity, tag):
    agent = Agent(reactor)
    args = {'query': '',
            'onlyWithPvs': True,
            'pvServices': 'Youtube',
            'tagName': tag,
            'getTotalCount': True,
            'maxResults': 0,
            }

    url = 'https://vocadb.net/api/songs?{}'.format(urllib.urlencode(args))
    url = url.encode('utf8')
    clog.warning('(requestSongsByTag) %s' % url, syst)
    d = agent.request('GET', url, Headers({'User-Agent':[UserAgentVdb]}))
    d.addCallback(readBody)
    d.addCallbacks(processVdbJson, apiError)
    d.addCallbacks(partial(requestSongByTagCountCallback, cbInfo, quantity, tag))
    return d
示例#30
0
文件: reprint.py 项目: d-dd/Yukari
 def processEnded(self, reason):
     clog.warning('[processEnded] Process %s had ended' % self.pid, syst)
     index = self.output.find('DONE ')
     if index != -1:
         ytid = self.output[index+5:-1] #-1 to remove \n
         self.reprinter._add_done_video(self.cy, ytid)
         self.cy.reprint = True
     else:
         if self.output.find('This video is low resolution.') != -1:
             self.cy.doSendChat('[reprint] NND is currently in economy mode.'
                              ' Please try again another time.', toIrc=False)
             self.cy.reprint = True
             return
         # process failed to upload, check console
         msg = ('[reprint] Failed to upload video. $reprint funcionality'
                'has been disabled. Check the log for errors.')
         self.cy.doSendChat(msg, toIrc=False)
         self.cy.reprint = False
示例#31
0
文件: reprint.py 项目: d-dd/Yukari
 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)
示例#32
0
 def processEnded(self, reason):
     clog.warning('[processEnded] Process %s had ended' % self.pid, syst)
     index = self.output.find('DONE ')
     if index != -1:
         ytid = self.output[index + 5:-1]  #-1 to remove \n
         self.reprinter._add_done_video(self.cy, ytid)
         self.cy.reprint = True
     else:
         if self.output.find('This video is low resolution.') != -1:
             self.cy.doSendChat(
                 '[reprint] NND is currently in economy mode.'
                 ' Please try again another time.',
                 toIrc=False)
             self.cy.reprint = True
             return
         # process failed to upload, check console
         msg = ('[reprint] Failed to upload video. $reprint funcionality'
                'has been disabled. Check the log for errors.')
         self.cy.doSendChat(msg, toIrc=False)
         self.cy.reprint = False
示例#33
0
文件: ircClient.py 项目: d-dd/Yukari
 def privmsg(self, user, channel, msg):
     clog.warning('(privmsg) message from %s in %s' % (user, channel), sys)
     if channel == self.channelStatus:
         nick = user[:user.find('!')]
         self.sendLine('mode %s +b %s' % (channel, user))
         self.sendLine('KICK %s %s READ-ONLY!' % (channel, nick))
         return
     if channel != self.channelName:
         return
     # msg comes as str bytes
     try:
         msg = msg.decode('utf-8', 'replace')
     except(UnicodeDecodeError):
         clog.warning('Message not in utf8. Decoding using ISO-8859-1', sys)
         msg = msg.decode('iso-8859-1')
     #clog.error('isUnicode: %s' % isinstance(msg, unicode), sys)
     
     self.factory.handle.recIrcMsg(user, channel, msg)
     flag = 0
     self.logProcess(user, msg, flag)
示例#34
0
    def privmsg(self, user, channel, msg):
        clog.warning('(privmsg) message from %s in %s' % (user, channel), sys)
        if channel == self.channelStatus:
            nick = user[:user.find('!')]
            self.sendLine('mode %s +b %s' % (channel, user))
            self.sendLine('KICK %s %s READ-ONLY!' % (channel, nick))
            return
        if channel != self.channelName:
            return
        # msg comes as str bytes
        try:
            msg = msg.decode('utf-8', 'replace')
        except (UnicodeDecodeError):
            clog.warning('Message not in utf8. Decoding using ISO-8859-1', sys)
            msg = msg.decode('iso-8859-1')
        #clog.error('isUnicode: %s' % isinstance(msg, unicode), sys)

        self.factory.handle.recIrcMsg(user, channel, msg)
        flag = 0
        self.logProcess(user, msg, flag)
示例#35
0
文件: vdbapi.py 项目: d-dd/Yukari
def requestApiByPv(mType, mId, timeNow):
    """ Request song information by Youtube or NicoNico Id,
    and save data to Song table """
    agent = Agent(reactor)
    if mType == 'yt':
        service = 'Youtube'
    else:
        service = 'NicoNicoDouga'
    args = {'pvId': mId,
            # pvService singular here (not pvServices)
            'pvService': service,
            'fields': 'Artists,Names',
            'lang': 'romaji',
            }
    url = 'https://vocadb.net/api/songs?{}'.format(urllib.urlencode(args))
    clog.warning('(requestApiByPv) %s' % url, syst)
    dd = agent.request('GET', str(url), Headers({'User-Agent':[UserAgentVdb]}))
    dd.addCallback(readBody)
    dd.addCallbacks(processVdbJsonForSongId, apiError)
    dd.addCallback(database.insertSong, timeNow)
    return dd
示例#36
0
文件: vocadb.py 项目: d-dd/Yukari
 def _com_vocadb(self, cy, username, args, source):
     """
     Vocadb command
     $vocadb (no commands) - rerun full search
     $vocadb 0 - set as 'no match found'
     $vocadb {vocadb song id} - manually set vocadb to specific song
     """
     if not vdb or not cy.nowPlayingMedia:
         clog.warning('no nowPlayingMedia', syst)
         return
     mType = cy.nowPlayingMedia['type']
     mId = cy.nowPlayingMedia['id']
     if not args:
         d = self.processVocadb(None, mType, mId, cy.name.lower(), 
                                                             True, True)
         d.addCallback(self.emitJs, cy)
         return
     try:
         songId = int(args)
     except IndexError:
         clog.warning('(_com_vocadb) Index Error by %s' % username, syst)
         return
     except ValueError:
         clog.warning('(_com_vocadb) Value Error by %s' % username, syst)
         return
     userId = cy.userdict[username]['keyId']
     isReg = cy.checkRegistered(username)
     nameLower = username.lower()
     timeNow = getTime()
     d = vdbapi3.setVocadbBySongId(mType, mId, songId, nameLower, isReg)
     # method 4 = manual set
     #d.addCallback(self._loadVocaDb, mType, mId, username)
     d.addCallback(self.emitJs, cy)
示例#37
0
文件: vdbapi.py 项目: zig-for/Yukari
def requestPVByTagOffset(cbInfo, tag, offset):
    def localCb(res):
        try:
            pbody = json.loads(res[0])
        except (ValueError):
            return defer.fail(Exception('No video found'))

        if pbody.get('items') and pbody['items'][0]:
            for pv in pbody['items'][0]['pVs']:
                # TODO: soundcloud, too
                if pv[u'service'] == "Youtube":
                    return [['yt', pv['pvId']]]

    agent = Agent(reactor)
    url = 'http://vocadb.net/api/songs?query=&onlyWithPvs=true&pvServices=Youtube&preferAccurateMatches=false&nameMatchMode=Partial&tag=%s&getTotalCount=false&start=%i&fields=PVs&maxResults=1' % (
        tag, offset)
    url = url.encode('utf8')
    clog.warning('(requestSongByTagOffset) %s' % url, syst)
    d = agent.request('GET', url, Headers({'User-Agent': [UserAgentVdb]}))
    d.addCallback(readBody)
    d.addCallbacks(processVdbJsonForSongId, apiError)
    d.addCallback(localCb)
    return d
示例#38
0
文件: poke.py 项目: d-dd/Yukari
 def startPokeTimer(self, cy):
     """ Starts poke timer if only one user left (besides Yukari) in the
     channel and timer hasn't been run for past 24h. It will be cancelled on:
     -user join
     -user leave
     """
     self.stopTimer(cy)
     if ((time.time() - self.lastPoke < self.pokeInterval) or
      (len(cy.userdict) != 2)): 
         return
     username = None
     for name in cy.userdict.iterkeys():
         if name != cy.name:
             username = name
     if not username:
         clog.error('Error at startTimer. 2 users but no non-Yukari name',
                 syst)
         return
     from twisted.internet import reactor
     self.pokeTimer = reactor.callLater(self.pokeTime,
         self.yukariPoke, cy, username)
     cy.laters.append(self.pokeTimer)
     clog.warning('Started poke timer for %s!' % username, syst)
     self.lastChatAtTimer = cy.factory.handle.lastIrcChat
示例#39
0
文件: poke.py 项目: zig-for/Yukari
 def startPokeTimer(self, cy):
     """ Starts poke timer if only one user left (besides Yukari) in the
     channel and timer hasn't been run for past 24h. It will be cancelled on:
     -user join
     -user leave
     """
     self.stopTimer(cy)
     if ((time.time() - self.lastPoke < self.pokeInterval)
             or (len(cy.userdict) != 2)):
         return
     username = None
     for name in cy.userdict.iterkeys():
         if name != cy.name:
             username = name
     if not username:
         clog.error('Error at startTimer. 2 users but no non-Yukari name',
                    syst)
         return
     from twisted.internet import reactor
     self.pokeTimer = reactor.callLater(self.pokeTime, self.yukariPoke, cy,
                                        username)
     cy.laters.append(self.pokeTimer)
     clog.warning('Started poke timer for %s!' % username, syst)
     self.lastChatAtTimer = cy.factory.handle.lastIrcChat
示例#40
0
文件: vdbapi.py 项目: d-dd/Yukari
def processVdbJsonForSongId(body):
    clog.info('(processVdbJsonForSongId) Received reply from VocaDB', syst)
   # clog.debug('(processVdbJsonForSongId) %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.warning('(processVdbJsonForSongId) null from Vocadb', syst)
        return defer.succeed(0)
    
    songId = pbody.get('id')
    
    # Couldn't find songId, this might be a list of songs...so pick the first ;)
    if not songId:
        items = pbody.get('items')
        if items and items[0]:
            songId = items[0]['id']

    return defer.succeed((body, songId))
示例#41
0
文件: vdbapi.py 项目: zig-for/Yukari
def processVdbJsonForSongId(body):
    clog.info('(processVdbJsonForSongId) Received reply from VocaDB', syst)
    # clog.debug('(processVdbJsonForSongId) %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.warning('(processVdbJsonForSongId) null from Vocadb', syst)
        return defer.succeed(0)

    songId = pbody.get('id')

    # Couldn't find songId, this might be a list of songs...so pick the first ;)
    if not songId:
        items = pbody.get('items')
        if items and items[0]:
            songId = items[0]['id']

    return defer.succeed((body, songId))
示例#42
0
 def _com_vocadb(self, cy, username, args, source):
     if not vdb or not cy.nowPlayingMedia:
         clog.warning('no nowPlayingMedia', syst)
         return
     mType = cy.nowPlayingMedia['type']
     mId = cy.nowPlayingMedia['id']
     if args is None:
         d = database.getSongId(mType, mId)
         d.addCallback(self.checkVocadbCommand, cy, mType, mId)
         d.addCallback(self.emitJs, cy)
     try:
         songId = int(args)
     except IndexError:
         clog.warning('(_com_vocadb) Index Error by %s' % username, syst)
         return
     except ValueError:
         clog.warning('(_com_vocadb) Value Error by %s' % username, syst)
         return
     userId = cy.userdict[username]['keyId']
     timeNow = getTime()
     d = vdbapi.requestSongById(mType, mId, songId, userId, timeNow, 4)
     # method 4 = manual set
     d.addCallback(self._loadVocaDb, mType, mId)
     d.addCallback(self.emitJs, cy)
示例#43
0
 def _checkSupply(self, cy):
     """Check automedia length and add more media if running low."""
     remaining = len(self.automedia)
     clog.warning(str(self.automedia), syst)
     if remaining < 4:
         self._queueMore(cy, 6 - remaining)
示例#44
0
文件: vdbapi.py 项目: d-dd/Yukari
def errNoIdInDesc(res):
    clog.warning('errNoIdInDesc %s' % res, syst)
    return defer.succeed((1, 0))
示例#45
0
文件: ircClient.py 项目: d-dd/Yukari
 def setInitialNick(self):
     clog.warning('(setInitialNick) setting initial nickname', sys)
     if self.factory.handle.cy:
         self.setOnlineNick()
     else:
         self.setOfflineNick()
示例#46
0
def insertSong(res, lastUpdate):
    if res == 0:
        clog.warning('(insertSong) VocaDB returned null. Skipping.', sys)
        return defer.succeed([0])
    return dbpool.runInteraction(_insertSong, res, lastUpdate)
示例#47
0
文件: database.py 项目: d-dd/Yukari
def insertSong(res, lastUpdate):
    if res == 0:
        clog.warning('(insertSong) VocaDB returned null. Skipping.', sys)
        return defer.succeed([0])
    return dbpool.runInteraction(_insertSong, res, lastUpdate)
示例#48
0
文件: vdbapi.py 项目: zig-for/Yukari
def errNoIdInDesc(res):
    clog.warning('errNoIdInDesc %s' % res, syst)
    return defer.succeed((1, 0))
示例#49
0
文件: snssms.py 项目: zig-for/Yukari
 def connectionMade(self):
     self.pid = self.transport.pid
     clog.warning('Connected to Sms process!', syst)
示例#50
0
 def clientConnectionFailed(self, connector, reason):
     clog.warning('Connection Failed to IRC. Reason: %s' % reason, sys)
示例#51
0
 def clientConnectionLost(self, connector, reason):
     clog.warning('Connection Lost to IRC. Reason: %s' % reason, sys)
     self.handle.doneCleanup('irc')
示例#52
0
 def setInitialNick(self):
     clog.warning('(setInitialNick) setting initial nickname', sys)
     if self.factory.handle.cy:
         self.setOnlineNick()
     else:
         self.setOfflineNick()
示例#53
0
文件: snssms.py 项目: zig-for/Yukari
 def processEnded(self, reason):
     clog.warning('[processEnded] Process %s has ended' % self.pid, syst)
示例#54
0
文件: add.py 项目: d-dd/Yukari
 def _checkSupply(self, cy):
     """Check automedia length and add more media if running low."""
     remaining = len(self.automedia)
     clog.warning(str(self.automedia), syst)
     if remaining < 4:
         self._queueMore(cy, 6 - remaining)