示例#1
0
    def update_server(self, data):
        if data.get('name'):
            self.name = data.get('name')
        if data.get('ip'):
            self.ip = data.get('ip')
        if data.get('port'):
            self.port = data.get('port')
        if data.get('password'):
            self.password = data.get('password')
        if data.get('monitor_chat'):
            self.monitor_chat = data.get('monitor_chat')
        if 'monitor_chat_channel' in data.keys():
            self.monitor_chat_channel = Channel.get_channel_by_id(
                data.get('monitor_chat_channel'))
        if 'alerts_channel' in data.keys():
            self.alerts_channel = Channel.get_channel_by_id(
                data.get('alerts_channel'))
        if 'info_channel' in data.keys():
            self.alerts_channel = Channel.get_channel_by_id(
                data.get('info_channel'))
        if 'info_message' in data.keys():
            self.info_message = Message.get_message_by_id(
                data.get('info_message'))
        if 'settings_message' in data.keys():
            self.settings_message = Message.get_message_by_id(
                data.get('settings_message'))

        self.save()
        return create_success_response(self,
                                       status.HTTP_202_ACCEPTED,
                                       many=False)
示例#2
0
    def test_saving_new_channel(self):
        channel = Channel(
            title="Channel Title",
            url="https://www.youtube.com/channel/UCsn8UgBuRxGGqKmrAy5d3gA",
        )
        channel.save()

        saved_channels = Channel.objects.all()
        self.assertEqual(saved_channels.count(), 1)
    def handle(self, *args, **options):
        """Perform the operations of importcategories command."""
        channel_ref = Channel.generate_reference(options['channel'])
        channel, created = Channel.objects.get_or_create(
            reference=channel_ref, defaults={'name': options['channel']})

        if not created:
            Category.objects.filter(channel=channel).delete()

        reader = csv.DictReader(options['csv'])
        for row in reader:
            full_path = [x.strip() for x in row['Category'].split('/')]
            ancestors = full_path[0:-1]
            current = full_path[-1]

            parent, error = self.validate_ancestors(channel_ref, ancestors)
            if error:
                raise CommandError('Unable to process "{:s}": {:s}'.format(row[
                    'Category'], error))

            category_ref = Category.generate_reference(
                current, [channel_ref] + ancestors)
            Category.objects.create(
                reference=category_ref,
                name=current,
                channel=channel,
                parent=parent)
示例#4
0
	def parseIPTV(self, sds):
		lcnCount = 0
		for chXML in sds.getroot().findall("BroadcastDiscovery/ServiceList/SingleService"):
			try:
				ch = {}
				ch['xmltvID'] 	= int(chXML.attrib['id'])
				ch['chanType']	= chXML.attrib['type']
				
				mcast 		= chXML.find('ServiceLocation/IPMulticastAddress')
				ch['tune'] 	= "udp://%s:%s" % (mcast.get('Address'), mcast.get('Port'))
				ch['name'] 	= chXML.find('TextualIdentifier').get('ServiceName')
				ch['mpaa']	= chXML.find('Rating')
				if not ch['mpaa']:
					ch['mpaa'] = 'G' # by default - general audiences
				else:
					ch['mpaa'] = ch['mpaa'].get('value')
				
			except Exception as e:
				self.stderr.write("*** Failed to parse %s reason %s" % (ET.tostring(chXML), e))
				continue
			
			lcnCount += 1
			# we don't duplicate records
			if Channel.objects.filter(xmltvID=ch['xmltvID']).count() > 0:
				self.stderr.write(" Channel XMLTV ID=%d already in database, skipping\n" % ch['xmltvID'])
				continue
			
			chanDB = Channel(name		= ch['name'],
						xmltvID		= ch['xmltvID'],
						tune		= ch['tune'],
						chanType	= ch['chanType'],
						mpaa		= ch['mpaa'],
						enabled		= True,
						lcn			= lcnCount,
						mode		= u'IPTV',
						mux			= None
						)
			try:
				chanDB.save()
			except IntegrityError as e:
				print self.stderr.write(u"*** Failed to save channel [%d]%s, reason %s\n" % (chanDB.xmltvID, chanDB.name, e.__unicode__()))
				continue
			
			self.stdout.write(u"added [%d] \n" % chanDB.xmltvID)
			
