Exemplo n.º 1
0
    def add_count(self, url, params, request, response):
        """ Add user action count of choosen AV.

        [Arguments]
            url[0] : string.
                AV ID.
            type   : string.
                Action type.
        """
        # API args
        av_id = url[0] if len(url) else None
        action_type = params.get_string('type', None)

        if not action_type or action_type not in [
                USER_ACTION_VIEW, USER_ACTION_DOWNLOAD, USER_ACTION_PLAY
        ]:
            raise RequestError(ERR_REQUEST_ARG, str_data=('type error.'))

        db_inst = PGClient(db='av')

        cur, rowcount = db_inst.query(table='video',
                                      condition=['id=%(id)s', {
                                          'id': av_id
                                      }])
        if not rowcount:
            raise RequestError(ERR_DB_NOT_FOUND)

        count, total = self._add_user_action(action_type=action_type,
                                             av_id=av_id,
                                             db_inst=db_inst)

        db_inst.commit()

        return Response(content={'count': count, 'total': total})
Exemplo n.º 2
0
    def delete_addon(self, url, params, request, response):
        """ delete addon file.

        [Arguments]
            url[0] : string.
                Addon version of file to remove.
        """
        # API args
        if len(url):
            version = url[0]
        else:
            raise RequestError(ERR_REQUEST_ARG, str_data=('version error.'))

        db_inst = PGClient(db='file', timeout=False)
        # check data exist
        cur, rowcount = db_inst.query(
            table='addons',
            fields=['version'],
            condition=[u'version=%(version)s', {
                'version': version
            }])
        if not rowcount:
            raise RequestError(ERR_REQUEST_ARG,
                               str_data=('data does not exist.'))

        db_inst.remove(
            table='addons',
            condition=[u'version=%(version)s', {
                'version': version
            }])
        db_inst.commit()

        return Response({'version': version})
Exemplo n.º 3
0
    def add_count(self, url, params, request, response):
        """ Add user action count of choosen dramas.

        [Arguments]
            url[0] : string.
                Drama ID.
            type   : string.
                Action type.
        """
        # API args
        drama_id = url[0] if len(url) else None
        action_type = params.get_string('type', None)

        if not action_type or action_type not in [USER_ACTION_VIEW, USER_ACTION_DOWNLOAD, USER_ACTION_PLAY]:
            raise RequestError(ERR_REQUEST_ARG, str_data=('type error.'))

        db_inst = PGClient()

        cur, rowcount = db_inst.query(table='drama', condition=['id=%(id)s', {'id': drama_id}])
        if not rowcount:
            raise RequestError(ERR_DB_NOT_FOUND)
   
        count, total = self._add_user_action(action_type=action_type, drama_id=drama_id, db_inst=db_inst)

        db_inst.commit()

        return Response(content={
            'count': count,
            'total': total
        })
Exemplo n.º 4
0
    def update_latest_movies(self, url, params, request, response):
        """ Update latest movies.

        [Arguments]
            imdbid_list: list
                The imdbid list to update latest table.
        [Return]
            rowcount: int
                The row count of 'movie_latest'.
        """
        imdbid_list = params.get_list('imdbid_list', None)
        # check argument 'imdbid_list'
        if not imdbid_list:
            raise RequestError(ERR_REQUEST_ARG, str_data=("argument 'imdbid_list' is need.",))

        values = ''
        for data in imdbid_list:
            # check imdbid pattern
            reslut = re.match('tt\d{7}', data[0])
            if reslut is None:
                raise RequestError(ERR_REQUEST_ARG, str_data=('imdbid_list(%s) is not imdbid format.' % data[0],))
            values += "('%s', '%s')," % (data[0], data[1])
        values = values[:-1]

        # insert db
        db_inst = PGClient()
        db_inst.execute('truncate table movie_latest')
        db_inst.execute('insert into movie_latest values %s' % values)
        db_inst.commit()
        cur = db_inst.execute('select count(*) from movie_latest')
        rowcount = cur.fetchone()[0]

        return Response(model_data={'rowcount': rowcount})
