Ejemplo n.º 1
0
 /// <summary>
 /// reads the d2v file, which is essentially a text file
 /// the first few lines contain the video properties in plain text and the
 /// last line contains the film percentage
 /// this method reads all this information and stores it internally, then
 /// closes the d2v file again
 /// </summary>
 private void readFileProperties()
 {
     info = reader.VideoInfo.Clone();
     using (StreamReader sr = new StreamReader(fileName))
     {
         int    iLineCount = 0;
         string line       = null;
         while ((line = sr.ReadLine()) != null)
         {
             iLineCount++;
             if (iLineCount == 3)
             {
                 string strSourceFile = line;
                 if (File.Exists(strSourceFile))
                 {
                     MediaInfoFile oInfo = new MediaInfoFile(strSourceFile);
                     info.DAR = oInfo.VideoInfo.DAR;
                 }
             }
             if (line.IndexOf("Field_Operation") != -1)
             {
                 string fieldOp = line.Substring(16, 1);
                 this.fieldOperation = Int32.Parse(fieldOp);
             }
             else if (line.IndexOf("FINISHED") != -1 && line.IndexOf("FILM") != -1)                     // dgindex now reports VIDEO % if it's > 50%
             {
                 int    end        = line.IndexOf("%");
                 string percentage = line.Substring(10, end - 10);
                 this.filmPercentage = Double.Parse(percentage, System.Globalization.CultureInfo.InvariantCulture);
             }
         }
     }
 }
Ejemplo n.º 2
0
        private ManifestInfo GetManifest5Jobs(ManifestInfo manifestInfo, IAsset theAsset, IEnumerable <IAssetFile> mp4AssetFiles, string AssetLocatorPath)
        {
            SharedAccessBlobPermissions allAccess =
                SharedAccessBlobPermissions.Read |
                SharedAccessBlobPermissions.Write |
                SharedAccessBlobPermissions.Add |
                SharedAccessBlobPermissions.Create;

            foreach (var file in mp4AssetFiles.OrderBy(f => f.ContentFileSize))
            {
                VideoInformation video = CreateVideoInformationK28JobNode(file.Name, theAsset, AssetLocatorPath);
                manifestInfo.VideoInformation.Add(video);
                //Watermarked
                foreach (var code in manifestInfo.EnbebedCodes)
                {
                    var wmp4Name = System.Web.HttpUtility.UrlPathEncode(video.FileName);
                    code.MP4WatermarkedURL.Add(new MP4WatermarkedURL()
                    {
                        FileName       = video.FileName,
                        WaterMarkedMp4 = GetBlobSasUri(_AMSStorageBlobClient, "watermarked", $"{theAsset.Id}/{code.EmbebedCode}/{wmp4Name}", allAccess, _SASTTL)
                    });
                }
            }
            return(manifestInfo);
        }
Ejemplo n.º 3
0
        ///<summary>It prints all available metadata and options about target clip.</summary>
        ///<param name="video">Video to peek.</param>
        ///<param name="clearBefore">If true, the function will clear console before displaying list of data.</param>
        static void ShowAllInfo(VideoInformation video, bool clearBefore)
        {
            if (clearBefore)
            {
                Console.Clear();
            }

            Console.WriteLine("=== VIDEO DETAILS ===");
            Console.WriteLine("Title: " + video.Title);
            if (video.Author == "")
            {
                Console.WriteLine("Author: UNKNOWN");
            }
            else
            {
                Console.WriteLine("Author: " + video.Author);
            }
            if (video.Description == "")
            {
                Console.WriteLine("Description: NONE");
            }
            else
            {
                Console.WriteLine("Description: " + video.Description);
            }
            Console.WriteLine("Duration: " + video.Duration);
            Console.WriteLine("Thumbnail: " + video.Thumbnail);
            Console.WriteLine("Url: " + video.Url);
            link = video.Url;
            Options();
        }