示例#5
0
def resetChannelList(hdid, channelList):
    device = Device.objects.get(hdid=hdid)

    Channel.objects.filter(device=device).delete()

    current_channel = ''

    channel_pattern = re.compile('SCANNING.*us-cable:(\d+)')
    program_pattern = re.compile('PROGRAM\s(\d+):\s(?![0])(.*)')

    for line in channelList:
        m = channel_pattern.match(line)
        if m:
            current_channel = m.group(1)
        else:
            m = program_pattern.match(line)
            if m:
                c = Channel(device=device, channel=int(current_channel), program=int(m.group(1)), desc=m.group(2))
                c.save()
示例#6
0
def resetChannelList(hdid, channelList):
    device = Device.objects.get(hdid=hdid)

    Channel.objects.filter(device=device).delete()

    current_channel = ''

    channel_pattern = re.compile('SCANNING.*us-cable:(\d+)')
    program_pattern = re.compile('PROGRAM\s(\d+):\s(?![0])(.*)')

    for line in channelList:
        m = channel_pattern.match(line)
        if m:
            current_channel = m.group(1)
        else:
            m = program_pattern.match(line)
            if m:
                c = Channel(device=device,
                            channel=int(current_channel),
                            program=int(m.group(1)),
                            desc=m.group(2))
                c.save()
示例#7
0
def import_file(channel_name, file):
    '''
    Import csv file to db.
    '''
    with open(file) as f:
        reader = csv.reader(f)
        try:
            channel = Channel.objects.get(name=channel_name)
        except Channel.DoesNotExist:
            channel = Channel(name=channel_name)
            channel.save()
        for row in reader:
            if row[0] != 'Category':
                categories = row[0].split(' / ')
                i = 0
                category_objs = []
                while i < len(categories):
                    try:
                        if i == 0:
                            channel_category = ChannelCategory.objects.get(
                                name=categories[i],
                                channel=channel,
                                parent_category=None)
                        else:
                            channel_category = ChannelCategory.objects.get(
                                name=categories[i],
                                channel=channel,
                                parent_category=category_objs[i - 1])

                    except ChannelCategory.DoesNotExist:
                        channel_category = ChannelCategory()
                        channel_category.name = categories[i]
                        channel_category.channel = channel
                    if i != 0:
                        channel_category.parent_category = category_objs[i - 1]
                    channel_category.save()
                    category_objs.append(channel_category)
                    i += 1
示例#8
0
    def add_new_request(cls, guild_id, data):
        author_id = data.get('author')
        message_id = data.get('message')
        channel_id = data.get('channel')
        content = data.get('content')
        if not (guild_id and author_id and message_id and channel_id
                and content):
            return create_error_response(
                "One or more of the required fields are missing.",
                status=status.HTTP_400_BAD_REQUEST)
        guild = Guild.get_guild_by_id(guild_id)
        if not isinstance(guild, Guild):
            return create_error_response('Guild Does Not Exist',
                                         status=status.HTTP_404_NOT_FOUND)
        author = User.get_user_by_id(author_id)
        if not isinstance(author, User):
            return create_error_response('Author Does Not Exist',
                                         status=status.HTTP_404_NOT_FOUND)
        message = Message.get_message_by_id(message_id)
        if not isinstance(message, Message):
            return create_error_response('Message Does Not Exist',
                                         status=status.HTTP_404_NOT_FOUND)
        channel = Channel.get_channel_by_id(guild_id, channel_id)
        if not isinstance(channel, Channel):
            return create_error_response('Channel Does Not Exist',
                                         status=status.HTTP_404_NOT_FOUND)

        print('test')

        request = cls(guild=guild,
                      author=author,
                      message=message,
                      channel=channel,
                      content=content)
        request.save()
        return create_request_success_response(request,
                                               status.HTTP_201_CREATED,
                                               many=False)
示例#9
0
 def writeToDataBase(self):
     ch = Channel(name=self.title,
                  country=self.country,
                  subscriberCount=self.subscriberCount)
     ch.save()
