def index( self, request, ): try: if request.method == 'GET': if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) registros = RedirectionRule.objects.all() context = { 'title': 'Listado Redirection Rules', 'registros': registros, 'rules': RULES } return render(request, 'cawas/redirectionrules/list.html', context) except CableOperator.DoesNotExist as e: return HttpResponse("No existe Cable Operador", None, 500) except Country.DoesNotExist as e: return HttpResponse( "Error: No Existe Pais (" + str(e.message) + ")", None, 500) except Exception as e: return HttpResponse("Hubo un error:(" + str(e.message) + ")", None, 500) except KeyError: return HttpResponse("Error en decodificacion de datos", None, 500)
def list(self, request): if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) usuario = request.user titulo = '' request.POST.get('page') message = '' flag = '' filter = False #Filtro de busqueda if request.GET.has_key('search'): search = request.GET.get('search') if search != '': filter = True movies = MovieMetadata.objects.filter( Q(title__icontains=search) | Q(movie__asset__asset_id__icontains=search)).order_by( '-id') if filter == False: movies = MovieMetadata.objects.all().order_by('-id') paginator = Paginator(movies, 25) page = request.GET.get('page') try: movies = paginator.page(page) except PageNotAnInteger: movies = paginator.page(1) except EmptyPage: movies = paginator.page(paginator.num_pages) #filtro por #if request.GET.has_key('activated'): # activated = request.GET.get('activated') # if activated != 'Todos': # movies.filter(activated=activated) if request.session.has_key('list_movie_message'): if request.session['list_movie_message'] != '': message = request.session['list_movie_message'] request.session['list_movie_message'] = '' if request.session.has_key('list_movie_flag'): if request.session['list_movie_flag'] != '': flag = request.session['list_movie_flag'] request.session['list_movie_flag'] = '' context = { 'message': message, 'flag': flag, 'registros': movies, 'titulo': titulo, 'usuario': usuario, 'filter': filter } return render(request, 'cawas/movies/list.html', context)
def unpublish(self, request, id): # Despublicar if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) try: md = MovieMetadata.objects.get(id=id) vasset_id = md.movie.asset.asset_id # 1 - VERIFICAR, si estado de publicacion esta en Q, se debe eliminar publishs = PublishQueue.objects.filter(item_id=vasset_id, status='Q', item_lang=md.language) if publishs.count > 0: publishs.delete() # Buscar todas Movies con esa chica # Realizar delete al backend setting = Setting.objects.get(code='backend_asset_url') api_key = Setting.objects.get(code='backend_api_key') vzones = PublishZone.objects.filter(enabled=True) for zone in vzones: abr = ApiBackendResource(zone.backend_url, setting.value, api_key.value) param = { "asset_id": md.movie.asset.asset_id, "asset_type": "show", "lang": md.language.code } abr.delete(param) # Actualizar Activated a False md.activated = False md.save() self.code_return = 0 request.session[ 'list_movie_message'] = 'Metadata en ' + md.language.name + ' de Movie ' + md.movie.asset.asset_id + ' Despublicado Correctamente' request.session['list_movie_flag'] = FLAG_SUCCESS except PublishZone.DoesNotExist as e: return render( request, 'cawas/error.html', {"message": "PublishZone no Existe. (" + str(e.message) + ")"}) except MovieMetadata.DoesNotExist as e: return render(request, 'cawas/error.html', { "message": "Metadata de Movie no Existe. (" + str(e.message) + ")" }) except ApiBackendException as e: request.session[ 'list_movie_message'] = "Error al despublicar (" + str( e.value) + ")" request.session['list_movie_flag'] = FLAG_ALERT return self.code_return
def list(self, request): if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) usuario = request.user message = '' flag = '' page = request.GET.get('page') request.POST.get('page') categories_list = None filter = False # Filtro de busqueda if request.GET.has_key('search'): search = request.GET.get('search') if search != '': filter = True registros = CableOperator.objects.filter( Q(cableoperator_id__icontains=search) | Q(name__icontains=search)).order_by('-id') if filter == False: registros = CableOperator.objects.all().order_by('-id') paginator = Paginator(registros, 25) page = request.GET.get('page') try: registros = paginator.page(page) except PageNotAnInteger: registros = paginator.page(1) except EmptyPage: registros = paginator.page(paginator.num_pages) if request.session.has_key('list_CableOperator_message'): if request.session['list_CableOperator_message'] != '': message = request.session['list_CableOperator_message'] request.session['list_CableOperator_message'] = '' if request.session.has_key('list_CableOperator_flag'): if request.session['list_CableOperator_flag'] != '': flag = request.session['list_CableOperator_flag'] request.session['list_CableOperator_flag'] = '' if self.message_return != '': message = self.message_return self.message_return = '' flag = 'success' operators = CableOperator.objects.all().order_by('-id') context = { 'message': message, 'flag': flag, 'registros': registros, 'usuario': usuario } return render(request, 'cawas/cableoperators/list.html', context)
def unpublish(self, request, id): if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) try: delete_param = int(request.GET.get('delete')) if (Slider.objects.filter(slider_id=id).count() > 0 ): slider = Slider.objects.get(slider_id=id) # 1 - VERIFICAR, si estado de publicacion esta en Q, se debe eliminar publishs = PublishQueue.objects.filter(item_id=slider.slider_id, status='Q') if publishs.count > 0: publishs.delete() # 2 - Realizar delete al backend setting = Setting.objects.get(code='backend_slider_url') api_key = Setting.objects.get(code='backend_api_key') vzones = PublishZone.objects.filter(enabled=True) #SE COMENTA PARA hasErrorBackend = False for zone in vzones: abr = ApiBackendResource(zone.backend_url, setting.value, api_key.value) param = {"slider_id": slider.slider_id, "lang": slider.language.code} respuesta = abr.delete(param) if 'status' in respuesta: if respuesta['status'] != 200: hasErrorBackend = True if not hasErrorBackend: if delete_param == 1: print 'se elimino' slider.delete() message = 'Slider Eliminado Correctamente ' else: print 'se despublico' message = 'Slider Despublicado Correctamente ' request.session['list_slider_message'] = message request.session['list_slider_flag'] = FLAG_SUCCESS except PublishZone.DoesNotExist as e: self.code_return = -1 request.session['list_slider_message'] = 'Error: ' + e.message request.session['list_slider_flag'] = FLAG_ALERT return self.code_return except ApiBackendException as e: self.code_return = -1 request.session['list_slider_message'] = 'Error: ' + e.message request.session['list_slider_flag'] = FLAG_ALERT return self.code_return
def unpublish(self, request, id): if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) try: print 'debugmetadata' # si es la ultima Cable Operador metadata, se debe eliminar la metadata y la Cable Operador operator = CableOperator.objects.get(id=id) # 1 - VERIFICAR, si estado de publicacion esta en Q, se debe eliminar publishs = PublishQueue.objects.filter( item_id=operator.cableoperator_id, status='Q') if publishs.count > 0: publishs.delete() #Realizar delete al backend setting = Setting.objects.get(code='backend_co_url') api_key = Setting.objects.get(code='backend_api_key') vzones = PublishZone.objects.filter(enabled=True) print 'CableoperadorID: ' + operator.cableoperator_id + 'asdf' for zone in vzones: abr = ApiBackendResource(zone.backend_url, setting.value, api_key.value) param = {"co_id": operator.cableoperator_id} abr.delete(param) #Actualizar Activated a False operator.activated = False operator.save() self.code_return = 0 request.session[ 'list_CableOperator_message'] = ' Cable Operador ' + operator.name + ' Despublicado Correctamente ' request.session['list_CableOperator_flag'] = FLAG_SUCCESS except PublishZone.DoesNotExist as e: request.session[ 'list_CableOperator_message'] = "PublishZone no Existe. (" + str( e.message) + ")" request.session['list_CableOperator_flag'] = FLAG_ALERT self.code_return = -1 except ApiBackendException as e: request.session[ 'list_CableOperator_message'] = "Error al despublicar (" + str( e.message) + ")" request.session['list_CableOperator_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return
def list(self, request): if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) usuario = request.user message = '' titulo = '' flag = '' page = request.GET.get('page') request.POST.get('page') filter = False # Filtro de busqueda if request.GET.has_key('search1'): search = request.GET.get('search1') if search != '': filter = True registros = Block.objects.filter( Q(block_id__icontains=search) | Q(name__icontains=search)).order_by('-id') if filter == False: registros = Block.objects.all().order_by('-id') paginator = Paginator(registros, 25) page = request.GET.get('page') try: registros = paginator.page(page) except PageNotAnInteger: registros = paginator.page(1) except EmptyPage: registros = paginator.page(paginator.num_pages) if request.session.has_key('list_block_message'): if request.session['list_block_message'] != '': message = request.session['list_block_message'] request.session['list_block_message'] = '' if request.session.has_key('list_block_flag'): if request.session['list_block_flag'] != '': flag = request.session['list_block_flag'] request.session['list_block_flag'] = '' blocks = Block.objects.all().order_by('-id') context = { 'message': message, 'flag': flag, 'registros': registros, 'titulo': titulo, 'usuario': usuario } return render(request, 'cawas/blocks/list.html', context)
def index(self, request): try: if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) registros = Tag.objects.all().order_by('-id') paginator = Paginator(registros, 25) page = request.GET.get('page') try: registros = paginator.page(page) except PageNotAnInteger: registros = paginator.page(1) except EmptyPage: registros = paginator.page(paginator.num_pages) context = {'registros': registros} return render(request, 'cawas/tags/index.html', context=context) except Exception as e: request.session['index_tags_message'] = e.message return render(request, 'cawas/tags/index.html', context=context)
def edit(self, request, slider_id): if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) # VARIABLES LOCALES vflag = '' message='' imgland = '' imglogo = '' try: pathfilesland = Setting.objects.get(code='image_repository_path_landscape') pathfileslogo = Setting.objects.get(code='image_repository_path_logo') base_dir = Setting.objects.get(code='dam_base_dir') except Setting.DoesNotExist as e: message= 'No existe Setting ' return render(request, 'cawas/error.html', {'code': 500, 'message': message}, status=500) try: vslider = Slider.objects.get(slider_id=slider_id) vassets = Asset.objects.all() vsliders = Slider.objects.all() vlanguages = Language.objects.all() vdevices = Device.objects.all() countries_selected = vslider.target_country.all().order_by('name') countries_notselected = Country.objects.exclude(id__in=countries_selected).order_by('name') vtypes = {"image": "Image", "video": "Video"} if vslider.image is not None: i = len(vslider.image.landscape.name) imgland = vslider.image.landscape.name[5:i] if vslider.image.logo is not None: if vslider.image.logo.name is not None: i = len(vslider.image.logo.name) imglogo = vslider.image.logo.name[5:i] except Slider.DoesNotExist as e: message = 'Error: ' + e.message return render(request, 'cawas/error.html', {'code': 500, 'message': message}, status=500) if request.method == 'POST': # VARIABLES try: # Parsear JSON strjson = request.POST['varsToJSON'] decjson = json.loads(strjson.replace('\r','\\r').replace('\n','\\n')) vslider = Slider.objects.get(slider_id=slider_id) if decjson['Slider']['asset_id'] is not None: if Asset.objects.filter(asset_id=decjson['Slider']['asset_id']).exists(): vasset = Asset.objects.get(asset_id=decjson['Slider']['asset_id']) vslider.asset = vasset else: vslider.asset = None vslider.media_type = decjson['Slider']['media_type'] vdevice = Device.objects.get(id=decjson['Slider']['target_device_id']) vslider.target_device = vdevice if decjson['Slider']['text'] is None: vslider.text = '' else: vslider.text = decjson['Slider']['text'] if decjson['Slider']['videoname'] is not None: vslider.video_name = decjson['Slider']['videoname'] if decjson['Slider']['linked_url'] is None: vslider.linked_url = '' else: vslider.linked_url = decjson['Slider']['linked_url'] print 'videoname ' vslider.save() vslider.language = Language.objects.get(code=decjson['Slider']['language']) if (decjson['Slider']['publish_date'] != ''): vschedule_date = datetime.datetime.strptime(decjson['Slider']['publish_date'], '%d-%m-%Y').strftime('%Y-%m-%d') else: vschedule_date = datetime.datetime.now().strftime('%Y-%m-%d') vslider.publish_date = vschedule_date if Image.objects.filter(name=vslider.slider_id).exists(): vimg = Image.objects.get(name=vslider.slider_id) else: vimg = Image() except Device.DoesNotExist as e: message = "Error: (" + str(e.message) + ")" return render(request, 'cawas/error.html', {'code': 500, 'message': message}, status=500) except Asset.DoesNotExist as e: message = "Error: (" + str(e.message) + ")" return render(request, 'cawas/error.html', {'code': 500, 'message': message}, status=500) vimg.name = vslider.slider_id # IMAGEN Portrait if (request.FILES.has_key('ThumbHor')): if request.FILES['ThumbHor'].name != '': # TRATAMIENTO DE IMAGEN Landscape vimg.landscape = request.FILES['ThumbHor'] extension = os.path.splitext(vimg.landscape.name)[1] varchivo = pathfilesland.value + vimg.name + extension vimg.landscape.name = varchivo varchivo_server = base_dir.value + varchivo if os.path.isfile(varchivo_server): os.remove(varchivo_server) # LOGO if (request.FILES.has_key('logo')): if request.FILES['logo'].name != '': # TRATAMIENTO DE IMAGEN LOGO vimg.logo = request.FILES['logo'] extension = os.path.splitext(vimg.logo.name)[1] varchivo = pathfileslogo.value + vimg.name + extension vimg.logo.name = varchivo varchivo_server = base_dir.value + varchivo if os.path.isfile(varchivo_server): os.remove(varchivo_server) # /LOGO vimg.save() vslider.image = vimg vslider.queue_status = 'Q' vslider.target_country = [] # CARGAR Countries al Asset del Episode if (decjson['Slider']['countries'] is not None): countries = decjson['Slider']['countries'] for item in countries: try: country = Country.objects.get(id=item['country_id']) vslider.target_country.add(country) except Country.DoesNotExist as e: message = "Error: No Existe Pais (" + str(e.message) + ")" return render(request, 'cawas/error.html', {'code': 500, 'message': message}, status=500) vslider.save() # publicar ph = PublishHelper() ph.func_publish_queue(request, vslider.slider_id, vslider.language, 'SL', 'Q', vslider.publish_date) ph.func_publish_image(request, vslider.image) vflag = "success" request.session['list_slider_message'] = 'Guardado Correctamente en Cola de Publicacion' request.session['list_slider_flag'] = FLAG_SUCCESS if request.method == 'GET': context = { 'vtypes': vtypes, 'vassets': vassets, 'vsliders': vsliders, 'imgland':imgland, 'imglogo': imglogo, 'vlanguages': vlanguages, 'vdevices': vdevices, 'flag': vflag, 'vslider':vslider, 'message':message, 'countries_selected':countries_selected, 'countries_notselected':countries_notselected} return render(request, 'cawas/sliders/edit.html', context)
def _start(self): #create log controller self.logController = LogController((('consoleLog', 'consoleLog', {'logLevel':'critical', 'logFormat':'%(asctime)s %(levelname)-8s %(name)-22s - %(message)s'}), ('fileLog' , 'fileLog' , {'filename':os.path.join(self.progPath, u'Logs', u'log'), 'logLevel':'info', 'logFormat':'%(asctime)s %(levelname)-8s %(name)-22s - %(message)s', 'fileMaxBytes':10485760, 'fileMaxRotatedCount':4}))) #create config, set defaults configDefaults = {'choker':{'chokeInterval':(60, 'int'), 'randomSlotRatio':(0.1, 'float'), 'maxSlots':(10, 'int'), 'slotLimitScope':('global', 'str')}, 'http':{'torrentFetchRetryInterval':(60, 'int'), 'torrentFetchTransferTimeout':(120, 'int'), 'torrentFetchRequestTimeout':(600, 'int'), 'torrentFetchMaxHeaderSize':(4096, 'int'), 'torrentFetchMaxDataSize':(1048576, 'int'), 'trackerRequestTransferTimeout':(120, 'int'), 'trackerRequestTimeout':(300, 'int'), 'trackerRequestMaxHeaderSize':(4096, 'int'), 'trackerRequestMaxDataSize':(1048576, 'int'), 'startDownloadAfterTorrentFetch':(False, 'bool')}, 'i2p':{'samIp':('127.0.0.1', 'ip'), 'samPort':(7656, 'port'), 'samDisplayName':('PyBit', 'str'), 'samSessionName':('PyBit', 'str'), 'samZeroHopsIn':(False, 'bool'), 'samZeroHopsOut':(False, 'bool'), 'samNumOfTunnelsIn':(3, 'int'), 'samNumOfTunnelsOut':(3, 'int'), 'samNumOfBackupTunnelsIn':(0, 'int'), 'samNumOfBackupTunnelsOut':(0, 'int'), 'samTunnelLengthIn':(2, 'int'), 'samTunnelLengthOut':(2, 'int'), 'samTunnelLengthVarianceIn':(0, 'int'), 'samTunnelLengthVarianceOut':(0, 'int')}, 'logging':{'consoleLoglevel':('critical', 'str'), 'fileLoglevel':('info', 'str')}, 'network':{'downSpeedLimit':(102400, 'int'), 'upSpeedLimit':(25600, 'int')}, 'paths':{'torrentFolder':(self.progPath, 'unicode'), 'downloadFolder':(self.progPath, 'unicode')}, 'requester':{'strictAvailabilityPrio':(True, 'bool')}, 'storage':{'persistPieceStatus':(True, 'bool'), 'skipFileCheck':(False, 'bool')}, 'tracker':{'announceInterval':(3600, 'int'), 'scrapeInterval':(3600, 'int'), 'clearOldScrapeStats':(True, 'bool'), 'scrapeWhileStopped':(False, 'bool'), 'scrapeTrackers':('active', 'str')}} self.config = Config(os.path.join(self.progPath, u'config.conf'), configDefaults=configDefaults) #set real log options and add callbacks self.logController.changeHandlerLoglevel('consoleLog', self.config.get('logging','consoleLoglevel')) self.logController.changeHandlerLoglevel('fileLog', self.config.get('logging','fileLoglevel')) self.config.addCallback((('logging', 'consoleLoglevel'),), self.logController.changeHandlerLoglevel, funcArgs=['consoleLog'], valueArgPlace=1) self.config.addCallback((('logging', 'fileLoglevel'),), self.logController.changeHandlerLoglevel, funcArgs=['fileLog'], valueArgPlace=1) #create persister self.log.info("Creating object persister instance") self.persister = ThreadedObjectPersister(os.path.join(self.progPath, u'state.db'), log='ObjectPersister') self.persister.start() #creat torrent handler self.torrentHandler = MultiBt(self.config, self.persister, self.progPath, self.version)
def unpublish(self, request, id): if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) try: episodemetadata = EpisodeMetadata.objects.get(id=id) vasset_id = episodemetadata.episode.asset.asset_id # 1 - VERIFICAR, si estado de publicacion esta en Q, se debe eliminar publishs = PublishQueue.objects.filter( item_id=vasset_id, status='Q', item_lang=episodemetadata.language) if publishs.count > 0: publishs.delete() # 2 - Realizar delete al backend setting = Setting.objects.get(code='backend_asset_url') api_key = Setting.objects.get(code='backend_api_key') vzones = PublishZone.objects.filter(enabled=True) for zone in vzones: abr = ApiBackendResource(zone.backend_url, setting.value, api_key.value) param = { "asset_id": episodemetadata.episode.asset.asset_id, "asset_type": "show", "lang": episodemetadata.language.code } abr.delete(param) # Se deberia hacer algo con las Series? # mostrar cartel de informaion # 3 - Actualizar Activated a False episodemetadata.activated = False episodemetadata.save() #publicar la serie nuevamente serie = episodemetadata.episode.serie serie_metadatas = SerieMetadata.objects.filter(serie=serie) for item in serie_metadatas: ph = PublishHelper() ph.func_publish_queue( request, item.serie.asset.asset_id, item.language, 'AS', 'Q', datetime.datetime.now().strftime('%Y-%m-%d')) self.code_return = 0 self.message_return = 'Episode ' + episodemetadata.episode.asset.asset_id + ' despublicada Correctamente' request.session[ 'list_episode_message'] = 'Metadata en ' + episodemetadata.language.name + ' de Capitulo ' + episodemetadata.episode.asset.asset_id + ' Despublicado Correctamente' request.session['list_episode_flag'] = FLAG_SUCCESS except PublishZone.DoesNotExist as e: return render( request, 'cawas/error.html', {"message": "PublishZone no Existe. (" + str(e.message) + ")"}) except EpisodeMetadata.DoesNotExist as e: return render( request, 'cawas/error.html', { "message": "Metadata de Capitulo no Existe. (" + str(e.message) + ")" }) except ApiBackendException as e: request.session[ 'list_episode_message'] = "Error al despublicar (" + str( e.value) + ")" request.session['list_episode_flag'] = FLAG_ALERT return self.code_return
def edit(self, request, episode_id): # AUTENTICACION DE USUARIO if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) # VARIABLES LOCALES message = '' vflag = '' vschedule_date = '' vasset = Asset() vepisode = Episode() imgport = '' imgland = '' publicar = 0 try: vasset = Asset.objects.get(asset_id=episode_id) vepisode = Episode.objects.get(asset=vasset) if vepisode.image is not None: if vepisode.image.portrait is not None: i = len(vepisode.image.portrait.name) imgport = vepisode.image.portrait.name[5:i] if vepisode.image.landscape is not None: i = len(vepisode.image.landscape.name) imgland = vepisode.image.landscape.name[5:i] except Asset.DoesNotExist as e: request.session['list_episode_message'] = 'No Existe Asset' + str( e.message) request.session['list_episode_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return except Setting.DoesNotExist as e: request.session[ 'list_episode_message'] = 'No Existe Espisodio ' + str( e.message) request.session['list_episode_flag'] = FLAG_SUCCESS self.code_return = -1 return self.code_return if request.method == 'POST': try: pathfilesport = Setting.objects.get( code='image_repository_path_portrait') pathfilesland = Setting.objects.get( code='image_repository_path_landscape') base_dir = Setting.objects.get(code='dam_base_dir') # Parsear JSON strjson = request.POST['varsToJSON'] decjson = json.loads( strjson.replace('\r', '\\r').replace('\n', '\\n')) vasset_serie = Asset.objects.get( asset_id=decjson['Episode']['serie_id']) vepisode.serie = Serie.objects.get(asset=vasset_serie) # Validar siel episodio existe # buscar episodio con igual serie, chapter y temporada # en la edicion se debe comprobar si el usuario cambio algun dato (episodio, temporada), # si se cambio entonces corroborar integracion de datos # si no cambio estos datos, entonces no hacer la validacion, para no mostrar el mensaje chapter = decjson['Episode']['chapter'] season = decjson['Episode']['season'] if ((vepisode.chapter != chapter & vepisode.season == season) | (vepisode.chapter == chapter & vepisode.season != season)): if Episode.objects.filter(chapter=chapter, season=season, serie=vasset_serie).count() > 0: request.session[ 'list_episode_message'] = 'Error: el numero de episodio ya existe para la Serie' request.session['list_episode_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return # DATOS OBLIGATORIOS vepisode.original_title = decjson['Episode']['original_title'] vepisode.channel = Channel.objects.get( pk=decjson['Episode']['channel_id']) vepisode.display_runtime = decjson['Episode'][ 'display_runtime'] vepisode.chapter = decjson['Episode']['chapter'] vepisode.season = decjson['Episode']['season'] publicar = decjson['Episode']['publicar'] # Datos OPCIONALES if (decjson['Episode']['year'] is not None): vepisode.year = decjson['Episode']['year'] if (decjson['Episode']['cast'] is not None): vepisode.cast = decjson['Episode']['cast'] if (decjson['Episode']['directors'] is not None): vepisode.directors = decjson['Episode']['directors'] try: vimg = Image.objects.get(name=vasset.asset_id) except Image.DoesNotExist as e: vimg = Image() vimg.name = vasset.asset_id # IMAGEN Portrait if (request.FILES.has_key('ThumbHor')): if request.FILES['ThumbHor'].name != '': # TRATAMIENTO DE IMAGEN Landscape vimg.landscape = request.FILES['ThumbHor'] extension = os.path.splitext(vimg.landscape.name)[1] varchivo = pathfilesland.value + vimg.name + extension vimg.landscape.name = varchivo varchivo_server = base_dir.value + varchivo if os.path.isfile(varchivo_server): os.remove(varchivo_server) # IMAGEN Landscape if (request.FILES.has_key('ThumbVer')): if request.FILES['ThumbVer'].name != '': # Landscape vimg.portrait = request.FILES['ThumbVer'] extension = os.path.splitext(vimg.portrait.name)[1] varchivo = pathfilesport.value + vimg.name + extension vimg.portrait.name = varchivo # si existe archivo, lo borra varchivo_server = base_dir.value + varchivo if os.path.isfile(varchivo_server): os.remove(varchivo_server) vimg.save() vepisode.image = vimg vepisode.save() except Asset.DoesNotExist as e: request.session[ 'list_episode_message'] = 'No Existe Asset' + str( e.message) request.session['list_episode_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return except Exception as e: request.session[ 'list_episode_message'] = 'Error al Guardar Episodio: ' + str( e.message) request.session['list_episode_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return # CARGAR ASSETS vepisode.girls = [] vepisode.save() if (decjson['Episode']['girls'] is not None): vgirls = decjson['Episode']['girls'] for item in vgirls: try: asset_id = item['girl_id'] vgirl = Girl.objects.get(id=item['girl_id']) vepisode.girls.add(vgirl) except Exception as e: request.session[ 'list_episode_message'] = 'Error al Guardar Episodio: ' + str( e.message) request.session['list_episode_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return vepisode.category = [] vepisode.save() # CARGAR CATEGORY vcategories = decjson['Episode']['categories'] for item in vcategories: try: category_id = item['category_id'] print "category_id add episode" + category_id vcategory = Category.objects.get(pk=category_id) vepisode.category.add(vcategory) except Exception as e: request.session[ 'list_episode_message'] = 'Error al Guardar Episodio: ' + str( e.message) request.session['list_episode_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return vepisode.save() #Eliminar cola de publicacion para el item en estado Queued ph = PublishHelper() vepisodemetadata = decjson['Episode']['Episodemetadatas'] for item in vepisodemetadata: try: vlang = Language.objects.get( code=item['Episodemetadata']['language']) try: emd = EpisodeMetadata.objects.get(episode=vepisode, language=vlang) except EpisodeMetadata.DoesNotExist as e: emd = EpisodeMetadata() # convertDateYMDnowIsNull if (item['Episodemetadata']['schedule_date'] != ''): vschedule_date = datetime.datetime.strptime( item['Episodemetadata']['schedule_date'], '%d-%m-%Y').strftime('%Y-%m-%d') else: vschedule_date = datetime.datetime.now().strftime( '%Y-%m-%d') emd.language = vlang emd.title = item['Episodemetadata']['title'] emd.summary_short = item['Episodemetadata'][ 'summary_short'] emd.summary_long = item['Episodemetadata']['summary_long'] emd.keywords = item['Episodemetadata']['keywords'] #emd.publish_date = vschedule_date emd.episode = vepisode emd.queue_status = 'Q' emd.save() #Publicar el Episodio ph = PublishHelper() if publicar > 0: # Consultar si serie metadata esta del lenguaje esta activada, de ser asi, se publica la serie nuevamente if (SerieMetadata.objects.filter( serie=vepisode.serie, language=vlang, activated=False).count() > 0): ph.func_publish_queue( request, vepisode.serie.asset.asset_id, vlang, 'AS', 'Q', vschedule_date) ph.func_publish_image(request, vepisode.serie.image) ph.func_publish_queue(request, vepisode.asset.asset_id, vlang, 'AS', 'Q', vschedule_date) ph.func_publish_image(request, vimg) #Se publica ph.func_publish_queue(request, vepisode.serie.asset.asset_id, vlang, 'AS', 'Q', vschedule_date) ph.func_publish_image(request, vepisode.serie.image) request.session[ 'list_episode_message'] = 'Guardado Correctamente ' request.session['list_episode_flag'] = FLAG_SUCCESS except Language.DoesNotExist as e: self.code_return = -1 request.session[ 'list_episode_message'] = 'Lenguaje no Existe ' + e.message request.session['list_episode_flag'] = FLAG_ALERT return self.code_return except Exception as e: self.code_return = -1 request.session[ 'list_episode_message'] = 'Error al Guardar Episode Metadata ' + e.message request.session['list_episode_flag'] = FLAG_ALERT return self.code_return try: vchannels = Channel.objects.all() vcategories = Category.objects.all() vgirls = Girl.objects.all() vlanguages = Language.objects.all() vmovies = Movie.objects.all() vcapitulos = Episode.objects.all() vassets = Asset.objects.filter(asset_type="unknown") vgirlselected = vepisode.girls.all() vgirlnotselected = Girl.objects.exclude(id__in=vgirlselected) vcategoryselected = vepisode.category.all() vcategorynotselected = Category.objects.exclude( id__in=vcategoryselected) vseries = Serie.objects.all() countries_selected = vepisode.asset.target_country.all().order_by( 'name') countries_notselected = Country.objects.exclude( id__in=countries_selected).order_by('name') # nuevo diccionario para completar lenguages y metadata vlangmetadata = [] for itemlang in vlanguages: try: vepisodemetadata = EpisodeMetadata.objects.get( episode=vepisode, language=itemlang) vlangmetadata.append({ 'checked': True, 'code': itemlang.code, 'name': itemlang.name, 'title': vepisodemetadata.title, 'summary_short': vepisodemetadata.summary_short, 'summary_long': vepisodemetadata.summary_long, 'publish_date': vepisodemetadata.publish_date, 'keywords': vepisodemetadata.keywords_as_list }) except EpisodeMetadata.DoesNotExist as a: vlangmetadata.append({ 'checked': False, 'code': itemlang.code, 'name': itemlang.name, 'titulo': '', 'descripcion': '', 'fechapub': '', 'keywords': '' }) except Girl.DoesNotExist as e: return render(request, 'cawas/error.html', {"message": "No existe Chica. (" + e.message + ")"}) except Category.DoesNotExist as e: return render( request, 'cawas/error.html', {"message": "No existe Categoria. (" + e.message + ")"}) context = { 'message': message, 'vgirlnotselected': vgirlnotselected, 'vgirlselected': vgirlselected, 'imgland': imgland, 'imgport': imgport, 'vepisode': vepisode, 'vcategorynotselected': vcategorynotselected, 'vcategoryselected': vcategoryselected, 'vchannels': vchannels, 'vlangmetadata': vlangmetadata, 'vseries': vseries, 'countries_selected': countries_selected, 'countries_notselected': countries_notselected, } return render(request, 'cawas/episodes/edit.html', context)
def edit(self, request, id): try: if request.is_ajax(): if request.method == 'POST': json_data = json.loads(request.body) rr = PackagePrice.objects.get( id=json_data['data']['packageprice_id']) print 'edit: ' + str(json_data) if (json_data['data']['country'] is not None): if (json_data['data']['country'] > 0): country_id = json_data['data']['country'] country = Country.objects.get(id=country_id) rr.country = country if (json_data['data']['price'] is not None): if (json_data['data']['price'] != ''): price = json_data['data']['price'] rr.price = price if (json_data['data']['currency'] is not None): if (json_data['data']['currency'] != ''): currency = json_data['data']['currency'] rr.currency = currency if (json_data['data']['package_duration'] is not None): if (json_data['data']['package_duration'] != ''): package_duration = json_data['data'][ 'package_duration'] rr.duration = package_duration print ' error' rr.save() mydata = [{ 'code': 200, 'message': 'Guardado Correctamente' }] return HttpResponse(json.dumps(mydata), None, 200) if request.method == 'GET': if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) registro = PackagePrice.objects.get(id=id) countries = Country.objects.all() context = { 'registro': registro, 'countries': countries, 'rules': RULES, 'duration': PACKAGE_DURATION_VIEW } return render(request, 'cawas/packageprices/edit.html', context) except CableOperator.DoesNotExist as e: return HttpResponse("No existe Cable Operador", None, 500) except Country.DoesNotExist as e: return HttpResponse( "Error: No Existe Pais (" + str(e.message) + ")", None, 500) except Exception as e: return HttpResponse("Hubo un error:(" + str(e.message) + ")", None, 500) except KeyError: return HttpResponse("Error en decodificacion de datos", None, 500)
def edit(self, request, id): try: if request.is_ajax(): if request.method == 'POST': json_data = json.loads(request.body) rr = RedirectionRule.objects.get( id=json_data['redirectionrules']['redirectionrule_id']) if (json_data['redirectionrules']['cableoperator'] is not None): if json_data['redirectionrules']['cableoperator'] != '': co_id = json_data['redirectionrules'][ 'cableoperator'] co = CableOperator.objects.get(id=co_id) rr.cableoperator = co if (json_data['redirectionrules']['country'] is not None): if (json_data['redirectionrules']['country'] > 0): country_id = json_data['redirectionrules'][ 'country'] country = Country.objects.get(id=country_id) rr.country = country if (json_data['redirectionrules']['rule'] is not None): if (json_data['redirectionrules']['rule'] != ''): rule_id = json_data['redirectionrules']['rule'] rr.rule = rule_id rr.save() mydata = [{ 'code': 200, 'message': 'Guardado Correctamente' }] messages.add_message(request, messages.INFO, 'Guardado Correctamente') return HttpResponse(json.dumps(mydata), None, 200) if request.method == 'GET': if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) registro = RedirectionRule.objects.get(id=id) countries = Country.objects.all() cableoperators = CableOperator.objects.all() context = { 'registro': registro, 'cableoperators': cableoperators, 'countries': countries, 'rules': RULES } return render(request, 'cawas/redirectionrules/edit.html', context) except CableOperator.DoesNotExist as e: return HttpResponse("No existe Cable Operador", None, 500) except Country.DoesNotExist as e: return HttpResponse( "Error: No Existe Pais (" + str(e.message) + ")", None, 500) except Exception as e: return HttpResponse("Hubo un error:(" + str(e.message) + ")", None, 500) except KeyError: return HttpResponse("Error en decodificacion de datos", None, 500)
def add(self, request): # AUTENTICACION DE USUARIO if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) flag = '' message = '' vimg = Image() vgrabarypublicar = '' try: pathfilesport = Setting.objects.get( code='image_repository_path_portrait') pathfilesland = Setting.objects.get( code='image_repository_path_landscape') base_dir = Setting.objects.get(code='dam_base_dir') except Setting.DoesNotExist as e: return render(request, 'cawas/error.html', {"message": "No Setting. (" + e.message + ")"}) # POST - Obtener datos del formulario y guardar la metadata if request.method == 'POST': # parsear JSON strjson = request.POST['varsToJSON'] decjson = json.loads( strjson.replace('\r', '\\r').replace('\n', '\\n')) print 'debug1' # VARIABLES - (esta logica pasa al controlador) vgirl = Girl() vasset = Asset() vasset.asset_type = "girl" vasset.save() print 'debug2' #try: vimg.name = vasset.asset_id # IMAGEN Portrait if (request.FILES.has_key('ThumbHor')): if request.FILES['ThumbHor'].name != '': # TRATAMIENTO DE IMAGEN Landscape vimg.landscape = request.FILES['ThumbHor'] extension = os.path.splitext(vimg.landscape.name)[1] varchivo = pathfilesland.value + vimg.name + extension vimg.landscape.name = varchivo varchivo_server = base_dir.value + varchivo if os.path.isfile(varchivo_server): os.remove(varchivo_server) # IMAGEN Landscape if (request.FILES.has_key('ThumbVer')): if request.FILES['ThumbVer'].name != '': # Landscape vimg.portrait = request.FILES['ThumbVer'] extension = os.path.splitext(vimg.portrait.name)[1] varchivo = pathfilesport.value + vimg.name + extension vimg.portrait.name = varchivo # si existe archivo, lo borra varchivo_server = base_dir.value + varchivo if os.path.isfile(varchivo_server): os.remove(varchivo_server) vimg.save() print 'debug3' # CREAR GIRL vgirl.asset = vasset vgirl.name = decjson['Girl']['name'] vgirl.type = decjson['Girl']['type_girl'] vgrabarypublicar = decjson['Girl']['publicar'] if (decjson['Girl']['birth_date'] is not None): vgirl.birth_date = datetime.datetime.strptime( decjson['Girl']['birth_date'], '%d-%m-%Y').strftime('%Y-%m-%d') else: vgirl.birth_date = datetime.datetime.now().strftime('%Y-%m-%d') vgirl.height = decjson['Girl']['height'] vgirl.weight = decjson['Girl']['weight'] vgirl.image = vimg print 'debug4' vgirl.save() # CARGAR Countries al Asset if (decjson['Girl']['countries'] is not None): countries = decjson['Girl']['countries'] for item in countries: try: country = Country.objects.get(id=item['country_id']) vgirl.asset.target_country.add(country) except Country.DoesNotExist as e: request.session[ 'list_girl_message'] = "Error: No Existe Pais (" + str( e.message) + ")" request.session['list_girl_flag'] = FLAG_ALERT self.code_return = -1 # CREAR METADATA print 'debug6' # Eliminar cola de publicacion para el item en estado Queued ph = PublishHelper() vgirlmetadatas = decjson['Girl']['Girlmetadatas'] for item in vgirlmetadatas: vlanguage = Language.objects.get( code=item['Girlmetadata']['language']) # Luego del POST redirige a pagina principal try: gmd = GirlMetadata.objects.get(girl=vgirl, language=vlanguage) except GirlMetadata.DoesNotExist as e: gmd = GirlMetadata() #if (item['Girlmetadata']['schedule_date'] != ''): # vschedule_date = datetime.datetime.strptime(item['Girlmetadata']['schedule_date'],'%d-%m-%Y').strftime('%Y-%m-%d') #else: vschedule_date = datetime.datetime.now().strftime('%Y-%m-%d') gmd.language = vlanguage gmd.description = item['Girlmetadata']['description'] gmd.nationality = item['Girlmetadata']['nationality'] #gmd.publish_date = vschedule_date gmd.girl = vgirl gmd.save() #PUBLICAR METADATA if vgrabarypublicar == '1': try: ph = PublishHelper() ph.func_publish_image(request, vimg) ph.func_publish_queue(request, gmd.girl.asset.asset_id, gmd.language, 'AS', 'Q', vschedule_date) gmd.queue_status = 'Q' except GirlMetadata.DoesNotExist as e: request.session[ 'list_girl_message'] = 'No existe GirlMetadata ' + e.message request.session['list_girl_flag'] = FLAG_ALERT return -1 request.session['list_girl_message'] = 'Guardado Correctamente' request.session['list_girl_flag'] = FLAG_SUCCESS #FIN DE POST if request.method == 'GET': # Cargar variables para presentar en templates vgirls = Girl.objects.all().order_by('name') vcategories = Category.objects.all().order_by('name') vlanguages = Language.objects.all() countries = Country.objects.all().order_by('name') vtypegirl = {"pornstar": "Pornstar", "playmate": "Playmate"} context = { 'vgirls': vgirls, 'vcategories': vcategories, 'vlanguages': vlanguages, 'vtypegirl': vtypegirl, 'countries': countries } return render(request, 'cawas/girls/add.html', context)
def unpublish(self, request, id): if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) try: block = Block.objects.get(id=id) #1 - quitar la asociacion #Si el Bloque no fue publicado, se elimina de cawas y sus relaciones if not block.activated: block.delete() self.code_return = 0 request.session[ 'list_block_message'] = 'Bloque Eliminado Correctamente ' request.session['list_block_flag'] = FLAG_SUCCESS return self.code_return assetsblock = block.assets.all() #print 'assetblock: ' + str(assetsblock) # 2 - VERIFICAR, Si bloque esta encolado, se elimina de cola de publicacion publishs = PublishQueue.objects.filter(item_id=block.block_id, status='Q') if publishs.count > 0: publishs.delete() print 'publish.delete(): ' # 3 - Publicar los assets que pertenecen al Bloque #vschedule_date = datetime.datetime.strptime(decjson['Block']['publish_date'], '%d-%m-%Y').strftime('%Y-%m-%d') for item in assetsblock: # enconlar los assets if item.asset_type == "movie": movie = Movie.objects.get(asset=item) ctr = MovieController() ctr.publish_all(request, param_movie=movie, param_lang=block.language) print 'publica movie: ' if item.asset_type == "serie": serie = Serie.objects.get(asset=item) ctr = SerieController() ctr.publish_all(request, param_serie=serie, param_lang=block.language) print 'publica serie: ' if item.asset_type == "episode": episode = Episode.objects.get(asset=item) ctr = EpisodeController() ctr.publish_all(request, param_episode=episode, param_lang=block.language) print 'publica episode: ' if item.asset_type == "girl": girl = Girl.objects.get(asset=item) ctr = GirlController() ctr.publish_all(request, param_girl=girl, param_lang=block.language) print 'publica girl: ' # 4 - Realizar delete al backend setting = Setting.objects.get(code='backend_block_url') api_key = Setting.objects.get(code='backend_api_key') vzones = PublishZone.objects.filter(enabled=True) for zone in vzones: abr = ApiBackendResource(zone.backend_url, setting.value, api_key.value) param = { "block_id": block.block_id, "lang": block.language.code } abr.delete(param) # 3 - Actualizar Activated a False #block.assets = [] #block.activated = False #block.save() # se elimina el bloque de cawas block.delete() self.code_return = 0 request.session[ 'list_block_message'] = 'Bloque Eliminado y Despublicado Correctamente ' request.session['list_block_flag'] = FLAG_SUCCESS except PublishZone.DoesNotExist as e: request.session[ 'list_block_message'] = "Error al despublicar (" + str( e.message) + ")" request.session['list_block_flag'] = FLAG_ALERT self.code_return = -1 except Block.DoesNotExist as e: request.session[ 'list_block_message'] = "Error al despublicar (" + str( e.message) + ")" request.session['list_block_flag'] = FLAG_ALERT self.code_return = -1 except Setting.DoesNotExist as e: request.session[ 'list_block_message'] = "Error al despublicar (" + str( e.message) + ")" request.session['list_block_flag'] = FLAG_ALERT self.code_return = -1 except ApiBackendException as e: request.session[ 'list_block_message'] = "Error al despublicar (" + str( e.value) + ")" request.session['list_block_flag'] = FLAG_ALERT except Exception as e: request.session[ 'list_block_message'] = "Error al despublicar (" + str(e) + ")" request.session['list_block_flag'] = FLAG_ALERT return self.code_return
def edit(self, request, block_id): # AUTENTICACION DE USUARIO if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) vblock = Block() # VARIABLES LOCALES message = '' vflag = '' vschedule_date = '' if request.method == 'POST': # Parsear JSON try: strjson = request.POST['varsToJSON'] decjson = json.loads( strjson.replace('\r', '\\r').replace('\n', '\\n')) vblock = Block.objects.get( block_id=decjson['Block']['block_id']) vblock.name = decjson['Block']['name'] vblock.order = decjson['Block']['order'] vschedule_date = datetime.datetime.strptime( decjson['Block']['publish_date'], '%d-%m-%Y').strftime('%Y-%m-%d') vblock.publish_date = vschedule_date vblock.language = Language.objects.get( code=decjson['Block']['language']) if decjson['Block']['channel_id'] is not None: vblock.channel = Channel.objects.get( pk=decjson['Block']['channel_id']) if (decjson['Block']['tipo'] is not None): vblock.type = decjson['Block']['tipo'] if (decjson['Block']['query'] is not None): vblock.query = decjson['Block']['query'] vdevice = Device.objects.get( pk=int(decjson['Block']['target_device_id'])) vblock.target_device_id = int( decjson['Block']['target_device_id']) vblock.queue_status = 'Q' vblock.save() except Exception as e: self.code_return = -1 request.session['list_block_message'] = 'Error: ' + str(e) request.session['list_block_flag'] = FLAG_ALERT return self.code_return vblock.target_country = [] # CARGAR Countries al Asset if (decjson['Block']['countries'] is not None): countries = decjson['Block']['countries'] for item in countries: try: country = Country.objects.get(id=item['country_id']) vblock.target_country.add(country) except Country.DoesNotExist as e: request.session[ 'list_block_message'] = "Error: No Existe Pais (" + str( e.message) + ")" request.session['list_block_flag'] = FLAG_ALERT self.code_return = -1 # CARGAR NUEVOS ASSETS SELECCIONADOS assetall = [] vassets = decjson['Block']['assets'] for itemactual in vassets: if itemactual['asset_id'] not in assetall: assetall.append(itemactual['asset_id']) for itemactual in vblock.assets.all(): if itemactual.asset_id not in assetall: assetall.append(itemactual.asset_id) # Bloque en Cawas vblock.assets.clear() for item in vassets: try: asset_id = item['asset_id'] vasset = Asset.objects.get(asset_id=asset_id) vblock.assets.add(vasset) except Asset.DoesNotExist as e: return render( request, 'cawas/error.html', {"message": "No existe Asset. (" + e.message + ")"}) vblock.save() # Publicacion for item in assetall: try: ph = PublishHelper() print item ph.func_publish_queue(request, item, vblock.language, 'AS', 'Q', vblock.publish_date) except Asset.DoesNotExist as e: request.session[ 'list_block_message'] = 'Error: ' + e.message request.session['list_block_flag'] = FLAG_ALERT return -1 ph = PublishHelper() ph.func_publish_queue(request, vblock.block_id, vblock.language, 'BL', 'Q', vblock.publish_date) context = {"flag": "success"} self.code_return = 0 request.session['list_block_message'] = 'Guardado Correctamente.' request.session['list_block_flag'] = FLAG_SUCCESS return render(request, 'cawas/blocks/edit.html', context) # Fin datos Bloque try: print "block_id" + block_id vblock = Block.objects.get(block_id=block_id) vassetselect = vblock.assets.all() # vmovienotselect = Movie.objects.exclude( asset__in=vassetselect).order_by('original_title') vserienotselect = Serie.objects.exclude( asset__in=vassetselect).order_by('original_title') vgirlnotselect = Girl.objects.exclude(asset__in=vassetselect) vepisodenotselect = Episode.objects.exclude(asset__in=vassetselect) vmovieselect = Movie.objects.filter(asset__in=vassetselect) vserieselect = Serie.objects.filter(asset__in=vassetselect) vgirlselect = Girl.objects.filter(asset__in=vassetselect) vepisodeselect = Episode.objects.filter(asset__in=vassetselect) countries_selected = vblock.target_country.all().order_by('name') countries_notselected = Country.objects.exclude( id__in=countries_selected).order_by('name') except Block.DoesNotExist as e: return render( request, 'cawas/error.html', {"message": "No existe Bloque2. (" + e.message + ")"}) # Variables Para GET vchannels = Channel.objects.all() vseries = Serie.objects.all() vgirls = Girl.objects.all() vlanguages = Language.objects.all() vdevices = Device.objects.all() context = { 'message': message, 'vchannels': vchannels, 'vgirls': vgirls, 'vlanguages': vlanguages, 'vseries': vseries, 'vblock': vblock, 'vdevices': vdevices, 'vmovienotselect': vmovienotselect, 'vgirlnotselect': vgirlnotselect, 'vepisodenotselect': vepisodenotselect, 'vmovieselect': vmovieselect, 'vgirlselect': vgirlselect, 'vepisodeselect': vepisodeselect, 'vserienotselect': vserienotselect, 'vserieselect': vserieselect, 'countries_selected': countries_selected, 'countries_notselected': countries_notselected, 'block_type': BLOCK_TYPE } return render(request, 'cawas/blocks/edit.html', context)
def add(self, request): # AUTENTICACION DE USUARIO if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) # VARIABLES LOCALES message = '' vflag = '' vschedule_date = '' vgrabarypublicar = '' if request.method == 'POST': # VARIABLES vblock = Block() # Parsear JSON try: strjson = request.POST['varsToJSON'] decjson = json.loads( strjson.replace('\r', '\\r').replace('\n', '\\n')) vblock.name = decjson['Block']['name'] vblock.order = decjson['Block']['order'] if (decjson['Block']['tipo'] is not None): vblock.type = decjson['Block']['tipo'] if (decjson['Block']['query'] is not None): vblock.query = decjson['Block']['query'] vgrabarypublicar = decjson['Block']['publicar'] vschedule_date = datetime.datetime.strptime( decjson['Block']['publish_date'], '%d-%m-%Y').strftime('%Y-%m-%d') if vschedule_date is None: vschedule_date = datetime.datetime.now().strftime( '%Y-%m-%d') vblock.publish_date = vschedule_date vblock.language = Language.objects.get( code=decjson['Block']['language']) vblock.queue_status = 'Q' if decjson['Block']['channel_id'] is not None: vblock.channel = Channel.objects.get( pk=decjson['Block']['channel_id']) vblock.target_device = Device.objects.get( pk=int(decjson['Block']['target_device_id'])) vblock.save() # CARGAR Countries al Asset if (decjson['Block']['countries'] is not None): countries = decjson['Block']['countries'] for item in countries: try: country = Country.objects.get( id=item['country_id']) vblock.target_country.add(country) except Country.DoesNotExist as e: request.session[ 'list_block_message'] = "Error: No Existe Pais (" + str( e.message) + ")" request.session['list_block_flag'] = FLAG_ALERT self.code_return = -1 vassets = decjson['Block']['assets'] for item in vassets: try: asset_id = item['asset_id'] vasset = Asset.objects.get(asset_id=asset_id) vblock.assets.add(vasset) except Asset.DoesNotExist as e: return render( request, 'cawas/error.html', { "message": "No existe Asset. " + asset_id + " (" + e.message + ")" }) vblock.save() except Setting.DoesNotExist as e: self.code_return = -1 request.session[ 'list_block_message'] = 'Error: No existe Configuracion. ' + e.message request.session['list_block_flag'] = FLAG_ALERT return self.code_return except Image.DoesNotExist as e: self.code_return = -1 request.session[ 'list_block_message'] = 'Error: No Existe imagen asociada a la serie. ' + e.message request.session['list_block_flag'] = FLAG_ALERT return self.code_return except Exception as e: self.code_return = -1 request.session['list_block_message'] = 'Error: ' + str(e) request.session['list_block_flag'] = FLAG_ALERT return self.code_return # CARGAR ASSETS if vgrabarypublicar == '1': vassets = decjson['Block']['assets'] for item in vassets: try: asset_id = item['asset_id'] vasset = Asset.objects.get(asset_id=asset_id) ph = PublishHelper() # Publica en PublishQueue # Eliminar cola de publicacion para el item en estado Queued ph.func_publish_queue(request, asset_id, vblock.language, 'AS', 'Q', vschedule_date) except Asset.DoesNotExist as e: self.code_return = -1 request.session[ 'list_block_message'] = 'Error: No existe Asset. ' + e.message request.session['list_block_flag'] = FLAG_ALERT return self.code_return vblock.queue_status = 'Q' vblock.save() ph = PublishHelper() ph.func_publish_queue(request, vblock.block_id, vblock.language, 'BL', 'Q', vblock.publish_date) self.code_return = 0 request.session['list_block_message'] = 'Guardado Correctamente.' request.session['list_block_flag'] = FLAG_SUCCESS return render(request, 'cawas/blocks/add.html') # Fin datos Bloque # Variables Para GET vblocks = Block.objects.all().order_by('name') vchannels = Channel.objects.all().order_by('name') vdevices = Device.objects.all().order_by('name') vgirls = Girl.objects.all().order_by('name') vlanguages = Language.objects.all() vmovies = Movie.objects.all().order_by('original_title') vcapitulos = Episode.objects.all().order_by('original_title') vseries = Serie.objects.all().order_by('original_title') countries = Country.objects.all().order_by('name') context = { 'message': message, 'vblocks': vblocks, 'vchannels': vchannels, 'vdevices': vdevices, 'vgirls': vgirls, 'vlanguages': vlanguages, 'vseries': vseries, 'vmovies': vmovies, 'vcapitulos': vcapitulos, 'countries': countries, 'block_type': BLOCK_TYPE } return render(request, 'cawas/blocks/add.html', context)
def add(self, request): # AUTENTICACION DE USUARIO if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) # ALTA - MOVIE GET debe cargar variables, # POST procesa solo la imagen, los datos se guaran # cawas/static/images/landscape/ cawas/static/images/portrait/ vflag = '' message = '' ph = PublishHelper() pathfilesport = '' pathfilesland = '' if request.method == 'POST': # DECLARACION DE OBJECTOS try: mv = Movie() vasset = Asset() img = Image() assetid = request.POST['movieID'] vasset = Asset.objects.get(asset_id=assetid) mv = Movie.objects.get(asset=vasset) base_dir = Setting.objects.get(code='dam_base_dir') pathfilesport = Setting.objects.get( code='image_repository_path_portrait') pathfilesland = Setting.objects.get( code='image_repository_path_landscape') img = Image.objects.get(name=vasset.asset_id) except Setting.DoesNotExist as e: request.session[ 'list_movie_message'] = "Error: No existe Setting (" + str( e.message) + ")" request.session['list_movie_flag'] = FLAG_ALERT self.code_return = -1 except Image.DoesNotExist as e: img = Image() img.name = vasset.asset_id # TRATAMIENTO DE IMAGEN Landscape if (request.FILES.has_key('ThumbHor')): if request.FILES['ThumbHor'].name != '': # TRATAMIENTO DE IMAGEN Landscape img.landscape = request.FILES['ThumbHor'] extension = os.path.splitext(img.landscape.name)[1] varchivo = pathfilesland.value + img.name + extension img.landscape.name = varchivo varchivo_server = base_dir.value + varchivo if os.path.isfile(varchivo_server): os.remove(varchivo_server) # IMAGEN Landscape if (request.FILES.has_key('ThumbVer')): if request.FILES['ThumbVer'].name != '': # Landscape img.portrait = request.FILES['ThumbVer'] extension = os.path.splitext(img.portrait.name)[1] varchivo = pathfilesport.value + img.name + extension img.portrait.name = varchivo # si existe archivo, lo borra varchivo_server = base_dir.value + varchivo if os.path.isfile(varchivo_server): os.remove(varchivo_server) img.save() mv.image = img mv.save() #La Imagen se publica siempre ph = PublishHelper() if ph.func_publish_image(request, img) == RETURN_ERROR: request.session[ 'list_movie_message'] = 'Error' + request.session['message'] request.session['list_movie_flag'] = FLAG_ALERT return RETURN_ERROR request.session['list_movie_message'] = 'Guardado Correctamente' request.session['list_movie_flag'] = FLAG_SUCCESS # CARGAR VARIABLES USADAS EN FRONT assets = Asset.objects.filter(asset_type="unknown") vmovies = Movie.objects.all().order_by('original_title') channels = Channel.objects.all().order_by('name') girls = Girl.objects.all().order_by('name') categories = Category.objects.all().order_by('original_name') countries = Country.objects.all().order_by('name') fatherassets = FatherAsset.objects.exclude(id=6).order_by('contract') vlanguages = Language.objects.all() title = 'Nueva Movie' context = { 'title': title, 'assets': assets, 'channels': channels, 'girls': girls, 'categories': categories, 'movies': vmovies, 'vlanguages': vlanguages, 'flag': vflag, 'message': message, 'countries': countries, 'fatherassets': fatherassets } return render(request, 'cawas/movies/add.html', context)
def add(self, request): # AUTENTICACION DE USUARIO if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) vgrabarypublicar = '0' # POST - Obtener datos del formulario y guardar la metadata if request.method == 'POST': # parsear JSON strjson = request.POST['varsToJSON'] print 'strjson:' + strjson decjson = json.loads( strjson.replace('\r', '\\r').replace('\n', '\\n')) print 'decjson:' + str(decjson) vimg = Image() operator = CableOperator() try: pathfilesland = Setting.objects.get( code='image_repository_path_landscape') api_key = Setting.objects.get(code='backend_api_key') co_url = Setting.objects.get(code='backend_co_url') base_dir = Setting.objects.get(code='dam_base_dir') print 'deb4' zones = PublishZone.objects.filter(enabled=True) operator.name = decjson['cableoperator']['name'] operator.phone = decjson['cableoperator']['phone'] operator.site = decjson['cableoperator']['site'] operator.country = Country.objects.get( id=decjson['cableoperator']['country_id']) vgrabarypublicar = decjson['cableoperator']['publicar'] operator.save() vimg.name = operator.cableoperator_id if (request.FILES.has_key('ThumbHor')): if request.FILES['ThumbHor'].name != '': # TRATAMIENTO DE IMAGEN Landscape vimg.landscape = request.FILES['ThumbHor'] extension = os.path.splitext(vimg.landscape.name)[1] varchivo = pathfilesland.value + vimg.name + extension vimg.landscape.name = varchivo varchivo_server = base_dir.value + varchivo if os.path.isfile(varchivo_server): os.remove(varchivo_server) vimg.save() #operator = CableOperator.objects.get(cableoperator_id=operator.cableoperator_id) #operator.update(image=vimg) operator.image = vimg operator.save() #Publicar en BKD self.publish(request, operator.id) except Setting.DoesNotExist as e: request.session[ 'list_CableOperator_message'] = "Error al Guardar CableOperator. (" + str( e.message) + ")" request.session['list_CableOperator_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return #except Exception as e: # request.session['list_CableOperator_message'] = "Error al Guardar CableOperator. (" + str(e.message) + ")" # request.session['list_CableOperator_flag'] = FLAG_ALERT # self.code_return = -1 # return self.code_return request.session[ 'list_CableOperator_message'] = 'Guardado Correctamente' request.session['list_CableOperator_flag'] = FLAG_SUCCESS #FIN DE POST if request.method == 'GET': # Cargar variables para presentar en templates countries = Country.objects.all() operators = CableOperator.objects.all().order_by('id') context = {'countries': countries, 'operators': operators} return render(request, 'cawas/cableoperators/add.html', context)
def edit(self, request, asset_id): # AUTENTICACION DE USUARIO if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) # CARGAR VARIABLES USADAS EN FRONT try: self.code_return = RETURN_OK vlangmetadata = [] flag = '' message = '' pathfilesport = '' pathfilesland = '' vmovie = Movie() vasset = Asset() imgport = '' imgland = '' vgirlselected = '' vgirlnotselected = '' title = 'Editar Movie' vasset = Asset.objects.get(asset_id=asset_id) vmovie = Movie.objects.get(asset=vasset) pathfilesport = Setting.objects.get( code='image_repository_path_portrait') pathfilesland = Setting.objects.get( code='image_repository_path_landscape') base_dir = Setting.objects.get(code='dam_base_dir') vmoviemetadata = MovieMetadata.objects.filter(movie=vmovie) vcategoryselected = vmovie.category.all().order_by('original_name') vcategorynotselected = Category.objects.exclude( id__in=vcategoryselected).order_by('original_name') languages = Language.objects.all() countries_selected = vmovie.asset.target_country.all().order_by( 'name') countries_notselected = Country.objects.exclude( id__in=countries_selected).order_by('name') assets = Asset.objects.filter(asset_type="unknown") channels = Channel.objects.all().order_by('name') girls = Girl.objects.all().order_by('name') fatherassets = FatherAsset.objects.exclude( id=6).order_by('contract') vgirlselected = vmovie.girls.all() vgirlnotselected = Girl.objects.exclude(id__in=vgirlselected) categories = Category.objects.all().order_by('original_name') languages = Language.objects.all() if vmovie.girls is not None: if vmovie.girls.count() > 0: vgirlselected = vmovie.girls.all().order_by('name') vgirlnotselected = Girl.objects.exclude( id__in=vgirlselected).order_by('name') # nuevo diccionario para completar lenguages y metadata for itemlang in languages: vmoviemetadata = None try: vmoviemetadata = MovieMetadata.objects.get( movie=vmovie, language=itemlang) vlangmetadata.append({ 'checked': True, 'code': itemlang.code, 'name': itemlang.name, 'title': vmoviemetadata.title, 'summary_short': vmoviemetadata.summary_short, 'summary_long': vmoviemetadata.summary_long, 'publish_date': vmoviemetadata.publish_date, 'keywords': vmoviemetadata.keywords_as_list }) except MovieMetadata.DoesNotExist as a: vlangmetadata.append({ 'checked': False, 'code': itemlang.code, 'name': itemlang.name, 'titulo': '', 'descripcion': '', 'fechapub': '', 'keywords': '' }) #imagenes if (vmovie.image is not None): i = len(vmovie.image.portrait.name) imgport = vmovie.image.portrait.name[5:i] if (vmovie.image is not None): i = len(vmovie.image.landscape.name) imgland = vmovie.image.landscape.name[5:i] # Post Movie - Graba datos if request.method == 'POST': # DECLARACION DE OBJECTOS try: img = Image() img = Image.objects.get(name=vasset.asset_id) except Image.DoesNotExist as e: img = Image() # IMAGEN Portrait if (request.FILES.has_key('ThumbHor')): print 'debug2' if request.FILES['ThumbHor'].name != '': # TRATAMIENTO DE IMAGEN Landscape img.landscape = request.FILES['ThumbHor'] extension = os.path.splitext(img.landscape.name)[1] varchivo = pathfilesland.value + img.name + extension img.landscape.name = varchivo varchivo_server = base_dir.value + varchivo if os.path.isfile(varchivo_server): os.remove(varchivo_server) # IMAGEN Landscape if (request.FILES.has_key('ThumbVer')): print 'debug1' if request.FILES['ThumbVer'].name != '': # Landscape img.portrait = request.FILES['ThumbVer'] extension = os.path.splitext(img.portrait.name)[1] varchivo = pathfilesport.value + img.name + extension img.portrait.name = varchivo # si existe archivo, lo borra varchivo_server = base_dir.value + varchivo if os.path.isfile(varchivo_server): os.remove(varchivo_server) img.save() vmovie.image = img vmovie.save() ph = PublishHelper() if ph.func_publish_image(request, img) == RETURN_ERROR: request.session[ 'list_movie_message'] = 'Error' + request.session[ 'message'] request.session['list_movie_flag'] = FLAG_ALERT return RETURN_ERROR request.session['list_movie_message'] = 'Guardado Correctamente' request.session['list_movie_flag'] = FLAG_SUCCESS context = { 'title': title, 'assets': assets, 'channels': channels, 'girls': girls, 'categories': categories, 'vmovie': vmovie, 'vgirlselected': vgirlselected, 'vgirlnotselected': vgirlnotselected, 'vcategoryselected': vcategoryselected, 'vcategorynotselected': vcategorynotselected, 'languages': languages, 'vmoviemetadata': vmoviemetadata, 'vlangmetadata': vlangmetadata, 'asset_id': asset_id, 'imgland': imgland, 'imgport': imgport, 'flag': flag, 'message': message, 'countries_selected': countries_selected, 'countries_notselected': countries_notselected, 'fatherassets': fatherassets } return render(request, 'cawas/movies/edit.html', context) except Setting.DoesNotExist as e: request.session[ 'list_movie_message'] = "Error: No existe Setting (" + str( e.message) + ")" request.session['list_movie_flag'] = FLAG_ALERT self.code_return = RETURN_ERROR return self.code_return except Asset.DoesNotExist as e: request.session[ 'list_movie_message'] = "Error: No existe Asset (" + str( e.message) + ")" request.session['list_movie_flag'] = FLAG_ALERT self.code_return = RETURN_ERROR except Movie.DoesNotExist as e: request.session[ 'list_movie_message'] = "Error: No existe Movie (" + str( e.message) + ")" request.session['list_movie_flag'] = FLAG_ALERT self.code_return = RETURN_ERROR return self.code_return except Category.DoesNotExist as e: request.session[ 'list_movie_message'] = "Error: No existe Categoria. (" + e.message + ")" request.session['list_movie_flag'] = FLAG_ALERT self.code_return = RETURN_ERROR return self.code_return except MovieMetadata.DoesNotExist as e: request.session[ 'list_movie_message'] = "Error: No existe MovieMetadata. (" + e.message + ")" request.session['list_movie_flag'] = FLAG_ALERT self.code_return = RETURN_ERROR return self.code_return
def edit(self, request, cableoperator_id): #AUTENTICACION DE USUARIO if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) #VARIABLES PARA GET - CARGA OPERADOR try: pathfilesland = Setting.objects.get( code='image_repository_path_landscape') api_key = Setting.objects.get(code='backend_api_key') co_url = Setting.objects.get(code='backend_co_url') base_dir = Setting.objects.get(code='dam_base_dir') zones = PublishZone.objects.filter(enabled=True) operator = CableOperator.objects.get( cableoperator_id=cableoperator_id) # carga imagenes i = len(operator.image.landscape.name) imgland = operator.image.landscape.name[5:i] countries = Country.objects.all() #Nuevo diccionario para completar lenguages y metadata except Setting.DoesNotExist as e: request.session[ 'list_CableOperator_message'] = "Error al Guardar Cable Operador. (" + e.message + ")" request.session['list_CableOperator_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return except CableOperator.DoesNotExist as e: request.session[ 'list_CableOperator_message'] = "Error al Guardar Cable Operador. (" + e.message + ")" request.session['list_CableOperator_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return if request.method == 'POST': # Parsear JSON strjson = request.POST['varsToJSON'] decjson = json.loads( strjson.replace('\r', '\\r').replace('\n', '\\n')) name = decjson['cableoperator']['name'] phone = decjson['cableoperator']['phone'] site = decjson['cableoperator']['site'] # Se mantiene la imagen actual try: operator = CableOperator.objects.get( cableoperator_id=cableoperator_id) vimg = operator.image except Asset.DoesNotExist as e: request.session[ 'list_CableOperator_message'] = "Error al Guardar Cable Operador. (" + e.message + ")" request.session['list_CableOperator_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return except Image.DoesNotExist as e: vimg = Image() if (request.FILES.has_key('ThumbHor')): if request.FILES['ThumbHor'].name != '': # TRATAMIENTO DE IMAGEN Landscape vimg.landscape = request.FILES['ThumbHor'] extension = os.path.splitext(vimg.landscape.name)[1] varchivo = pathfilesland.value + vimg.name + extension vimg.landscape.name = varchivo varchivo_server = base_dir.value + varchivo if os.path.isfile(varchivo_server): os.remove(varchivo_server) vimg.save() operator.image = vimg #Actualiza CableOperator operator.name = name operator.phone = phone operator.site = site operator.save() # Publicar en BKD #co_id = operator.cableoperator_id self.publish(request, operator.id) # Eliminar cola de publicacion para el item en estado Queued try: ph = PublishHelper() ph.func_publish_image(request, vimg) except Exception as e: request.session[ 'list_CableOperator_message'] = "Error al Guardar Imagen de Cable Operador. (" + str( e.message) + ")" request.session['list_CableOperator_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return request.session[ 'list_CableOperator_message'] = 'Guardado Correctamente' request.session['list_CableOperator_flag'] = FLAG_SUCCESS context = { 'operator': operator, 'imgland': imgland, 'countries': countries, 'imgland': imgland } # checks: return render(request, 'cawas/cableoperators/edit.html', context)
def edit(self, request, asset_id): # AUTENTICACION DE USUARIO if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) # VARIABLES LOCALES message = '' flag = '' publicar = 0 if request.method == 'POST': # VARIABLES vserie = Serie() vimg = Image() vasset = Asset() # Parsear JSON try: strjson = request.POST['varsToJSON'] decjson = json.loads( strjson.replace('\r', '\\r').replace('\n', '\\n')) vasset = Asset.objects.get(asset_id=asset_id) vserie = Serie.objects.get(asset=vasset) vimg = Image.objects.get(name=vasset.asset_id) pathfilesport = Setting.objects.get( code='image_repository_path_portrait') pathfilesland = Setting.objects.get( code='image_repository_path_landscape') base_dir = Setting.objects.get(code='dam_base_dir') except Exception as e: self.code_return = -1 print 'fallo json' request.session['list_serie_message'] = 'Error: ' + e.message request.session['list_serie_flag'] = FLAG_ALERT return self.code_return vimg.name = vasset.asset_id # IMAGEN Landscape if (request.FILES.has_key('ThumbHor')): if request.FILES['ThumbHor'].name != '': # TRATAMIENTO DE IMAGEN Landscape vimg.landscape = request.FILES['ThumbHor'] extension = os.path.splitext(vimg.landscape.name)[1] varchivo = pathfilesland.value + vimg.name + extension vimg.landscape.name = varchivo varchivo_server = base_dir.value + varchivo if os.path.isfile(varchivo_server): os.remove(varchivo_server) # IMAGEN Landscape if (request.FILES.has_key('ThumbVer')): if request.FILES['ThumbVer'].name != '': # Landscape vimg.portrait = request.FILES['ThumbVer'] extension = os.path.splitext(vimg.portrait.name)[1] varchivo = pathfilesport.value + vimg.name + extension vimg.portrait.name = varchivo # si existe archivo, lo borra varchivo_server = base_dir.value + varchivo if os.path.isfile(varchivo_server): os.remove(varchivo_server) vimg.save() # FIN IMAGEN publicar = int(decjson['Serie']['publicar']) # Datos de Serie vserie.asset = vasset vserie.original_title = decjson['Serie']['original_title'] vserie.year = decjson['Serie']['year'] if (decjson['Serie']['cast'] is not None): vserie.cast = decjson['Serie']['cast'] if (decjson['Serie']['directors'] is not None): vserie.directors = decjson['Serie']['directors'] vserie.image = vimg vserie.save() # CARGAR GIRLS vserie.girls = [] vserie.save() if (decjson['Serie']['girls'] is not None): vgirls = decjson['Serie']['girls'] for item in vgirls: try: g = Girl.objects.get(pk=item['girl_id']) vserie.girls.add(g) except Girl.DoesNotExist as e: self.code_return = -1 request.session[ 'list_serie_message'] = 'Error: ' + e.message request.session['list_serie_flag'] = FLAG_ALERT return self.code_return vserie.save() # CARGAR CATEGORIES vserie.category = [] vserie.save() vcategories = decjson['Serie']['categories'] for item in vcategories: try: vserie.category.add( Category.objects.get(pk=item['category_id'])) except Category.DoesNotExist as e: self.code_return = -1 request.session[ 'list_serie_message'] = 'Error: ' + e.message request.session['list_serie_flag'] = FLAG_ALERT return self.code_return vserie.asset.target_country = [] vserie.save() #!!!cuando se cambie countries, se debe actualizar los paises en los episodios que pertenecen a la serie!!! # CARGAR Countries al Asset if (decjson['Serie']['countries'] is not None): countries = decjson['Serie']['countries'] for item in countries: try: country = Country.objects.get(id=item['country_id']) vserie.asset.target_country.add(country) except Country.DoesNotExist as e: request.session[ 'list_serie_message'] = "Error: No Existe Pais (" + str( e.message) + ")" request.session['list_serie_flag'] = FLAG_ALERT self.code_return = -1 # Channel try: vserie.channel = Channel.objects.get( pk=decjson['Serie']['channel_id']) except Channel.DoesNotExist as e: self.code_return = -1 request.session['list_serie_message'] = 'Error: ' + e.message request.session['list_serie_flag'] = FLAG_ALERT return self.code_return vserie.save() message = 'Categoria - Registrado Correctamente' # BORRAR Y CREAR METADATA vseriemetadatas = decjson['Serie']['Seriemetadatas'] for item in vseriemetadatas: try: vlanguage = Language.objects.get( code=item['Seriemetadata']['language']) smd = SerieMetadata.objects.get(serie=vserie, language=vlanguage) except SerieMetadata.DoesNotExist as e: smd = SerieMetadata() except Language.DoesNotExist as e: self.code_return = -1 request.session[ 'list_serie_message'] = 'Error: ' + e.message request.session['list_serie_flag'] = FLAG_ALERT return self.code_return vschedule_date = datetime.datetime.now().strftime('%Y-%m-%d') smd.language = vlanguage smd.title = item['Seriemetadata']['title'] smd.summary_short = item['Seriemetadata']['summary_short'] smd.summary_long = item['Seriemetadata']['summary_long'] smd.keywords = item['Seriemetadata']['keywords'] smd.serie = vserie smd.publish_date = vschedule_date smd.queue_status = 'Q' smd.save() if publicar > 0: if (Episode.objects.filter(serie=vserie).count() > 0): ph = PublishHelper() ph.func_publish_queue(request, vserie.asset.asset_id, smd.language, 'AS', 'Q', vschedule_date) ph.func_publish_image(request, vimg) else: self.code_return = -1 request.session[ 'list_serie_message'] = 'No se puede Publicar Serie sin Episodios asignados ' request.session['list_serie_flag'] = FLAG_ALERT return self.code_return # Fin de POST flag = "success" self.code_return = 0 request.session['list_serie_message'] = 'Guardado Correctamente' request.session['list_serie_flag'] = FLAG_SUCCESS # VARIABLES PARA GET - CARGAR GIRL try: message = '' vlanguages = Language.objects.all() vgirls = Girl.objects.all() vcategories = Category.objects.all() vchannels = Channel.objects.all() vseries = Serie.objects.all() vasset = Asset.objects.get(asset_id=asset_id) vserie = Serie.objects.get(asset=vasset) vepisodes = Episode.objects.filter(serie=vserie) countries_selected = vserie.asset.target_country.all().order_by( 'name') countries_notselected = Country.objects.exclude( id__in=countries_selected).order_by('name') # carga imagenes i = len(vserie.image.portrait.name) imgport = vserie.image.portrait.name[5:i] i = len(vserie.image.landscape.name) imgland = vserie.image.landscape.name[5:i] vgirlselected = vserie.girls.all() vgirlnotselected = Girl.objects.exclude(id__in=vgirlselected) vcategoryselected = vserie.category.all() vcategorynotselected = Category.objects.exclude( id__in=vcategoryselected) # Nuevo diccionario para completar lenguages y metadata is_activated = SerieMetadata.objects.filter(serie=vserie, activated=True) vlangmetadata = [] for itemlang in vlanguages: vseriemetadata = None try: vseriemetadata = SerieMetadata.objects.get( serie=vserie, language=itemlang) vlangmetadata.append({ 'checked': True, 'code': itemlang.code, 'name': itemlang.name, 'title': vseriemetadata.title, 'summary_short': vseriemetadata.summary_short, 'summary_long': vseriemetadata.summary_long, 'keywords': vseriemetadata.keywords_as_list }) except SerieMetadata.DoesNotExist as a: vlangmetadata.append({ 'checked': False, 'code': itemlang.code, 'name': itemlang.name, 'title': '', 'summary_short': '', 'summary_long': '', 'keywords': '' }) except Exception as e: self.code_return = -1 request.session['list_serie_message'] = 'Error: ' + e.message request.session['list_serie_flag'] = FLAG_ALERT return self.code_return context = { 'message': message, 'vgirls': vgirls, 'vlanguages': vlanguages, 'vcategories': vcategories, 'vchannels': vchannels, 'vseries': vseries, 'vlangmetadata': vlangmetadata, 'vserie': vserie, 'imgport': imgport, 'imgland': imgland, 'vgirlnotselected': vgirlnotselected, 'vgirlselected': vgirlselected, 'vcategoryselected': vcategoryselected, 'vcategorynotselected': vcategorynotselected, 'vepisodes': vepisodes, 'countries_selected': countries_selected, 'countries_notselected': countries_notselected, 'message': message, 'is_activated': is_activated } return render(request, 'cawas/series/edit.html', context)
def add(self, request): # AUTENTICACION DE USUARIO if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) # VARIABLES LOCALES message = '' vschedule_date = '' if request.method == 'POST': # VARIABLES vepisode = Episode() try: pathfilesport = Setting.objects.get( code='image_repository_path_portrait') pathfilesland = Setting.objects.get( code='image_repository_path_landscape') base_dir = Setting.objects.get(code='dam_base_dir') # Parsear JSON strjson = request.POST['varsToJSON'] decjson = json.loads( strjson.replace('\r', '\\r').replace('\n', '\\n')) vasset_serie = Asset.objects.get( asset_id=decjson['Episode']['serie_id']) vepisode.serie = Serie.objects.get(asset=vasset_serie) #Validar siel episodio existe #buscar episodio con igual serie, chapter y temporada chapter = decjson['Episode']['chapter'] season = decjson['Episode']['season'] if Episode.objects.filter(chapter=chapter, season=season, serie=vasset_serie).count() > 0: request.session[ 'list_episode_message'] = 'Error: el numero de episodio ya existe para la Serie' request.session['list_episode_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return # DATOS OBLIGATORIOS vasset = Asset.objects.get( asset_id=decjson['Episode']['asset_id']) vasset.asset_type = "episode" vasset.save() vepisode.asset = vasset vepisode.original_title = decjson['Episode']['original_title'] vepisode.channel = Channel.objects.get( pk=decjson['Episode']['channel_id']) vepisode.display_runtime = decjson['Episode'][ 'display_runtime'] vepisode.chapter = decjson['Episode']['chapter'] vepisode.season = decjson['Episode']['season'] vgrabarypublicar = decjson['Episode']['publicar'] # Datos OPCIONALES if (decjson['Episode']['year'] is not None): vepisode.year = decjson['Episode']['year'] if (decjson['Episode']['cast'] is not None): vepisode.cast = decjson['Episode']['cast'] if (decjson['Episode']['directors'] is not None): vepisode.directors = decjson['Episode']['directors'] try: vimg = Image.objects.get(name=vasset.asset_id) except Image.DoesNotExist as e: vimg = Image() vimg.name = vasset.asset_id # IMAGEN Portrait if (request.FILES.has_key('ThumbHor')): if request.FILES['ThumbHor'].name != '': # TRATAMIENTO DE IMAGEN Landscape vimg.landscape = request.FILES['ThumbHor'] extension = os.path.splitext(vimg.landscape.name)[1] varchivo = pathfilesland.value + vimg.name + extension vimg.landscape.name = varchivo varchivo_server = base_dir.value + varchivo if os.path.isfile(varchivo_server): os.remove(varchivo_server) # IMAGEN Landscape if (request.FILES.has_key('ThumbVer')): if request.FILES['ThumbVer'].name != '': # Landscape vimg.portrait = request.FILES['ThumbVer'] extension = os.path.splitext(vimg.portrait.name)[1] varchivo = pathfilesport.value + vimg.name + extension vimg.portrait.name = varchivo # si existe archivo, lo borra varchivo_server = base_dir.value + varchivo if os.path.isfile(varchivo_server): os.remove(varchivo_server) vimg.save() vepisode.image = vimg vepisode.save() except Asset.DoesNotExist as e: request.session['list_episode_message'] = 'Error: ' + str( e.message) request.session['list_episode_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return except Setting.DoesNotExist as e: request.session['list_episode_message'] = 'Error: ' + str( e.message) request.session['list_episode_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return except Serie.DoesNotExist as e: request.session['list_episode_message'] = 'Error: ' + str( e.message) request.session['list_episode_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return except Image.DoesNotExist as e: request.session['list_episode_message'] = 'Error: ' + str( e.message) request.session['list_episode_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return except Language.DoesNotExist as e: request.session['list_episode_message'] = 'Error: ' + str( e.message) request.session['list_episode_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return except Channel.DoesNotExist as e: request.session['list_episode_message'] = 'Error: ' + str( e.message) request.session['list_episode_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return except Device.DoesNotExist as e: request.session['list_episode_message'] = 'Error: ' + str( e.message) request.session['list_episode_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return # CARGAR ASSETS if (decjson['Episode']['girls'] is not None): vgirls = decjson['Episode']['girls'] for item in vgirls: try: asset_id = item['girl_id'] print "AssetId add episode" + asset_id vgirl = Girl.objects.get(id=item['girl_id']) vepisode.girls.add(vgirl) except Girl.DoesNotExist as e: request.session[ 'list_episode_message'] = 'Error: ' + str( e.message) request.session['list_episode_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return except Asset.DoesNotExist as e: request.session[ 'list_episode_message'] = 'Error: ' + str( e.message) request.session['list_episode_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return # CARGAR CATEGORY vcategories = decjson['Episode']['categories'] for item in vcategories: try: category_id = item['category_id'] print "category_id add episode" + category_id vcategory = Category.objects.get(pk=category_id) vepisode.category.add(vcategory) except Category.DoesNotExist as e: request.session[ 'list_episode_message'] = 'No Existe Categoria ' + str( e.message) request.session['list_episode_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return #leer target_country de la serie a la que pertence el episodio #setear en el asset del episodio los mismos target_countries #countries = vepisode.serie.asset serie = vepisode.serie asset = serie.asset vepisode.save() vepisode.asset.target_country = [] vepisode.save() for item in vepisode.serie.asset.target_country.all(): vepisode.asset.target_country.add(item) vepisode.save() #SI hay items en estado Queued ph = PublishHelper() vepisodemetadata = decjson['Episode']['Episodemetadatas'] for item in vepisodemetadata: try: vlang = Language.objects.get( code=item['Episodemetadata']['language']) try: emd = EpisodeMetadata.objects.get(episode=vepisode, language=vlang) except EpisodeMetadata.DoesNotExist as e: emd = EpisodeMetadata() # convertDateYMDnowIsNull if (item['Episodemetadata']['schedule_date'] != ''): vschedule_date = datetime.datetime.strptime( item['Episodemetadata']['schedule_date'], '%d-%m-%Y').strftime('%Y-%m-%d') else: vschedule_date = datetime.datetime.now().strftime( '%Y-%m-%d') emd.language = vlang emd.title = item['Episodemetadata']['title'] emd.summary_short = item['Episodemetadata'][ 'summary_short'] emd.summary_long = item['Episodemetadata']['summary_long'] emd.keywords = item['Episodemetadata']['keywords'] #emd.publish_date = vschedule_date emd.episode = vepisode emd.save() # PUBLICAR METADATA if vgrabarypublicar == '1': try: # Publicar el Episodio emd.queue_status = True emd.save() ph = PublishHelper() ph.func_publish_queue(request, emd.episode.asset.asset_id, emd.language, 'AS', 'Q', vschedule_date) ph.func_publish_image(request, vimg) # Se vuelve a publicar la SERIE en el idioma del Episodio publicado if (PublishQueue.objects.filter( item_id=emd.episode.serie.asset.asset_id, status__in=['Q', 'D']).count() < 1): ph = PublishHelper() ph.func_publish_queue( request, vepisode.serie.asset.asset_id, vlang, 'AS', 'Q', vschedule_date) ph.func_publish_image(request, vepisode.serie.image) except EpisodeMetadata.DoesNotExist as e: self.code_return = -1 request.session[ 'list_episode_message'] = 'Error al Publicar el Episodio ' + e.message request.session['list_episode_flag'] = FLAG_ALERT return self.code_return except Exception as e: self.code_return = -1 request.session[ 'list_episode_message'] = 'Error al Republicar la SERIE' + e.message request.session['list_episode_flag'] = FLAG_ALERT return self.code_return except Language.DoesNotExist as e: request.session['list_episode_message'] = 'Error: ' + str( e.message) request.session['list_episode_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return request.session['list_episode_message'] = 'Guardado Correctamente' request.session['list_episode_flag'] = FLAG_SUCCESS vflag = "success" message = 'Guardado Correctamente' context = {"flag": vflag, 'message': message} return render(request, 'cawas/episodes/add.html', context) # Fin datos EPISODE # Variables Para GET vseries = Serie.objects.all() vchannels = Channel.objects.all() vcategories = Category.objects.all() vgirls = Girl.objects.all() vlanguages = Language.objects.all() vmovies = Movie.objects.all() vcapitulos = Episode.objects.all() vassets = Asset.objects.filter(asset_type="unknown") countries = Country.objects.all().order_by('name') context = { 'message': message, 'vcategories': vcategories, 'vchannels': vchannels, 'vgirls': vgirls, 'vlanguages': vlanguages, 'vseries': vseries, 'vmovies': vmovies, 'vcapitulos': vcapitulos, 'vassets': vassets, 'countries': countries, } return render(request, 'cawas/episodes/add.html', context)
def edit(self, request, asset_id): #AUTENTICACION DE USUARIO if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) #VARIABLES PARA GET - CARGAR GIRL try: message = '' flag = '' vlangmetadata = [] pathfilesport = Setting.objects.get( code='image_repository_path_portrait') pathfilesland = Setting.objects.get( code='image_repository_path_landscape') base_dir = Setting.objects.get(code='dam_base_dir') vasset = Asset.objects.get(asset_id=asset_id) vgirl = Girl.objects.get(asset=vasset) vtypegirl = {"pornstar": "Pornstar", "playmate": "Playmate"} vlanguages = Language.objects.all() # carga imagenes i = len(vgirl.image.portrait.name) imgport = vgirl.image.portrait.name[5:i] i = len(vgirl.image.landscape.name) imgland = vgirl.image.landscape.name[5:i] countries_selected = vgirl.asset.target_country.all().order_by( 'name') countries_notselected = Country.objects.exclude( id__in=countries_selected).order_by('name') #Nuevo diccionario para completar lenguages y metadata for itemlang in vlanguages: vgirlmetadata = None try: vgirlmetadata = GirlMetadata.objects.get(girl=vgirl, language=itemlang) vlangmetadata.append({ 'checked': True, 'code': itemlang.code, 'name': itemlang.name, 'description': vgirlmetadata.description, 'nationality': vgirlmetadata.nationality }) except GirlMetadata.DoesNotExist as a: vlangmetadata.append({ 'checked': False, 'code': itemlang.code, 'name': itemlang.name, 'description': '', 'nationality': '' }) except Setting.DoesNotExist as e: request.session[ 'list_girl_message'] = 'No existe Setting ' + e.message request.session['list_girl_flag'] = FLAG_ALERT return -1 except Girl.DoesNotExist as e: request.session[ 'list_girl_message'] = 'No existe Girl ' + e.message request.session['list_girl_flag'] = FLAG_ALERT return -1 except Asset.DoesNotExist as e: request.session[ 'list_girl_message'] = 'No existe Asset ' + e.message request.session['list_girl_flag'] = FLAG_ALERT return -1 except Category.DoesNotExist as e: request.session[ 'list_girl_message'] = 'No existe Categoria ' + e.message request.session['list_girl_flag'] = FLAG_ALERT return -1 except GirlMetadata.DoesNotExist as e: request.session[ 'list_girl_message'] = 'No existe Metadata de Categoria ' + e.message request.session['list_girl_flag'] = FLAG_ALERT return -1 if request.method == 'POST': #VARIABLES vasset = Asset() vgirl = Girl() # Parsear JSON strjson = request.POST['varsToJSON'] decjson = json.loads( strjson.replace('\r', '\\r').replace('\n', '\\n')) #print 'idioma' + request.GET['HTTP_ACCEPT_LANGUAGE'] # Leer GIRL desde AssetID try: vasset = Asset.objects.get( asset_id=decjson['Girl']['asset_id']) vgirl = Girl.objects.get(asset=vasset) #verificar imagen vimg = Image.objects.get(name=vasset.asset_id) except Asset.DoesNotExist as e: request.session[ 'list_girl_message'] = 'No existe Asset ' + e.message request.session['list_girl_flag'] = FLAG_ALERT return -1 except GirlMetadata.DoesNotExist as e: request.session[ 'list_girl_message'] = 'No existe Girl Metadata ' + e.message request.session['list_girl_flag'] = FLAG_ALERT return -1 except Image.DoesNotExist as e: vimg = Image() vimg.name = vasset.asset_id # IMAGEN Portrait if (request.FILES.has_key('ThumbHor')): if request.FILES['ThumbHor'].name != '': # TRATAMIENTO DE IMAGEN Landscape vimg.landscape = request.FILES['ThumbHor'] extension = os.path.splitext(vimg.landscape.name)[1] varchivo = pathfilesland.value + vimg.name + extension vimg.landscape.name = varchivo varchivo_server = base_dir.value + varchivo if os.path.isfile(varchivo_server): os.remove(varchivo_server) # IMAGEN Landscape if (request.FILES.has_key('ThumbVer')): if request.FILES['ThumbVer'].name != '': # Landscape vimg.portrait = request.FILES['ThumbVer'] extension = os.path.splitext(vimg.portrait.name)[1] varchivo = pathfilesport.value + vimg.name + extension vimg.portrait.name = varchivo # si existe archivo, lo borra varchivo_server = base_dir.value + varchivo if os.path.isfile(varchivo_server): os.remove(varchivo_server) vimg.save() # CARGAR Countries al Asset vgirl.asset.target_country = [] if (decjson['Girl']['countries'] is not None): countries = decjson['Girl']['countries'] for item in countries: try: country = Country.objects.get(id=item['country_id']) vgirl.asset.target_country.add(country) except Country.DoesNotExist as e: request.session[ 'list_girl_message'] = "Error: No Existe Pais (" + str( e.message) + ")" request.session['list_girl_flag'] = FLAG_ALERT self.code_return = -1 #Actualiza Girl try: vgirl.name = decjson['Girl']['name'] vgirl.type = decjson['Girl']['type_girl'] vgirl.birth_date = datetime.datetime.strptime( decjson['Girl']['birth_date'], '%d-%m-%Y').strftime('%Y-%m-%d') vgirl.height = decjson['Girl']['height'] vgirl.weight = decjson['Girl']['weight'] vgirl.image = vimg vgirl.save() except Exception as e: request.session[ 'list_girl_message'] = 'Error al Guardar Chica ' + e.message request.session['list_girl_flag'] = FLAG_ALERT return -1 # Eliminar cola de publicacion para el item en estado Queued ph = PublishHelper() #BORRAR Y CREAR METADATA vgirlmetadatas = decjson['Girl']['Girlmetadatas'] for item in vgirlmetadatas: vlanguage = Language.objects.get( code=item['Girlmetadata']['language']) try: gmd = GirlMetadata.objects.get(girl=vgirl, language=vlanguage) except GirlMetadata.DoesNotExist as e: gmd = GirlMetadata() vschedule_date = datetime.datetime.now().strftime('%Y-%m-%d') gmd.language = vlanguage gmd.description = item['Girlmetadata']['description'] gmd.nationality = item['Girlmetadata']['nationality'] #gmd.publish_date = vschedule_date gmd.girl = vgirl gmd.queue_status = 'Q' gmd.save() # Publica en PublishQueue ph = PublishHelper() ph.func_publish_queue(request, vasset.asset_id, vlanguage, 'AS', 'Q', vschedule_date) # Publica en PublishImage ph.func_publish_image(request, vimg) flag = 'success' message = 'Guardado Correctamente.' request.session['list_girl_message'] = 'Guardado Correctamente' request.session['list_girl_flag'] = FLAG_SUCCESS context = { 'vlanguages': vlanguages, 'vgirl': vgirl, 'vtypegirl': vtypegirl, 'vlangmetadata': vlangmetadata, 'imgport': imgport, 'imgland': imgland, 'flag': flag, 'message': message, 'countries_selected': countries_selected, 'countries_notselected': countries_notselected } # checks: return render(request, 'cawas/girls/edit.html', context)
def list(self, request): if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) usuario = request.user #Cuando hay una Des-publicacion se completa esta variable message = '' flag = '' registros = '' filter = False search = '' # Filtro de busqueda if request.GET.has_key('search'): search = request.GET.get('search') if search != '': #Si se completo el filtro print 'debug1' + str(search) registros = EpisodeMetadata.objects.filter( Q(episode__original_title__icontains=search) | Q(episode__asset__asset_id__icontains=search)).order_by( '-id') else: #Si filtro es nada print 'debug2' registros = EpisodeMetadata.objects.all().order_by('-id') else: #Si filtro no existe (vino de otra url), pregunto por cookie if 'search_episode' in request.COOKIES: search = request.COOKIES['search_episode'] registros = EpisodeMetadata.objects.filter( Q(episode__original_title__icontains=search) | Q(episode__asset__asset_id__icontains=search)).order_by( '-id') else: #si no existe cookie y no existe key en get registros = EpisodeMetadata.objects.all().order_by('-id') print 'registros' + str(registros) paginator = Paginator(registros, 25) page = request.GET.get('page') try: registros = paginator.page(page) except PageNotAnInteger: registros = paginator.page(1) except EmptyPage: registros = paginator.page(paginator.num_pages) if request.session.has_key('list_episode_message'): if request.session['list_episode_message'] != '': message = request.session['list_episode_message'] request.session['list_episode_message'] = '' if request.session.has_key('list_episode_flag'): if request.session['list_episode_flag'] != '': flag = request.session['list_episode_flag'] request.session['list_episode_flag'] = '' page = request.GET.get('page') #request.POST.get('page') episodes = EpisodeMetadata.objects.all().order_by('-id') episodes_sin_metadata = Episode.objects.all().exclude(id__in=episodes) context = { 'message': message, 'flag': flag, 'registros': registros, 'episodes_sin_metadata': episodes_sin_metadata, 'usuario': usuario, 'search': search } response = render(request, 'cawas/episodes/list.html', context) response.set_cookie('search_episode', search) return response
def add(self, request): if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) # VARIABLES LOCALES message = '' vflag = "" vasset = Asset() vslider = Slider() try: pathfilesland = Setting.objects.get(code='image_repository_path_landscape') pathfileslogo = Setting.objects.get(code='image_repository_path_logo') base_dir = Setting.objects.get(code='dam_base_dir') except Setting.DoesNotExist as e: message ='No existe Setting ' return render(request, 'cawas/error.html', {'code': 500, 'message': message}, status=500) #PROCESAMIENTO POST if request.method == 'POST': # VARIABLES try: vimg = Image() # Parsear JSON strjson = request.POST['varsToJSON'] decjson = json.loads(strjson.replace('\r','\\r').replace('\n','\\n')) vgrabarypublicar = decjson['Slider']['publicar'] if decjson['Slider']['asset_id'] is not None: if Asset.objects.filter(asset_id=decjson['Slider']['asset_id']).exists(): vasset = Asset.objects.get(asset_id=decjson['Slider']['asset_id']) vslider.asset = vasset else: vslider.asset = None vslider.media_type = decjson['Slider']['media_type'] vdevice = Device.objects.get(id=decjson['Slider']['target_device_id']) vslider.target_device = vdevice vslider.text = decjson['Slider']['text'] if decjson['Slider']['videoname'] is not None: vslider.video_name = decjson['Slider']['videoname'] if decjson['Slider']['linked_url'] is None: vslider.linked_url = '' else: vslider.linked_url = decjson['Slider']['linked_url'] vslider.language = Language.objects.get(code=decjson['Slider']['language']) vslider.save() vimg.name = vslider.slider_id if (request.FILES.has_key('ThumbHor')): if request.FILES['ThumbHor'].name != '': # TRATAMIENTO DE IMAGEN Landscape vimg.landscape = request.FILES['ThumbHor'] extension = os.path.splitext(vimg.landscape.name)[1] varchivo = pathfilesland.value + vimg.name + extension vimg.landscape.name = varchivo varchivo_server = base_dir.value + varchivo if os.path.isfile(varchivo_server): os.remove(varchivo_server) #LOGO if (request.FILES.has_key('logo')): if request.FILES['logo'].name != '': # TRATAMIENTO DE IMAGEN LOGO vimg.logo = request.FILES['logo'] extension = os.path.splitext(vimg.logo.name)[1] varchivo = pathfileslogo.value + vimg.name + extension vimg.logo.name = varchivo varchivo_server = base_dir.value + varchivo if os.path.isfile(varchivo_server): os.remove(varchivo_server) #/LOGO vimg.save() vslider.image = vimg vslider.save() # CARGAR Countries al Asset if (decjson['Slider']['countries'] is not None): countries = decjson['Slider']['countries'] for item in countries: try: country = Country.objects.get(id=item['country_id']) vslider.target_country.add(country) except Country.DoesNotExist as e: message = "Error: No Existe Pais (" + str(e.message) + ")" return render(request, 'cawas/error.html', {'code': 500, 'message': message}, status=500) if decjson['Slider']['text'] is None: vslider.text = '' else: vslider.text = decjson['Slider']['text'] if (decjson['Slider']['publish_date'] != ''): vschedule_date = datetime.datetime.strptime(decjson['Slider']['publish_date'],'%d-%m-%Y').strftime('%Y-%m-%d') else: vschedule_date = datetime.datetime.now().strftime('%Y-%m-%d') vslider.publish_date = vschedule_date vslider.queue_status = 'Q' vslider.save() vflag = "success" request.session['list_slider_message'] = 'Guardado Correctamente' request.session['list_slider_flag'] = FLAG_SUCCESS # PUBLICAR METADATA if vgrabarypublicar == '1': # preguntar si asset asociado NO esta activado, no publicar el Slider y mostrar mensaje, # se debe publicar asset asociado antes de publicar el slider ph = PublishHelper() ph.func_publish_queue(request, vslider.slider_id, vslider.language, 'SL', 'Q', vschedule_date) ph.func_publish_image(request, vslider.image) vflag = "success" request.session['list_slider_message'] = 'Guardado Correctamente en Cola de Publicacion' request.session['list_slider_flag'] = FLAG_SUCCESS except Exception as e: message = "Error al Guardar Slider. (" + str(e) + " )" return render(request, 'cawas/error.html', {'code':500, 'message':message}, status=500) vassets = Asset.objects.all() vsliders = Slider.objects.all() vlanguages = Language.objects.all() vdevices = Device.objects.all() vtypes = {"image": "Image", "video": "Video"} countries = Country.objects.all().order_by('name') context = {'message': message, 'flag': vflag, 'vtypes': vtypes, 'vassets': vassets, 'vsliders': vsliders, 'vlanguages': vlanguages, 'vdevices': vdevices, 'countries':countries} return render(request, 'cawas/sliders/add.html', context)
def add(self, request): # AUTENTICACION DE USUARIO if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) # VARIABLES LOCALES message = '' flag = '' vgrabarypublicar = '' if request.method == 'POST': # VARIABLES vserie = Serie() vimg = Image() vasset = Asset() vasset.asset_type = "serie" vasset.save() # Parsear JSON strjson = request.POST['varsToJSON'] decjson = json.loads( strjson.replace('\r', '\\r').replace('\n', '\\n')) try: pathfilesport = Setting.objects.get( code='image_repository_path_portrait') pathfilesland = Setting.objects.get( code='image_repository_path_landscape') base_dir = Setting.objects.get(code='dam_base_dir') except Setting.DoesNotExist as e: self.code_return = -1 request.session['list_serie_message'] = 'Error: ' + e.message request.session['list_serie_flag'] = FLAG_ALERT return self.code_return vimg.name = vasset.asset_id # IMAGEN Landscape if (request.FILES.has_key('ThumbHor')): if request.FILES['ThumbHor'].name != '': # TRATAMIENTO DE IMAGEN Landscape vimg.landscape = request.FILES['ThumbHor'] extension = os.path.splitext(vimg.landscape.name)[1] varchivo = pathfilesland.value + vimg.name + extension vimg.landscape.name = varchivo varchivo_server = base_dir.value + varchivo if os.path.isfile(varchivo_server): os.remove(varchivo_server) # IMAGEN Landscape if (request.FILES.has_key('ThumbVer')): if request.FILES['ThumbVer'].name != '': # Landscape vimg.portrait = request.FILES['ThumbVer'] extension = os.path.splitext(vimg.portrait.name)[1] varchivo = pathfilesport.value + vimg.name + extension vimg.portrait.name = varchivo # si existe archivo, lo borra varchivo_server = base_dir.value + varchivo if os.path.isfile(varchivo_server): os.remove(varchivo_server) vimg.save() # FIN IMAGEN # Datos de Serie vserie.asset = vasset vserie.original_title = decjson['Serie']['original_title'] vserie.year = decjson['Serie']['year'] if (decjson['Serie']['cast'] is not None): vserie.cast = decjson['Serie']['cast'] if (decjson['Serie']['directors'] is not None): vserie.directors = decjson['Serie']['directors'] vserie.image = vimg vserie.save() # CARGAR GIRLS if (decjson['Serie']['girls'] is not None): vgirls = decjson['Serie']['girls'] for item in vgirls: try: g = Girl.objects.get(pk=item['girl_id']) vserie.girls.add(g) except Girl.DoesNotExist as e: self.code_return = -1 request.session[ 'list_serie_message'] = 'Error: ' + e.message request.session['list_serie_flag'] = FLAG_ALERT return self.code_return # CARGAR CATEGORIES vcategories = decjson['Serie']['categories'] for item in vcategories: try: vserie.category.add( Category.objects.get(pk=item['category_id'])) except Category.DoesNotExist as e: self.code_return = -1 request.session[ 'list_serie_message'] = 'Error: ' + e.message request.session['list_serie_flag'] = FLAG_ALERT return self.code_return # CARGAR Countries al Asset if (decjson['Serie']['countries'] is not None): countries = decjson['Serie']['countries'] for item in countries: try: country = Country.objects.get(id=item['country_id']) vserie.asset.target_country.add(country) except Country.DoesNotExist as e: request.session[ 'list_serie_message'] = "Error: No Existe Pais (" + str( e.message) + ")" request.session['list_serie_flag'] = FLAG_ALERT self.code_return = -1 # Channel try: vserie.channel = Channel.objects.get( pk=decjson['Serie']['channel_id']) except Channel.DoesNotExist as e: self.code_return = -1 request.session['list_serie_message'] = 'Error: ' + e.message request.session['list_serie_flag'] = FLAG_ALERT return self.code_return vserie.save() message = 'Registrado Correctamente' # Fin datos serie # BORRAR Y CREAR METADATA vseriemetadatas = decjson['Serie']['Seriemetadatas'] for item in vseriemetadatas: smd = SerieMetadata() try: smd.language = Language.objects.get( code=item['Seriemetadata']['language']) vschedule_date = datetime.datetime.now().strftime( '%Y-%m-%d') smd.title = item['Seriemetadata']['title'] smd.summary_short = item['Seriemetadata']['summary_short'] smd.summary_long = item['Seriemetadata']['summary_long'] smd.keywords = item['Seriemetadata']['keywords'] smd.serie = vserie smd.publish_date = vschedule_date smd.queue_status = 'Q' smd.save() except Language.DoesNotExist as e: self.code_return = -1 request.session[ 'list_serie_message'] = 'Error No existe Lenguaje ' + e.message request.session['list_serie_flag'] = FLAG_ALERT return self.code_return flag = 'success' self.code_return = 0 request.session['list_serie_message'] = 'Guardado Correctamente' request.session['list_serie_flag'] = FLAG_SUCCESS # VARIABLES PARA GET - CARGAR GIRL try: message = '' vlanguages = Language.objects.all() vgirls = Girl.objects.all() vcategories = Category.objects.all() vchannels = Channel.objects.all() vseries = Serie.objects.all() countries = Country.objects.all().order_by('name') except Exception as e: self.code_return = -1 request.session['list_serie_message'] = 'Error: ' + e.message request.session['list_episode_flag'] = FLAG_ALERT return self.code_return context = { 'message': message, 'flag': flag, 'vgirls': vgirls, 'vlanguages': vlanguages, 'vcategories': vcategories, 'vchannels': vchannels, 'vseries': vseries, 'flag': flag, 'countries': countries } return render(request, 'cawas/series/add.html', context)
def unpublish(self, request, id): if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) try: girlmetadata = GirlMetadata.objects.get(id=id) vasset_id = girlmetadata.girl.asset.asset_id # 1 - VERIFICAR, si estado de publicacion esta en Q, se debe eliminar publishs = PublishQueue.objects.filter( item_id=vasset_id, status='Q', item_lang=girlmetadata.language) if publishs.count > 0: publishs.delete() # Buscar todas Movies con esa chica girl = girlmetadata.girl movies = Movie.objects.filter(girls__in=[girl]) for movie in movies: # Quitar la asocicacion de Chica-Movie movie.girls.remove(girl) movie.save() # Las movies modificadas, volver a publicarlas PublishQueue metadatas = MovieMetadata.objects.filter(movie=movie, activated=True) for metadata in metadatas: ph = PublishHelper() ph.func_publish_queue( request, movie.asset.asset_id, metadata.language, 'AS', 'Q', datetime.datetime.now().strftime('%Y-%m-%d')) print 'asset_id Despublicacion: ' + movie.asset.asset_id # Realizar delete al backend setting = Setting.objects.get(code='backend_asset_url') api_key = Setting.objects.get(code='backend_api_key') vzones = PublishZone.objects.filter(enabled=True) for zone in vzones: abr = ApiBackendResource(zone.backend_url, setting.value, api_key.value) param = { "asset_id": girlmetadata.girl.asset.asset_id, "asset_type": "girl", "lang": girlmetadata.language.code } #print 'param: ' + param abr.delete(param) # Actualizar Activated a False girlmetadata.activated = False girlmetadata.save() self.code_return = 0 request.session[ 'list_girl_message'] = 'Metadata en ' + girlmetadata.language.name + ' de Chica ' + girlmetadata.girl.asset.asset_id + ' Despublicado Correctamente' request.session['list_girl_flag'] = FLAG_SUCCESS except PublishZone.DoesNotExist as e: request.session[ 'list_girl_message'] = 'No existe PublishZone ' + e.message request.session['list_girl_flag'] = FLAG_ALERT return -1 except GirlMetadata.DoesNotExist as e: request.session[ 'list_girl_message'] = 'No existe Metadata de Chica ' + e.message request.session['list_girl_flag'] = FLAG_ALERT return -1 except ApiBackendException as e: request.session[ 'list_girl_message'] = 'Error al Despublicar ' + e.message request.session['list_girl_flag'] = FLAG_ALERT return -1 return self.code_return
def unpublish(self, request, id): if not request.user.is_authenticated: lc = LogController() return redirect(lc.login_view(request)) try: seriemetadata = SerieMetadata.objects.get(id=id) vasset_id = seriemetadata.serie.asset.asset_id # 1 - VERIFICAR, si estado de publicacion DE SERIE esta en Q, se debe eliminar if PublishQueue.objects.filter(item_id=vasset_id, status='Q').count() > 0: PublishQueue.objects.filter(item_id=vasset_id, status='Q').delete() # 2 - Realizar delete al backend de la Serie setting = Setting.objects.get(code='backend_asset_url') api_key = Setting.objects.get(code='backend_api_key') vzones = PublishZone.objects.filter(enabled=True) #despublica la serie for zone in vzones: abr = ApiBackendResource(zone.backend_url, setting.value, api_key.value) param = { "asset_id": seriemetadata.serie.asset.asset_id, "asset_type": "show", "lang": seriemetadata.language.code } abr.delete(param) #Obtener los episodios que pertenecen a esta serie #publicar nuevamente los episodes episodes = Episode.objects.filter(serie=seriemetadata.serie) for item in episodes: try: # Despublicar los episodios que tengan el mismo idioma que la serie. mde = EpisodeMetadata.objects.filter( episode=item, language=seriemetadata.language, activated=True) for episodemetadata in mde: # VERIFICAR SI estado de publicacion de EPISODE esta en Q, se debe eliminar if PublishQueue.objects.filter( item_id=episodemetadata.episode.asset.asset_id, status='Q').count() > 0: PublishQueue.objects.filter( item_id=episodemetadata.episode.asset.asset_id, status='Q').delete() for zone in vzones: abr = ApiBackendResource(zone.backend_url, setting.value, api_key.value) param = { "asset_id": episodemetadata.episode.asset.asset_id, "asset_type": "show", "lang": episodemetadata.language.code } abr.delete(param) episodemetadata.activated = False episodemetadata.save() except ApiBackendException as e: request.session[ 'list_serie_message'] = "Error al Despublicar Episodios en Backend(" + str( e.value) + ")" request.session['list_serie_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return except PublishQueue.DoesNotExist as e: request.session[ 'list_serie_message'] = "No existen PublishQueue para eliminar (" + str( e.value) + ")" request.session['list_serie_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return except Exception as e: request.session[ 'list_serie_message'] = "Error General al Despublicar Episodios(" + str( e.value) + ")" request.session['list_serie_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return # 3 - Actualizar Activated a False seriemetadata.activated = False seriemetadata.save() # esto es para que se actualice el campo "episodes" en el backend serie = seriemetadata.serie serie.save() self.code_return = 0 request.session['list_serie_message'] = 'Metadata ' + str( seriemetadata.id) + ' de Serie ' + str( seriemetadata.serie.asset.asset_id ) + ' Despublicado Correctamente' request.session['list_serie_flag'] = FLAG_SUCCESS except PublishZone.DoesNotExist as e: request.session[ 'list_serie_message'] = "No existe Publish Zone (" + str( e.value) + ")" request.session['list_serie_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return except SerieMetadata.DoesNotExist as e: request.session[ 'list_serie_message'] = "No Existe Metadata para Serie (" + str( e.value) + ")" request.session['list_serie_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return except ApiBackendException as e: request.session[ 'list_serie_message'] = "Error al despublicar Backend(" + str( e.value) + ")" request.session['list_serie_flag'] = FLAG_ALERT self.code_return = -1 return self.code_return
''' copyright @wangxiaojie 2020.01.17 author: wangxiaojie ''' import os, sys codePath = os.path.abspath(os.path.join(__file__, "..", "Code")) if os.path.exists(codePath): sys.path.append(codePath) from LogController import LogController from Logger import * if __name__ == "__main__": logRoot = os.path.abspath(os.path.join(__file__, "../log")) #指定日志存放的根路径 logController = LogController(logRoot) #使用根目录初始化日志控制器 logController.addLogger("socket", LOG_TYPE_DEBUG) #添加一个名为socket的日志控制类,记录DEBUG级别以上的日志 SocketLogger = logController.getLogger("socket") #获取socket的日志控制类 logController.addLogger( "monitor", LOG_TYPE_ERROR) #添加一个名为monitor的日志控制类,记录Error级别以上的日志 MonitorLogger = logController.getLogger("monitor") #获取monitor的日志控制类 SocketLogger.logDebug("hello socket %s, %s", "world", "debug man") #SocketLogger输出Debug日志 SocketLogger.logInfo("hello socket %s, %s", "world", "info man") #SocketLogger输出info日志 SocketLogger.logError("hello socket %s, %s", "world", "error man") #SocketLogger输出error日志 MonitorLogger.logDebug("hello monitor %s, %s", "world", "debug man") #MonitorLogger输出Debug日志 MonitorLogger.logInfo("hello monitor %s, %s", "world",