Exemplo n.º 5
0
    def delete_addon(self, url, params, request, response):
        """ delete addon file.

        [Arguments]
            url[0] : string.
                Addon version of file to remove.
        """
        # API args
        if len(url):
            version = url[0]
        else:
            raise RequestError(ERR_REQUEST_ARG, str_data=('version error.'))

        db_inst = PGClient(db='file', timeout=False)
        # check data exist
        cur, rowcount = db_inst.query(
            table='addons', fields=['version'], condition=[u'version=%(version)s', {'version': version}]
        )
        if not rowcount:
            raise RequestError(ERR_REQUEST_ARG, str_data=('data does not exist.'))

        db_inst.remove(table='addons', condition=[u'version=%(version)s', {'version': version}])
        db_inst.commit()

        return Response({
            'version': version
        })
Exemplo n.º 6
0
 def run(self):
     db_inst = PGClient(db=self.db, timeout=False)
     try:
         db_inst.execute(self.sqlcmd)
         db_inst.commit()
         self.done = True  # task done
     except Exception as e:
         self.error = True
         self.error_message = str(e)
         log.send(LOG_ERROR, str(e), traceback=True)
Exemplo n.º 7
0
    def add_count(self, url, params, request, response):
        """ Add user action count of choosen karaoke.

        [Arguments]
            url[0] : string.
                Karaoke ID.
            type   : string.
                Action type.
        """
        # API args
        karaoke_id = url[0] if len(url) else None
        id_list = params.get_list('ids', [])
        action_type = params.get_string('type', None)

        if not action_type or action_type not in [USER_ACTION_VIEW, USER_ACTION_DOWNLOAD, USER_ACTION_PLAY]:
            raise RequestError(ERR_REQUEST_ARG, str_data=('type error.'))

        if karaoke_id:
            id_list = [karaoke_id]
        elif not id_list:
            raise RequestError(ERR_REQUEST_ARG, str_data=('id_list error.'))

        db_inst = PGClient(db='karaoke')

        cur, rowcount = db_inst.query(table='songs', condition=['keymd5 IN %(ids)s', {'ids': tuple(id_list)}])
        if rowcount != len(id_list):
            raise RequestError(ERR_DB_NOT_FOUND)
   
        resp = Response()

        for ID in id_list:
            count, total = self._add_user_action(action_type=action_type, karaoke_id=ID, db_inst=db_inst)
            resp[ID] = {
                'count': count,
                'total': total
            }

        db_inst.commit()

        return resp.pop(karaoke_id) if karaoke_id else resp
Exemplo n.º 8
0
    def update_latest_movies(self, url, params, request, response):
        """ Update latest movies.

        [Arguments]
            imdbid_list: list
                The imdbid list to update latest table.
        [Return]
            rowcount: int
                The row count of 'movie_latest'.
        """
        imdbid_list = params.get_list('imdbid_list', None)
        # check argument 'imdbid_list'
        if not imdbid_list:
            raise RequestError(ERR_REQUEST_ARG,
                               str_data=("argument 'imdbid_list' is need.", ))

        values = ''
        for data in imdbid_list:
            # check imdbid pattern
            reslut = re.match('tt\d{7}', data[0])
            if reslut is None:
                raise RequestError(
                    ERR_REQUEST_ARG,
                    str_data=('imdbid_list(%s) is not imdbid format.' %
                              data[0], ))
            values += "('%s', '%s')," % (data[0], data[1])
        values = values[:-1]

        # insert db
        db_inst = PGClient()
        db_inst.execute('truncate table movie_latest')
        db_inst.execute('insert into movie_latest values %s' % values)
        db_inst.commit()
        cur = db_inst.execute('select count(*) from movie_latest')
        rowcount = cur.fetchone()[0]

        return Response(model_data={'rowcount': rowcount})