示例#10
0
	def parseHybrid(self, sds):
		xmltvCounter = 5000
		for muxML in sds.getroot().findall("Multiplexer"):
			# create a mux if doesn't exist
			try:
				mux = DvbMux.objects.get(fec_hp = muxML.attrib['fec_hp'],
										 fec_lp = muxML.attrib['fec_lp'],
										 freq	= int(muxML.attrib['freq']),
										 modulation = muxML.attrib['modulation'], 
										 symbolRate = int(muxML.attrib['symbol_rate']))
			except ObjectDoesNotExist:
				mux = DvbMux(fec_hp = muxML.attrib['fec_hp'],
							 fec_lp = muxML.attrib['fec_lp'],
							 freq	= int(muxML.attrib['freq']),
							 modulation = muxML.attrib['modulation'], 
							 symbolRate = int(muxML.attrib['symbol_rate']))
				mux.save()
			
			# populate mux with channels
			for chML in muxML.findall("Service"):
				xmltvML = chML.find("XMLTV"); 
				if xmltvML.attrib['id'] == '--':
					self.stderr.write("* Warn: auto-assign XMLTV ID %d to %s \n"% (xmltvCounter, chML.find('Name').attrib['value']))
					xmltvID = xmltvCounter
					xmltvCounter += 1
				else:	
					xmltvID = int(xmltvML.attrib['id']); 
				chML.remove(xmltvML)
				try:
					chan = Channel.objects.get(xmltvID=xmltvID)
				except ObjectDoesNotExist:
					chan = Channel()
					chan.xmltvID = xmltvID
				
				nameML 	= chML.find('Name'); chan.name = nameML.attrib['value']; chML.remove(nameML)
				lcnML 	= chML.find('LCN'); chan.lcn = int(lcnML.attrib['value']); chML.remove(lcnML)
				rateML 	= chML.find("Rating")
				if rateML != None:
					chan.mpaa = rateML.attrib['value']
					chML.remove(rateML)
				else:
					chan.mpaa = u'G'
				
				chan.tune = ET.tostring(chML, encoding='utf-8')
				chan.mux  = mux
				chan.mode = u'DVB'
				chan.chanType = chML.attrib['type']
				try :
					chan.save()
				except Exception as e:
					self.stderr.write("Failed to save channel %s, reason %s\n" % (chan, e))
示例#11
0
    def add_new_message(cls, data):
        id = data.get('id')
        if id and cls.get_message_by_id(id):
            return create_error_response("Message Already Exists",
                                         status=status.HTTP_409_CONFLICT)
        author_id = data.get('author')
        guild_id = data.get('guild')
        channel_id = data.get('channel')
        created_at = data.get('created_at')
        content = data.get('content')
        tagged_everyone = data.get('tagged_everyone')
        if not (id and author_id and guild_id and channel_id and created_at and
                (tagged_everyone is not None)):
            return create_error_response(
                "One or more required fields are missing.",
                status=status.HTTP_400_BAD_REQUEST)
        author = User.get_user_by_id(author_id)
        if not isinstance(author, User):
            return create_error_response("Author Does Not Exist",
                                         status=status.HTTP_404_NOT_FOUND)
        guild = Guild.get_guild_by_id(guild_id)
        if not isinstance(guild, Guild):
            return create_error_response("Guild Does Not Exist",
                                         status=status.HTTP_404_NOT_FOUND)
        channel = Channel.get_channel_by_id(guild_id, channel_id)
        if not isinstance(channel, Channel):
            return create_error_response("Channel Does Not Exist",
                                         status=status.HTTP_404_NOT_FOUND)
        created_at = datetime.fromtimestamp(created_at, tz=timezone.utc)

        message = cls(id=id,
                      author=author,
                      guild=guild,
                      channel=channel,
                      created_at=created_at,
                      tagged_everyone=tagged_everyone or False,
                      content=content or '',
                      embeds=data.get('embeds') or [])
        message.save()
        if data.get('tagged_users'):
            tagged_users = data.get('tagged_users')
            for user_id in tagged_users:
                user = User.get_user_by_id(user_id)
                if user:
                    message.tagged_users.add(user)
        if data.get('tagged_roles'):
            tagged_roles = data.get('tagged_roles')
            for role_id in tagged_roles:
                role = Role.get_role_by_id(guild_id, role_id)
                if role:
                    message.tagged_roles.add(role)
        if data.get('tagged_channels'):
            tagged_channels = data.get('tagged_channels')
            for channel_id in tagged_channels:
                channel = Channel.get_channel_by_id(guild_id, channel_id)
                if channel:
                    message.tagged_channels.add(channel)

        return create_success_response(message,
                                       status.HTTP_201_CREATED,
                                       many=False)