Ejemplo n.º 4
0
        /// <summary>
        /// initializes the ffms reader
        /// </summary>
        /// <param name="fileName">the FFMSIndex source file file that this reader will process</param>
        /// <param name="indexFile">the FFMSIndex index file that this reader will process</param>
        public ffmsFile(string fileName, string indexFile)
        {
            string strScript = "";

            if (!String.IsNullOrEmpty(indexFile) && String.IsNullOrEmpty(fileName))
            {
                this.fileName = indexFile.Substring(0, indexFile.Length - 8);
                indexFile     = null;
            }
            else
            {
                this.fileName = fileName;
            }

            string strDLL = Path.Combine(Path.GetDirectoryName(MainForm.Instance.Settings.FFMSIndexPath), "ffms2.dll");

            strScript = "LoadPlugin(\"" + strDLL + "\")\r\nFFVideoSource(\"" + this.fileName + "\""
                        + (!string.IsNullOrEmpty(indexFile) ? ", cachefile=\"" + indexFile + "\"" : String.Empty)
                        + (MainForm.Instance.Settings.FFMSThreads > 0 ? ", threads=" + MainForm.Instance.Settings.FFMSThreads : String.Empty) + ")";
            reader = AvsFile.ParseScript(strScript);
            info   = reader.VideoInfo.Clone();
            if (File.Exists(this.fileName))
            {
                MediaInfoFile oInfo = new MediaInfoFile(this.fileName);
                info.DAR = oInfo.VideoInfo.DAR;
            }
        }
Ejemplo n.º 5
0
 public YoutubeVideo(VideoInformation info)
 {
     this.Info     = info;
     this.Title    = RemoveIllegalPathCharacters(info.Title);
     this.Url      = info.Url;
     this.Duration = info.Duration;
 }
        private void SearchVideosButton_Click(object sender, EventArgs e)
        {
            var searchContent = VideoSearchText.Text;

            Indexes       = AllIndexesOf(VideoInformation.Text, searchContent, IgnoreCaseSearch.Checked).ToList();
            indexesLength = searchContent.Length;
            if (Indexes.Any())
            {
                var firstIndex = Indexes[0];
                VideoInformation.SelectionStart  = firstIndex;
                VideoInformation.SelectionLength = searchContent.Length;
                VideoInformation.HideSelection   = false;
                VideoInformation.ScrollToCaret();
                prevIndex.Enabled = true;
                nextIndex.Enabled = true;
            }
            int sum          = 0;
            int videoMatches = 0;

            foreach (var video in Videos)
            {
                int amout = RegMatches(video.DisplayDescription, searchContent, IgnoreCaseSearch.Checked);
                if (amout > 0)
                {
                    sum += amout;
                    videoMatches++;
                }
            }

            MessageBox.Show($"Found {sum} occurrences of {searchContent} in {videoMatches}/{Videos.Count} videos");
            LogMessage($"Found {sum} occurrences of {searchContent} in {videoMatches}/{Videos.Count} videos");
        }
Ejemplo n.º 7
0
        /// <summary>
        /// initializes the ffms reader
        /// </summary>
        /// <param name="fileName">the FFMSIndex source file file that this reader will process</param>
        /// <param name="indexFile">the FFMSIndex index file that this reader will process</param>
        public ffmsFile(string fileName, string indexFile)
        {
            if (!String.IsNullOrEmpty(indexFile) && String.IsNullOrEmpty(fileName))
            {
                this.fileName = indexFile.Substring(0, indexFile.Length - 8);
                indexFile     = null;
            }
            else
            {
                this.fileName = fileName;
            }

            double        fps   = 0;
            MediaInfoFile oInfo = null;

            if (File.Exists(this.fileName))
            {
                oInfo = new MediaInfoFile(this.fileName);
                if (oInfo.VideoInfo.HasVideo && oInfo.VideoInfo.FPS > 0)
                {
                    fps = oInfo.VideoInfo.FPS;
                }
            }

            reader = AvsFile.ParseScript(VideoUtil.getFFMSVideoInputLine(this.fileName, indexFile, fps), true);
            info   = reader.VideoInfo.Clone();
            if (oInfo != null)
            {
                info.DAR = oInfo.VideoInfo.DAR;
            }
        }
Ejemplo n.º 8
0
        public async Task fmytSearchAsync(params string[] searchterms)
        {
            if (searchterms.Length < 1)
            {
                await ReplyAsync("Please enter a searchvalue.").ConfigureAwait(false);

                return;
            }

            string querystring = string.Join(" ", searchterms);

            try
            {
                VideoInformation youtubeResult = _youtubeService.GetSearchResult(querystring);

                await ReplyAsync(youtubeResult.Url).ConfigureAwait(false);

                this._logger.LogCommandUsed(Context.Guild?.Id, Context.Channel.Id, Context.User.Id, Context.Message.Content);
            }
            catch (Exception e)
            {
                _logger.LogException(Context.Message.Content, e);
                await ReplyAsync("No results have been found for this track.").ConfigureAwait(false);
            }
        }
