public async Task <String> Publish([FromBody] FolderDetailsModel data)
        {
            if (data.publishStatus != PublishStatusModel.publishRequested)
            {
                data.publishStatus = PublishStatusModel.publishRequested;

                data.publishedActions = (data.publishedActions ?? new PublishedLinkModel[] { }).Concat(new[] { new PublishedLinkModel {
                                                                                                                   lastModified = DateTime.Now,
                                                                                                                   message      = "publish requested"
                                                                                                               } }).ToArray();
            }

            var statusFileName = await SaveFolderAsync(data);

            var ct = new CancellationTokenSource(TimeSpan.FromSeconds(10));

            await _mqBus.Send(new neSchedular.ExecuteJobTask
            {
                jobName  = "publishPost",
                JobParam = data.savedFolder
            }, ct.Token);

            return(statusFileName);
        }
        public async Task <string> createNewFolder([FromBody] FolderDetailsModel data)
        {
            var statusFileName = await SaveFolderAsync(data);

            var origin = this.originFromURL("/api/foldercreator");

            var shortcut = $"[InternetShortcut]\r\nURL={origin}/publiMe?filename={System.Uri.EscapeDataString(statusFileName) }";

            var stream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(shortcut));

            await _storage.SaveStream($"{data.savedFolder}/avRadioPublisher.url", stream);

            var templatePrefix = "Other_";
            var otherTemplates = await getTemplatesByGenreAsync(templatePrefix);

            var templatemap = otherTemplates.ToDictionary(k => k.Replace(templatePrefix, ""), v => v);

            templatePrefix = $"{data.genre}_";
            var genre_templates = await getTemplatesByGenreAsync(templatePrefix);

            foreach (var t in genre_templates)
            {
                templatemap[t.Replace(templatePrefix, "")] = t;
            }

            foreach (var t in templatemap.Values)
            {
                var templatFileName = Path.GetFileName(t);

                var ext = Path.GetExtension(templatFileName).Trim('.');

                if ("rpp" == ext)
                {
                    var rppData = await System.IO.File.ReadAllTextAsync(t);

                    await Task.WhenAll(data.publishDetails.mediaFiles.Where(f => f is mediaList.AuViFileModel).Select(async f =>
                    {
                        var justfileName = Path.GetFileNameWithoutExtension(f.fileName);

                        var rppDataEdited = rppData.Replace(@"\\aleph\playground\Mix", $"Final");
                        await _storage.SaveStream(
                            $"{data.savedFolder}/{justfileName}.rpp",
                            new MemoryStream(Encoding.UTF8.GetBytes(rppDataEdited)));

                        var dest = Path.Combine(_mediaLocations.playgroundFolder, data.savedFolder, templatFileName);
                        System.IO.File.Copy(t, dest);

                        //                        await _storage.copyObjectAsync(t, $"{data.savedFolder}/{justfileName}.rpp");
                    }));
                }
                else
                {
                    //await _storage.copyObjectAsync(t, $"{data.savedFolder}/{templatFileName}");

                    var dest = Path.Combine(_mediaLocations.playgroundFolder, data.savedFolder, templatFileName);

                    System.IO.File.Copy(t, dest);
                }
            }

            //create the FinalFolder With dummey status
            stream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes("{}"));
            await _storage.SaveStream($"{data.savedFolder}/Final/status.json", stream);

            return(statusFileName);
        }
        public async Task <string> SaveFolderAsync([FromBody] FolderDetailsModel data)
        {
            if (string.IsNullOrWhiteSpace(data.savedFolder))
            {
                throw new bootCommon.ExceptionWithCode("savedfolder is empty");
            }

            if (null == data.publishDetails || null == data.publishDetails.mediaFiles || 0 == data.publishDetails.mediaFiles.Length)
            {
                throw new bootCommon.ExceptionWithCode("no media files");
            }

            {
                var unInitializedMediaFile = data.publishDetails.mediaFiles.Where(f =>
                                                                                  f.objectType == typeof(mediaList.ImageFileModel).Name &&
                                                                                  null == ((mediaList.ImageFileModel)f).imageInfo)
                                             .Cast <mediaList.ImageFileModel>().ToArray();

                await Task.WhenAll(unInitializedMediaFile.Select(async f =>
                {
                    f.imageInfo = await _storage.getImageInfoAsync($"{data.savedFolder}/{f.path}");

                    var tolerance = ((f.imageInfo.height * 1.0) / f.imageInfo.width) / ((_desiredImageInfo.height * 1.0) / _desiredImageInfo.width);

                    f.canPublish = tolerance >= 0.87 && tolerance < 1.05;

                    return(true);
                }));
            }

            {/*
              * var unInitializedMediaFile = data.publishDetails.mediaFiles.Where(f =>
              *                 f.objectType == typeof(mediaList.AuViFileModel).Name
              *                 && null == ((mediaList.AuViFileModel)f).info)
              *         .Cast<mediaList.AuViFileModel>().ToArray();
              *
              * await Task.WhenAll(unInitializedMediaFile.Select(async f =>
              * {
              *     f.info = await _storage.getAudioInfoAsync($"{data.savedFolder}/{f.path}");
              *     return true;
              * }));
              */
            }

            if (string.IsNullOrWhiteSpace(data.description))
            {
                throw new bootCommon.ExceptionWithCode("no description");
            }

            if (string.IsNullOrWhiteSpace(data.publishDetails.title))
            {
                data.publishDetails.title = data.description;
            }

            var jsonData       = JsonConvert.SerializeObject(data, Formatting.Indented);
            var statusFileName = $"{data.savedFolder}/sessionData.json";

            var stream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(jsonData));

            await _storage.SaveStream(statusFileName, stream);

            return(statusFileName);
        }
