Beispiel #1
0
 def plrc(server: PyWebHost, request: Request, content):
     id = request.query['id'][0]
     detail_dict = pyncm.apis.track.GetTrackDetail(id)['songs'][0]
     track = pyncm.utils.helper.TrackHelper(detail_dict)
     lyrics_dict = pyncm.apis.track.GetTrackLyrics(id)
     lrc = {'romalrc': None, 'lrc': None, 'tlyric': None}
     for index in lrc:
         lrc[index] = pyncm.utils.lrcparser.LrcParser(
             lyrics_dict[index]['lyric'])
     ticks = lrc['lrc'].lyrics_sorted.keys()
     content = ''
     content += (
         f'<head><link rel="stylesheet" href="../css/printableLyrics.css"><title>{track.Title}</title></head>'
     )
     content += (f'<h1>{track.TrackName}</h1>')
     content += (f'<h2>{track.AlbumName} / {track.TrackPublishTime}</h2>')
     content += (f'<h2>{" / ".join(track.Artists)}</h2>')
     for tick in ticks:
         content += ('<div class="block">')
         for index in lrc:
             if not lrc[index].lyrics: continue
             ts, lines, lno = lrc[index].Find(lrc[index].lyrics_sorted,
                                              tick)
             if tick >= ts:
                 tss, line = lines[-1]
                 content += (
                     f'    <p class={index} ts="{tss}">{line.strip()}</p>')
         content += ('</div>')
     logging.info('static/printableLyrics : %s complete' % id)
     request.send_response(200)
     request.send_header('Content-Type', 'text/html;charset=UTF-8')
     return content
Beispiel #2
0
 def _stats_requests(self, request: Request, content):
     '''accumulates total requests'''
     self.setdefault('count', 0)
     if self['count'] < 2:
         self['count'] = 2
     request.send_response(200)
     return {
         'self': self.local_request_stack.to_list(),
         'global': self.global_request_stack.to_list()
     }
Beispiel #3
0
 def _stats_server(self, request: Request, content):
     '''server hoster nickname'''
     self.setdefault('count', 0)
     if self['count'] < 2:
         self['count'] = 2
     if GetCurrentSession().login_info['success']:
         request.send_response(200)
         return GetCurrentSession().login_info['content']['profile']
     else:
         request.send_response(404)
         return {}
Beispiel #4
0
 def _file_get(self, request: Request, content):
     key = request.query['key'][0]
     if not key in files.keys():
         return request.send_error(HTTPStatus.NOT_FOUND,
                                   'Resource not found')
     file: File = files[key]
     self_name = self.get('name')
     print(self_name or self.request.useragent_string + ' -- Anonymous --',
           ': Downloading', file.file_name)
     file.downloader.add(self_name)
     while not file.bytes_written >= file.file_size:
         time.sleep(0.1)  # wait till upload finishes
     request.send_response(200)
     request.send_header('Content-Disposition',
                         'filename="%s"' % file.file_name)
     if 'thumb' in request.query:
         # fetching thumbnails for images
         from PIL import Image
         temp_img_path = FileSession.temp_img_path_format % file.temp_file_path
         if not isfile(temp_img_path):
             # creating one if object does not exist
             try:
                 thumb: Image.Image = Image.open(file.temp_file_path)
                 thumb.thumbnail((128, 128))
                 thumb.save(temp_img_path, "JPEG")
             except:
                 # failed to parse
                 return WriteContentToRequest(request,
                                              file.temp_file_path,
                                              partial_acknowledge=True,
                                              mime_type=file.file_type)
         return WriteContentToRequest(request,
                                      temp_img_path,
                                      mime_type='image/jpg')
         # writing temp image
     else:
         if not self_name in file.downloader:
             # boardcast download event
             boardcast(
                 Chat.srv_msg(msg={
                     'file': file.dict(),
                     'user': self_name
                 },
                              type='filedownload'))
         return WriteContentToRequest(request,
                                      file.temp_file_path,
                                      partial_acknowledge=True,
                                      mime_type=file.file_type)
Beispiel #5
0
def index(initator, request: Request, content):
    real = 'html' + request.path
    if os.path.isfile(real):
        WriteContentToRequest(request,
                              real,
                              mime_type=mimetypes.guess_type(real)[0])
    else:
        # request.send_error(404)
        request.send_response(404)
        request.send_header('Content-Length', 0)
        request.end_headers()
Beispiel #6
0
        def routeCloudmusicApis(self, request: Request, content):
            self.setdefault('count', 0)
            self['count'] = self['count'] + 1
            if self['count'] < 2:
                return request.send_response(503)
            path = list(
                filter(lambda x: x and x != 'pyncm', request.path.split('/')))
            base, target = path
            if not base in filter(lambda x: x.islower() and not '_' in x,
                                  dir(pyncm.apis)):
                return request.send_error(404,
                                          'base method %s not found' % base)
            if base in {'user', 'login'}:
                return request.send_error(403,
                                          'base method %s not allowed' % base)
            base = getattr(pyncm.apis, base)
            if not target in filter(lambda x: 'Get' in x or 'Set' in x,
                                    dir(base)):
                return request.send_error(
                    404, 'target method %s not found' % target)
            if 'Set' in target:
                return request.send_error(403, 'cannot perfrom "Set" calls')
            query = {
                k: v if not len(v) == 1 else v[0]
                for k, v in request.query.items()
            }
            response = getattr(base, target)(**query)
            self.logger.info('[%s #%d] %s - %s' %
                             (self.session_id, self['count'], target, query))
            if target in {'GetTrackAudio'} and response['code'] == 200:
                ids = [e['id'] for e in response['data']]
                self.local_request_stack.extend(ids)
                self.global_request_stack.extend(ids)

            request.send_response(200)
            return response
Beispiel #7
0
def index(initator, request: Request, content):
    request.send_response(200)
    paths = ['<a href=%s>%s</a></br>' % (path, path) for path in server.paths]
    return TEMPLATE % ''.join(paths)
Beispiel #8
0
 def _session_test_(initiator, request: Request, content):
     request.send_response(200)
     return self.session_id
Beispiel #9
0
 def _file_view(self, request: Request, content):
     key = request.query['key'][0]
     if not key in files.keys():
         return request.send_error(HTTPStatus.NOT_FOUND,
                                   'Resource not found')
     return files[key].dict()
Beispiel #10
0
 def onCreate(self, request: Request, content):
     if not self.session_id: self.set_session_id(path='/')
     request.send_response(200)
     request.send_header('Access-Control-Allow-Origin', '*')