Ejemplo n.º 9
0
        public ExtendMedia ParseExtendMedia(JObject obj)
        {
            var extendMedia = new ExtendMedia
            {
                ID            = obj["id"].ToObject <long>(),
                Indices       = ParseIndices(obj["indices"].ToObject <JArray>()),
                MediaURL      = obj["media_url"].ToString(),
                MediaURLHttps = obj["media_url_https"].ToString(),
                URL           = ParseURL(obj),
                Type          = obj["type"].ToString()
            };

            if (obj.ContainsKey("video_info"))
            {
                var infoObj = obj["video_info"].ToObject <JObject>();
                var info    = new VideoInformation
                {
                    AspectRatio = ParseIndices(infoObj["aspect_ratio"].ToObject <JArray>()),
                    //animated_gif doesn't have duration_millis data
                    Duration = SafeGetLong(infoObj, "duration_millis")
                };
                var variantArray = infoObj["variants"].ToObject <JArray>();
                info.Variants = ParseArray(variantArray, ParseVideoVariant);

                extendMedia.Video = info;
            }

            return(extendMedia);
        }
Ejemplo n.º 10
0
        private AvsFile(string script, bool parse)
        {
            try
            {
                this.enviroment = new AviSynthScriptEnvironment();
                this.clip       = parse ? enviroment.ParseScript(script, AviSynthColorspace.RGB24) : enviroment.OpenScriptFile(script, AviSynthColorspace.RGB24);

                checked
                {
                    if (clip.HasVideo)
                    {
                        ulong width  = (ulong)clip.VideoWidth;
                        ulong height = (ulong)clip.VideoHeight;
                        info = new VideoInformation(
                            clip.HasVideo, width, height,
                            new Dar(clip.GetIntVariable("MeGUI_darx", -1),
                                    clip.GetIntVariable("MeGUI_dary", -1),
                                    width, height),
                            (ulong)clip.num_frames,
                            ((double)clip.raten) / ((double)clip.rated),
                            clip.raten, clip.rated);
                    }
                    else
                    {
                        info = new VideoInformation(false, 0, 0, Dar.A1x1, (ulong)clip.SamplesCount, (double)clip.AudioSampleRate, 0, 0);
                    }
                }
            }
            catch (Exception)
            {
                cleanup();
                throw;
            }
        }
        internal void SetVideoInformation(string p)
        {
            VideoInformation vi = VideoInformationRetrieval.VideoInformationRetrieval.GetVideoInformation(FilePath);

            durationLabel.Content   = duration + (vi.duration.Minutes < 10 ? "0" + vi.duration.Minutes : vi.duration.Minutes.ToString()) + ":" + (vi.duration.Seconds < 10 ? "0" + vi.duration.Seconds : vi.duration.Seconds.ToString());
            framesPerSecond.Content = framesSecond + vi.frameRate;
        }