Esempio n. 4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="data"></param>
        /// <returns>The link to the post</returns>
        async Task <String> PushToWP(FolderDetailsModel data)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(data.publishDetails.category))
                {
                    throw new bootCommon.ExceptionWithCode("category is required");
                }


                if (string.IsNullOrWhiteSpace(data.publishDetails.title))
                {
                    throw new bootCommon.ExceptionWithCode("title is empty");
                }

                if (string.IsNullOrWhiteSpace(data.publishDetails.bodyText))
                {
                    throw new bootCommon.ExceptionWithCode("bodyText is empty");
                }

                var client = await login.AuthController.InitWP("" /*_wp_url*/, Request, _logger);


                var imagesToUpload = data.publishDetails.mediaFiles.Where(f => f is mediaList.ImageFileModel && ((mediaList.ImageFileModel)f).canPublish).ToArray();
                if (0 == imagesToUpload.Length)
                {
                    throw new bootCommon.ExceptionWithCode("at least one image is required");
                }

                var avToUpload = data.publishDetails.mediaFiles.Where(f => f is mediaList.AuViFileModel).ToArray();
                if (0 == avToUpload.Length)
                {
                    throw new bootCommon.ExceptionWithCode("at least one audio/video is required");
                }

                var allFileToUpload = imagesToUpload.Concat(avToUpload).ToArray();

                foreach (var f in allFileToUpload)
                {
                    var fPath = $"{data.savedFolder}/{f.proccessedPath}";
                    if (!(await _storage.keyExists(fPath)))
                    {
                        throw new bootCommon.ExceptionWithCode($"the proccessed file {fPath} is not ready");
                    }
                }

                var allCategories = (await client.Categories.GetAll()).ToArray();

                var category = allCategories.FirstOrDefault(c => c.Name == data.publishDetails.category);
                if (null == category)
                {
                    throw new bootCommon.ExceptionWithCode($"Category {data.publishDetails.category} not found");
                }

                /*
                 * if (null != data.publishedLink)
                 *  throw new bootCommon.ExceptionWithCode("Not implemented");
                 *
                 * var thePost = await client.Posts.Create(new Post
                 * {
                 *  Status = Status.Draft,
                 *  Title = new Title(data.publishDetails.title),
                 *  Content = new Content(data.publishDetails.bodyText),
                 *  Categories = new[] { category.Id }
                 * });
                 *
                 * data.publishedLink = new PublishedLinkModel
                 * {
                 *  wpPostId = thePost.Id,
                 *  wpLink = thePost.Link,
                 *  lastModified = DateTime.Now
                 * };
                 */

                await SaveFolderAsync(data);

                //var uploadedMedia = await Task.WhenAll(allFileToUpload.Select(async (image, i) =>
                //fails cause of the rate limited need to put 1 sec delays

                var uploadedMedia = allFileToUpload.Select((image, i) =>
                {
                    var ext = System.IO.Path.GetExtension(image.fileName).Trim('.');

                    var imageStream = (image is mediaList.ImageFileModel) ?
                                      _storage.getImageStream($"{data.savedFolder}/{image.proccessedPath}", 800).Result
                        :  _storage.getStreamAsync($"{data.savedFolder}/{image.proccessedPath}").Result;

                    var uploaded = client.Media.Create(imageStream, $"{data.publishDetails.title}_{i}.{ext}").Result;

                    Task.Delay(TimeSpan.FromSeconds(3)).Wait();

                    //uploaded.Post = thePost.Id;

                    uploaded = client.Media.Update(uploaded).Result;

                    return(new { image, uploaded });
                });


                var image_gallery = uploadedMedia.Where(f => f.image is mediaList.ImageFileModel)

                                    .Select(f => {
                    var image = f.image as mediaList.ImageFileModel;

                    return(new
                    {
                        add_a_picture = f.uploaded.Id,
                        photographer = image.photographer,
                        description = image.title
                    });
                })
                                    .ToArray();

                var add_mp3s = uploadedMedia.Where(f => f.image is mediaList.AuViFileModel)
                               .Select(f =>
                {
                    var image = f.image as mediaList.AuViFileModel;
                    return(new
                    {
                        mp3 = f.uploaded.Id,
                        mp3_artists = data.recordingBy,
                        duration = null == image.info ? "" : image.info.duration.ToString(@"mm\:ss"),
                    });
                })
                               .ToArray();

                /*
                 * var post = new {
                 *  post_status = "draft",
                 *  post_title = data.publishDetails.title,
                 *  post_content = data.publishDetails.bodyText,
                 * };
                 */

                var acfFields = new
                {
                    /*  program_rate
                     * 1 Can be better : 1 Can be better
                     * 2 Fairly Ok : 2 Fairly Ok
                     * 3 Good: 3 Good
                     * 4 Very good : 4 Very good
                     * 5 Excellent: 5 Excellent
                     */
                    field_12 = "5 Excellent",

                    /* Time span
                     * 2 weeks : 2 weeks
                     * 6 months : 6 months
                     * 1 year : 1 year
                     * more than 1 year : more than 1 year
                     */
                    field_14 = "more than 1 year",

                    field_13 = "5 Excellent",                   //quality_rate

                    field_15 = "AurovilleRadioTV",              //place
                    field_17 = data.publishDetails.twiterTitle, //twitter_text
                    field_18 = "AurovilleRadio",                //episode

                    field_5 = image_gallery,                    //"image_gallery"
                    field_3 = add_mp3s,                         //add-mp3s
                };

                throw new NotImplementedException();

                /*
                 * var done = await postToWP(client, new {
                 *  postId = thePost.Id,
                 *  acfFields,
                 *  featuredImageId = image_gallery.First().add_a_picture
                 * });
                 *
                 * data.publishedLink.lastModified = DateTime.Now;
                 * await SaveFolderAsync(data);
                 *
                 * return thePost.Link;
                 */
            }
            catch (bootCommon.ExceptionWithCode ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw new bootCommon.ExceptionWithCode("failed to publish to wordpress", innerException: ex);
            }
        }