Exemplo n.º 9
0
    def upload_addon(self, url, params, request, response):
        """ Upload addon file.

        [Arguments]
            url[0] : string.
                Addon version of this file.
            md5sum : string. (opt)
                md5sum of this file to check data is complete.
        """
        # API args
        if len(url):
            version = url[0]
        else:
            raise RequestError(ERR_REQUEST_ARG, str_data=('version error.'))

        if not params.has_key('file'):
            raise RequestError(ERR_REQUEST_ARG, str_data=('file error.'))

        file_md5sum = params.get_string('md5sum', None)

        # check data exist
        db_inst = PGClient(db='file', timeout=False)
        cur, rowcount = db_inst.query(
            table='addons',
            fields=['version'],
            condition=[u'version=%(version)s', {
                'version': version
            }])
        if rowcount:
            raise RequestError(ERR_REQUEST_ARG, str_data=('data existed.'))

        # handle updating file
        upload_file = params['file']
        tmp_file_path = '%s/%s' % (TMP_PATH, upload_file.filename)

        try:
            # save file
            md5 = hashlib.md5()
            with open(tmp_file_path, mode='wb') as fp:
                while True:
                    data = upload_file.file.read(8192)
                    if data:
                        fp.write(data)
                        md5.update(data)
                    else:
                        break

            # compare md5sum
            md5sum = md5.hexdigest()
            if file_md5sum and md5sum != file_md5sum:
                raise RequestError(ERR_REQUEST_ARG,
                                   str_data=('md5sum check error.'))

            # insert data to db
            with open(tmp_file_path, mode='rb') as f:
                db_inst.insert(table='addons',
                               data={
                                   'version': version,
                                   'name': upload_file.filename,
                                   'data': Binary(f.read()),
                                   'md5sum': md5sum,
                                   'udate': datetime.utcnow().isoformat()
                               })

            # remove redundant data
            addons, rowcount = db_inst.query(table='addons',
                                             fields=['version'],
                                             ret_type='all',
                                             else_sql='ORDER BY version DESC')
            if rowcount > MAX_NUM_ADDONS:
                versions_to_remove = [
                    addons[-1 * index]['version']
                    for index in xrange(1, rowcount - MAX_NUM_ADDONS + 1)
                ]
                db_inst.remove(table='addons',
                               condition=[
                                   'version IN %(versions)s', {
                                       'versions': tuple(versions_to_remove)
                                   }
                               ])

            db_inst.commit()

            return Response({'version': version, 'md5sum': md5sum})
        finally:
            os.remove(tmp_file_path)
Exemplo n.º 10
0
    def upload_addon(self, url, params, request, response):
        """ Upload addon file.

        [Arguments]
            url[0] : string.
                Addon version of this file.
            md5sum : string. (opt)
                md5sum of this file to check data is complete.
        """
        # API args
        if len(url):
            version = url[0]
        else:
            raise RequestError(ERR_REQUEST_ARG, str_data=('version error.'))

        if not params.has_key('file'):
            raise RequestError(ERR_REQUEST_ARG, str_data=('file error.'))

        file_md5sum = params.get_string('md5sum', None)

        # check data exist
        db_inst = PGClient(db='file', timeout=False)
        cur, rowcount = db_inst.query(
            table='addons', fields=['version'], condition=[u'version=%(version)s', {'version': version}]
        )
        if rowcount:
            raise RequestError(ERR_REQUEST_ARG, str_data=('data existed.'))

        # handle updating file
        upload_file = params['file']
        tmp_file_path = '%s/%s' % (TMP_PATH, upload_file.filename)

        try:
            # save file
            md5 = hashlib.md5()
            with open(tmp_file_path, mode='wb') as fp:
                while True:
                    data = upload_file.file.read(8192)
                    if data:
                        fp.write(data)
                        md5.update(data)
                    else:
                        break

            # compare md5sum
            md5sum = md5.hexdigest()
            if file_md5sum and md5sum != file_md5sum:
                raise RequestError(ERR_REQUEST_ARG, str_data=('md5sum check error.'))

            # insert data to db
            with open(tmp_file_path, mode='rb') as f:
                db_inst.insert(table='addons', data={
                    'version': version,
                    'name': upload_file.filename,
                    'data': Binary(f.read()),
                    'md5sum': md5sum,
                    'udate': datetime.utcnow().isoformat()
                })

            # remove redundant data
            addons, rowcount = db_inst.query(
                table='addons', fields=['version'], ret_type='all', else_sql='ORDER BY version DESC'
            )
            if rowcount > MAX_NUM_ADDONS:
                versions_to_remove = [addons[-1*index]['version'] for index in xrange(1, rowcount-MAX_NUM_ADDONS+1)]
                db_inst.remove(
                    table='addons', condition=['version IN %(versions)s', {'versions': tuple(versions_to_remove)}]
                )

            db_inst.commit()

            return Response({
                'version': version,
                'md5sum': md5sum
            })
        finally:
            os.remove(tmp_file_path)