Ejemplo n.º 12
0
        private VideoInformation CreateVideoInformationK28JobNode(string FileName, string AssetID, string AssetLocatorPath)
        {
            VideoInformation videoinfo = new VideoInformation()
            {
                FileName = FileName
            };
            var EncodeFileName = System.Web.HttpUtility.UrlPathEncode(videoinfo.FileName);

            IActionsProvider xman = ActionProviderFactory.GetActionProvider();
            var assetStatus       = xman.GetAssetStatus(AssetID);

            if (assetStatus.State == ExecutionStatus.Finished)
            {
                videoinfo.MP4URL = "";
            }
            else
            {
                videoinfo.MP4URL = $"{AssetLocatorPath}{EncodeFileName}";
            }

            videoinfo.MMRKURL = GetBlobSasUri("mmrkrepo", $"{AssetID}/{EncodeFileName}.mmrk");

            //Update GOP, Bitrate and Video filter
            return(ParseGopBitrateFilter(videoinfo));
        }
        // POST: /api/videos
        public async Task <HttpResponseMessage> Post()
        {
            if (!Request.Content.IsMimeMultipartContent("form-data"))
            {
                throw new HttpResponseException(HttpStatusCode.NotAcceptable);
            }

            var streamProvider = new MultipartMemoryStreamProvider();
            var provider       = await Request.Content.ReadAsMultipartAsync(streamProvider);

            var videoInf         = VideoInformation.Parse(provider.Contents);
            var validationErrors = videoInf.GetErrors();
            var isValid          = !validationErrors.Any();

            if (isValid)
            {
                var video =
                    await
                    this.service.CreateVideoAsync(
                        videoInf.Title,
                        videoInf.Description,
                        videoInf.FileInformation.Name,
                        videoInf.FileInformation.Type,
                        await videoInf.FileInformation.Data.ReadAsStreamAsync());

                return(Request.CreateResponse(HttpStatusCode.Created, video));
            }
            else
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, string.Join("\n", validationErrors)));
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Moves the downloaded file to the downloads folder of the windows user.
        /// </summary>
        /// <param name="videoInfo"></param>
        private void MoveFileToDownloadsFolder(VideoInformation videoInfo)
        {
            try
            {
                var downloadsFolder = KnownFolders.GetPath(KnownFolder.Downloads);
                if (File.Exists($"{downloadsFolder}\\{videoInfo.FileName}"))
                {
                    Console.WriteLine($"{videoInfo.FileName} already exists within your Download Folder.");
                    Console.WriteLine($"Would you like to overwrite it? (y/n)");

                    if (ApplicationNavigation.DetermineYesOrNo())
                    {
                        File.Move(videoInfo.SourceLocation, downloadsFolder, true);
                    }
                    else
                    {
                        Console.WriteLine("Would you like to restart? (y/n)");
                        if (ApplicationNavigation.DetermineYesOrNo())
                        {
                            Console.Clear();
                            ApplicationNavigation.StartApplicationProcess();
                        }
                        else
                        {
                            ApplicationNavigation.CloseApplication(10);
                        }
                    }
                }
            }
            catch (IOException ioException)
            {
                Console.WriteLine(ioException.Message);
                throw;
            }
        }
Ejemplo n.º 15
0
        private string SearchVideo(string search)
        {
            VideoSearch      items      = new VideoSearch();
            List <Video>     list       = new List <Video>();
            VideoInformation firstVideo = items.SearchQuery(search, 1).FirstOrDefault();

            return(firstVideo.Url);
        }
Ejemplo n.º 16
0
        private void SkinListBox_MouseDoubleClick_1(object sender, MouseButtonEventArgs e)
        {
            ListBox lb = sender as ListBox;

            VideoInformation vi = lb.SelectedItem as VideoInformation;

            System.Diagnostics.Process.Start(vi.Url);
        }
Ejemplo n.º 17
0
 public MontageModel(int totalLength)
 {
     Chunks = new StreamChunksArray(totalLength);
     Borders = new List<Border>();
     Information = new VideoInformation();
     SoundIntervals = new List<SoundInterval>();
     SubtitleFixes = new List<SubtitleFix>();
 }
Ejemplo n.º 18
0
 /// <summary>
 /// sets all properties given from input
 /// </summary>
 /// <param name="info">VideoInformation object, usually gathered from YT Query-search</param>
 public VideoData(VideoInformation info)
 {
     Title       = info.Title;
     Url         = info.Url;
     ImageUrl    = info.Thumbnail;
     Duration    = info.Duration;
     Description = info.Description;
     Author      = info.Author;
 }
Ejemplo n.º 19
0
        /// <summary>
        /// initializes the lsmash reader
        /// </summary>
        /// <param name="fileName">the LSMASHIndex source file file that this reader will process</param>
        /// <param name="indexFile">the LSMASHIndex index file that this reader will process</param>
        public lsmashFile(string fileName, string indexFile)
        {
            MediaInfoFile oInfo = null;

            reader = AvsFile.ParseScript(VideoUtil.getLSMASHVideoInputLine(fileName, indexFile, 0, ref oInfo), true);
            info   = reader.VideoInfo.Clone();
            if (oInfo != null)
            {
                info.DAR = oInfo.VideoInfo.DAR;
            }
        }
Ejemplo n.º 20
0
        private VideoInformation ParseGopBitrateFilter(VideoInformation xVideo)
        {
            string partialName = xVideo.FileName.Substring(xVideo.FileName.LastIndexOf('_') + 1);

            xVideo.vbitrate    = partialName.Substring(0, partialName.IndexOf('.'));
            partialName        = xVideo.FileName.Substring(0, xVideo.FileName.LastIndexOf('_'));
            partialName        = partialName.Substring(partialName.LastIndexOf('_') + 1);
            xVideo.videoFilter = $"resize:width={partialName.Substring(0, partialName.IndexOf('x'))},height={partialName.Substring(partialName.IndexOf('x') + 1)}";
            //GOP Size fix from configuration;
            xVideo.gopsize = System.Configuration.ConfigurationManager.AppSettings["gopsize"];
            return(xVideo);
        }
Ejemplo n.º 21
0
        private void searchButton_Click(object sender, RoutedEventArgs e)
        {
            VideoSearch vs = new VideoSearch();

            string query = searchTextBox.Text;

            // Make the query
            List <VideoInformation> vlist = vs.SearchQuery(query, 1);

            // Bind vlist to the listbox.
            SkinListBox.ItemsSource = vlist;
            VideoInformation v = new VideoInformation();
        }
Ejemplo n.º 22
0
 public Song(VideoInformation video, Guid userId)
 {
     Title         = video.Title;
     Author        = video.Author;
     Description   = video.Description;
     Duration      = video.Duration;
     Url           = video.Url;
     Thumbnail     = video.Thumbnail;
     NoAuthor      = video.NoAuthor;
     NoDescription = video.NoDescription;
     ViewCount     = video.ViewCount;
     AddedByUser   = userId;
 }
        public static VideoInformation GetVideoInformation(string filePath)
        {
            VFR.Open(filePath);

            VideoInformation vi = new VideoInformation()
            {
                frameRate = VFR.FrameRate,
                frames    = VFR.FrameCount,
                duration  = TimeSpan.FromSeconds((double)VFR.FrameCount / VFR.FrameRate)
            };

            return(vi);
        }
Ejemplo n.º 24
0
        public async Task <ActionResult> Create([Bind(Include = "Asset")] AddAssetViewModel model)
        {
            if (ModelState.IsValid)
            {
                var selectedApplication = await db.Applications.FirstAsync(app => app.Id == model.Asset.Application.Id);

                model.Asset.Application = selectedApplication;
                selectedApplication.Assets.Add(model.Asset);
                db.Assets.Add(model.Asset);
                await db.SaveChangesAsync();

                // download the selected file
                var client = await EnsureSharePointClientCreatedAsync();

                using (var stream = await client.Files.GetById(model.Asset.RawUrl).ToFile().DownloadAsync())
                {
                    // and copy it to the destination storage account
                    var storageAccount =
                        CloudStorageAccount.Parse(
                            @"DefaultEndpointsProtocol=https;AccountName=wchstorage;AccountKey=3eEeXTV0hn/sdYEyQQ5fMS6HMrLBZP6Fdm4EStxV+ySCWeUJLCYFddxQYTaDUZn+zZtdkud+JyRAu32kuYwpeA==;BlobEndpoint=https://wchstorage.blob.core.windows.net/;TableEndpoint=https://wchstorage.table.core.windows.net/;QueueEndpoint=https://wchstorage.queue.core.windows.net/;FileEndpoint=https://wchstorage.file.core.windows.net/");
                    var blobclient = storageAccount.CreateCloudBlobClient();
                    var container  = blobclient.GetContainerReference("rawvideos");
                    var blockblob  = container.GetBlockBlobReference(string.Format("{0}.mp4", model.Asset.RawUrl));

                    await blockblob.UploadFromStreamAsync(stream);
                }
                // queue a message for further processing


                ConnectionStringSettings connectionString = ConfigurationManager.ConnectionStrings["AzureWebJobsStorage"];
                CloudStorageAccount      storageAccount2  =
                    CloudStorageAccount.Parse(connectionString.ConnectionString);
                CloudQueueClient queueClient = storageAccount2.CreateCloudQueueClient();

                CloudQueue queue = queueClient.GetQueueReference("videoqueue");

                queue.CreateIfNotExists();

                VideoInformation videoInformation = new VideoInformation();
                videoInformation.Uri = new Uri(model.Asset.RawUrl + ".mp4");
                videoInformation.Id  = Guid.NewGuid();

                CloudQueueMessage message = new CloudQueueMessage(JsonConvert.SerializeObject(videoInformation));
                queue.AddMessage(message);

                return(RedirectToAction("Index"));
            }

            return(View(model));
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Logic to handle the inputs from the user to determine the video we're going to download for them.
        /// </summary>
        /// <returns></returns>
        public static void StartApplicationProcess()
        {
            VideoInfo = new VideoInformation();
            while (true)
            {
                Console.WriteLine($"===========================================================================");
                Console.WriteLine("                  Application developed by Coaction.                        ");
                Console.WriteLine("        Currently Supported: Youtube, TwitchClips and Streamable            ");
                Console.WriteLine($"===========================================================================");
                Console.WriteLine("\n");
                Console.WriteLine("Enter the URL of the video you'd like to download.");

                VideoInfo.VideoUrl = Console.ReadLine() ?? "";
                var validateHyperlink = Uri.TryCreate(VideoInfo.VideoUrl, UriKind.Absolute, out var uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
                if (!validateHyperlink)
                {
                    Console.Clear();
                    Console.WriteLine("Entry not a valid website. Enter a valid web address.");
                    Console.WriteLine("\n");
                    continue;
                }

                Console.WriteLine("\nEnter the name of the video you'd like to download. Do not provide a file extension.");
                VideoInfo.FileName = $"{Console.ReadLine()}";
                Console.WriteLine("\nLocating video to download. This can take some time..");
                var downloadManager = new VideoDownloadManager(VideoInfo);

                switch (uriResult.Host)
                {
                case "www.youtube.com":
                    downloadManager.DownloadStreamableVideo(VideoSource.Youtube);
                    break;

                case "streamable.com":
                    downloadManager.DownloadStreamableVideo(VideoSource.Streamable);
                    break;

                case "www.twitch.tv":
                    downloadManager.DownloadStreamableVideo(VideoSource.TwitchClip);
                    break;

                default:
                    Console.WriteLine($"{uriResult.Host} isn't currently supported.");
                    DetermineRetryApplication();
                    break;
                }
                break;
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// initializes the lsmash reader
        /// </summary>
        /// <param name="fileName">the LSMASHIndex source file file that this reader will process</param>
        /// <param name="indexFile">the LSMASHIndex index file that this reader will process</param>
        public lsmashFile(string fileName, string indexFile)
        {
            if (!String.IsNullOrEmpty(indexFile) && String.IsNullOrEmpty(fileName))
            {
                using (StreamReader sr = new StreamReader(indexFile, System.Text.Encoding.Default))
                {
                    string line = null;
                    while ((line = sr.ReadLine()) != null)
                    {
                        if (line.StartsWith("<InputFilePath>"))
                        {
                            string strSourceFile = line.Substring(15, line.LastIndexOf("</InputFilePath>") - 15);
                            if (File.Exists(strSourceFile))
                            {
                                this.fileName = strSourceFile;
                            }
                            break;
                        }
                    }
                }
            }
            else
            {
                this.fileName = fileName;
            }

            double        fps   = 0;
            MediaInfoFile oInfo = null;

            if (File.Exists(this.fileName))
            {
                oInfo = new MediaInfoFile(this.fileName);
                if (oInfo.VideoInfo.HasVideo && oInfo.VideoInfo.FPS > 0)
                {
                    fps = oInfo.VideoInfo.FPS;
                }
            }

            reader = AvsFile.ParseScript(VideoUtil.getLSMASHVideoInputLine(this.fileName, indexFile, fps));
            info   = reader.VideoInfo.Clone();
            if (oInfo != null)
            {
                info.DAR = oInfo.VideoInfo.DAR;
            }
        }
Ejemplo n.º 27
0
        public async Task fmytAsync(IUser user = null)
        {
            Data.Entities.User userSettings = await _userService.GetUserSettingsAsync(Context.User);

            if (userSettings == null || userSettings.UserNameLastFM == null)
            {
                await ReplyAsync("Your LastFM username has not been set. Please set your username using the `.fmset 'username' 'embedfull/embedmini/textfull/textmini'` command.").ConfigureAwait(false);

                return;
            }

            try
            {
                LastTrack track = await _lastFmService.GetLastScrobbleAsync(userSettings.UserNameLastFM).ConfigureAwait(false);

                if (track == null)
                {
                    await ReplyAsync("No scrobbles found on your LastFM profile. (" + userSettings.UserNameLastFM + ")").ConfigureAwait(false);

                    return;
                }

                try
                {
                    string querystring = track.Name + " - " + track.ArtistName;

                    VideoInformation youtubeResult = _youtubeService.GetSearchResult(querystring);

                    await ReplyAsync($"Searched for: `{querystring}`\n " +
                                     youtubeResult.Url).ConfigureAwait(false);

                    this._logger.LogCommandUsed(Context.Guild?.Id, Context.Channel.Id, Context.User.Id, Context.Message.Content);
                }
                catch (Exception e)
                {
                    _logger.LogException(Context.Message.Content, e);
                    await ReplyAsync("No results have been found for this track.").ConfigureAwait(false);
                }
            }
            catch (Exception e)
            {
                _logger.LogException(Context.Message.Content, e);
                await ReplyAsync("Unable to show Last.FM info via YouTube due to an internal error. Try setting a Last.FM name with the 'fmset' command, scrobbling something, and then use the command again.").ConfigureAwait(false);
            }
        }
Ejemplo n.º 28
0
        private IMessageActivity MessageReceivedAsync_Musica(IDialogContext context, String busqueda, String profile, DoWorkEventArgs e, String calidad)
        {
            //Creamos un mensaje que se le enivará al usuario
            IMessageActivity mensajeDelAdjunto = context.MakeMessage();

            try
            {
                //Creamos el objeto Buscador encargado de buscar y descargar
                Buscador buscador = new Buscador(busqueda, 1, ref context);

                //Buscamos y cargamos el/los videos
                VideoInformation urlVideoEncontrado = buscador.BuscarVideos();

                //Obtenemos la ruta donde se ha descargado de manera temporal el mp3
                String rutaDelMP3 = buscador.DescargarVideo(urlVideoEncontrado.Url, calidad, true);

                //Creamos el adjunto con la ruta y la url del vídeo
                Attachment adjunto = Dialogos.AdjuntarAudio(rutaDelMP3, urlVideoEncontrado);

                //Ahora añadimos nuestros adjuntos al mensaje
                mensajeDelAdjunto.Attachments = new List <Attachment> {
                    adjunto
                };

                ArrayList listaArgumentos = new ArrayList {
                    adjunto
                };
                BackgroundWorker bw_DDelMusica = new BackgroundWorker                        //Creamos una tarea en segundo plano
                {
                    WorkerSupportsCancellation = true                                        //Permitimos que se pueda cancelar con bw.CancelAsync()
                };
                bw_DDelMusica.DoWork += bw_DDelMusica_IniciarTarea;                          //Definimos cual es el método que iniciará la tarea
                bw_DDelMusica.RunWorkerAsync(listaArgumentos);
                mensajeDelAdjunto.Text = Dialogos.msg_DescargaMensaje;                       //Mandamos iniciar la tarea mandandole nuestra lista de argumentos

                return(mensajeDelAdjunto);
            }
            catch
            {
                //En caso de producirse un error en la descarga o conversión
                mensajeDelAdjunto.Text = Dialogos.msg_ErrorDescargaAudio;
            }

            return(mensajeDelAdjunto);
        }
        public VideoInformation GetVideoInformation(string filePath)
        {
            VideoFileReader VFR = new VideoFileReader();

            VFR.Open(filePath);

            VideoInformation vi = new VideoInformation()
            {
                frameRate = VFR.FrameRate,
                frames    = VFR.FrameCount,
                duration  = TimeSpan.FromSeconds((double)VFR.FrameCount / VFR.FrameRate)
            };

            VFR.Close();
            VFR.Dispose();

            return(vi);
        }
Ejemplo n.º 30
0
        //Adjunta un archivo de audio
        public static Attachment AdjuntarAudio(String ruta, VideoInformation video)
        {
            /*var audioCard = new AudioCard
             * {
             *  Title = video.Title,
             *  Shareable = true,
             *  Subtitle = video.Author + video.Duration,
             *  Text = video.Description,
             *  Image = new ThumbnailUrl
             *  {
             *      Url = video.Thumbnail
             *  },
             *  Media = new List<MediaUrl>
             * {
             * new MediaUrl()
             * {
             *  Url = "https://weedmebot.azurewebsites.net/temp/"+ruta
             * }
             * },
             *  Buttons = new List<CardAction>
             * {
             * new CardAction()
             * {
             *  Title = "Ver la versión en vídeo",
             *  Type = ActionTypes.OpenUrl,
             *  Value = video.Url
             * }
             * }
             * };
             *
             * return audioCard.ToAttachment();*/



            Attachment attachment = new Attachment
            {
                ContentUrl  = "https://weedmebot.azurewebsites.net/temp/" + ruta,
                ContentType = "audio/mp3",
                Content     = video.Description,
                Name        = NormalizarTexto(video.Title),
            };

            return(attachment);
        }
Ejemplo n.º 31
0
 private ManifestInfo GetManifest5Jobs(ManifestInfo manifestInfo, string AssetID, IEnumerable <IAssetFile> mp4AssetFiles, string AssetLocatorPath)
 {
     foreach (var file in mp4AssetFiles.OrderBy(f => f.ContentFileSize))
     {
         VideoInformation video = CreateVideoInformationK28JobNode(file.Name, AssetID, AssetLocatorPath);
         manifestInfo.VideoInformation.Add(video);
         //Watermarked
         foreach (var code in manifestInfo.EnbebedCodes)
         {
             var wmp4Name = System.Web.HttpUtility.UrlPathEncode(video.FileName);
             code.MP4WatermarkedURL.Add(new MP4WatermarkedURL()
             {
                 FileName       = video.FileName,
                 WaterMarkedMp4 = GetBlobSasUri("watermarked", $"{AssetID}/{code.EmbebedCode}/{wmp4Name}")
             });
         }
     }
     return(manifestInfo);
 }
Ejemplo n.º 32
0
        public override PacketMainReturn interiorMain(ref Packet in_packet)
        {
            if (in_packet.ContainsLayer(Protocol.TCP) && !in_packet.Outbound)
            {
                TCPPacket tcp = (TCPPacket)in_packet;
                Quad q = new Quad() { dstIP = tcp.DestIP, dstPort = tcp.DestPort, srcIP = tcp.SourceIP, srcPort = tcp.SourcePort };
                VideoInformation vid;
                if(videos.TryGetValue(q, out vid))
                {
                    if (tcp.SourcePort == 80 && tcp.ACK)
                    {
                        if (tcp.FIN)
                        {
                            //finish the file
                            vid.Done();
                            lock (videos)
                            {
                                videos.Remove(q);
                            }
                        }
                        else
                        {
                            //continue writing then update the openFiles dictionary
                            byte[] data = tcp.GetApplicationLayer_safe();
                            if (data != null && data.Length != 0)
                            {
                                vid.AddData(data, tcp.SequenceNumber);
                            }
                        }
                    }
                }
                else if (tcp.SourcePort == 80 && tcp.ACK)
                {
                    byte[] data = tcp.GetApplicationLayer_safe();
                    string str = ASCIIEncoding.ASCII.GetString(data);
                    if (!str.StartsWith("HTTP/1.1 200 OK"))
                        return null;
                    if (str.Contains("Content-Type: "))
                    {
                        string type = null;
                        string strLen = null;
                        if (!str.Contains("Content-Length: "))
                        {
                            strLen = "0";
                        }
                        string[] lines = str.Replace("\r","").Split("\n".ToCharArray());
                        foreach (string line in lines)
                        {
                            if (type == null && line.StartsWith("Content-Type: "))
                            {
                                type = line.Replace("Content-Type: ", "").Replace("\n", "");
                            }
                            else if (strLen == null && line.StartsWith("Content-Length: "))
                            {
                                strLen = line.Replace("Content-Length: ", "").Replace("\n", "");
                            }
                            if (type != null && strLen != null)
                                break;
                        }
                        if (type.StartsWith("video/") || type == "flv-application/octet-stream" || type.StartsWith("audio/"))
                        {
                            ulong length = ulong.Parse(strLen);
                            if (!videos.ContainsKey(q))
                            {
                                VideoInformation vi = new VideoInformation(q, length, tcp.GetNextSequenceNumber(), type);

                                if (str.Contains("\r\n\r\n"))
                                {
                                    int dataStart = str.IndexOf("\r\n\r\n") + 4;
                                    if (data.Length > dataStart)
                                    {
                                        byte[] first = new byte[data.Length - dataStart];
                                        Buffer.BlockCopy(data, dataStart, first, 0, first.Length);
                                        vi.AddData(first);
                                    }
                                }
                                vi.SetSequence(tcp.GetNextSequenceNumber());
                                lock (videos)
                                {
                                    videos[q] = vi;
                                }
                            }
                        }
                    }
                }
            }
            return null;
        }