Пример #1
0
        public void SetUp()
        {
            var mock    = new Mock <ISerializer>();
            var fixture = new Fixture();

            Plex = fixture.Create <PlexServers>();
            SonarrSystemStatus = fixture.Create <SonarrSystemStatus>();
            CouchPotatoStatus  = fixture.Create <CouchPotatoStatus>();
            NzbGetHistory      = fixture.Create <NzbGetHistory>();
            NzbGetList         = fixture.Create <NzbGetList>();
            NzbGetStatus       = fixture.Create <NzbGetStatus>();
            SonarrSeries       = fixture.CreateMany <SonarrSeries>().ToList();
            SabNzbdHistory     = fixture.Create <SabNzbdHistory>();
            SabNzbdQueue       = fixture.Create <SabNzbdQueue>();

            mock.Setup(x => x.SerializeXmlData <PlexServers>(It.IsAny <string>())).Returns(Plex);
            mock.Setup(x => x.SerializedJsonData <SonarrSystemStatus>(It.IsAny <string>())).Returns(SonarrSystemStatus);
            mock.Setup(x => x.SerializedJsonData <CouchPotatoStatus>(It.IsAny <string>())).Returns(CouchPotatoStatus);
            mock.Setup(x => x.SerializedJsonData <NzbGetHistory>(It.IsAny <string>())).Returns(NzbGetHistory);
            mock.Setup(x => x.SerializedJsonData <NzbGetList>(It.IsAny <string>())).Returns(NzbGetList);
            mock.Setup(x => x.SerializedJsonData <NzbGetStatus>(It.IsAny <string>())).Returns(NzbGetStatus);
            mock.Setup(x => x.SerializedJsonData <List <SonarrSeries> >(It.IsAny <string>())).Returns(SonarrSeries);
            mock.Setup(x => x.SerializedJsonData <SabNzbdHistory>(It.IsAny <string>())).Returns(SabNzbdHistory);
            mock.Setup(x => x.SerializedJsonData <SabNzbdQueue>(It.IsAny <string>())).Returns(SabNzbdQueue);

            Mock    = mock;
            Service = new ThirdPartyService(Mock.Object);
        }
Пример #2
0
        /// <summary>
        /// 添加第三方服务
        /// </summary>
        /// <param name="thirdPartyService">第三方服务信息</param>
        /// <returns>写入基础数据库的状态项数</returns>
        public async Task <HttpResponseMessage> AddService(ThirdPartyService thirdPartyService)
        {
            _db.ThirdPartyService.Add(thirdPartyService);
            var result = await _db.SaveChangesAsync();

            return(Request.CreateResponse(HttpStatusCode.OK, Json(result)));
        }
Пример #3
0
 public HomeController(ILogger <HomeController> logger,
                       ThirdPartyService thirdPartyService, StudentInfo studentInfo)
 {
     _logger            = logger;
     _thirdPartyService = thirdPartyService;
     _studentInfo       = studentInfo;
 }
        public ActionResult DeleteConfirmed(long id)
        {
            ThirdPartyService thirdpartyservice = db.ThirdPartyServices.Find(id);

            db.ThirdPartyServices.Remove(thirdpartyservice);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Пример #5
0
        public override async Task <List <Person> > GetPeople()
        {
            var result = await ThirdPartyService.ListCharactersAsync(MAXRESULTCOUNT).ConfigureAwait(false);

            return(result.Select(dto => new Person {
                Name = dto.CharacterName, Gender = dto.Gender.ToString()
            }).ToList());
        }
Пример #6
0
        /// <summary>
        /// 更新第三方服务信息
        /// </summary>
        /// <param name="id">第三方服务编号</param>
        /// <param name="thirdPartyService">第三方服务信息</param>
        /// <returns>写入基础数据库的状态项数</returns>
        public async Task <HttpResponseMessage> Update(int id, ThirdPartyService thirdPartyService)
        {
            thirdPartyService.ThirdPartyServiceId = id;
            _db.Entry(thirdPartyService).State    = EntityState.Modified;
            var result = await _db.SaveChangesAsync();

            return(Request.CreateResponse(HttpStatusCode.OK, Json(result)));
        }
        //
        // GET: /ThirdPartyService/Delete/5

        public ActionResult Delete(long id = 0)
        {
            ThirdPartyService thirdpartyservice = db.ThirdPartyServices.Find(id);

            if (thirdpartyservice == null)
            {
                return(HttpNotFound());
            }
            return(View(thirdpartyservice));
        }
 public ActionResult Edit(ThirdPartyService thirdpartyservice)
 {
     if (ModelState.IsValid)
     {
         db.Entry(thirdpartyservice).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(thirdpartyservice));
 }
Пример #9
0
        public override async Task <List <Person> > GetPeople()
        {
            var thirdPartyService = new ThirdPartyService();

            var result = await thirdPartyService.ListCharactersAsync(MAX_RESULT_COUNT);

            return(result.Select(dto => new Person {
                Name = dto.CharacterName, Gender = dto.Gender.ToString()
            }).ToList());
        }
        public ActionResult Create(ThirdPartyService thirdpartyservice)
        {
            if (ModelState.IsValid)
            {
                db.ThirdPartyServices.Add(thirdpartyservice);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(thirdpartyservice));
        }
Пример #11
0
 public void TEST_ThirdPartyController_GotoGame()
 {
     IThirdPartyService begoniaService = new ThirdPartyService();
     // var controller = new ThirdPartyController();
 }
Пример #12
0
 public MyServiceDependOnThirdPartyService(ThirdPartyService thirdPartyService)
 {
     ThirdPartyService = thirdPartyService;
 }
Пример #13
0
        /// <summary>
        /// The ConvertAndPostAsync is executed on an individual file. It reads the file, processes it by removing localURLs and pulling the required frontmatter out of the document. This is then added to an appropriate POCO, either for Medium or for DevTo. As a future exercise, could investigate making this POCO agnostic of the third party service.
        /// </summary>
        /// <param name="filePath">File Path of the file to be processed.</param>
        async Task <ProcessedResultObject> ConvertAndPostAsync(string filePath, ThirdPartyService thirdPartyService, CancellationTokenSource cts)
        {
            // Obtain the filename without the directoryPath, so that it can be used for the canonical URL details later on.
            string canonicalPath = filePath.Replace($"{directoryPath}\\", "");

            _logger.LogInformation($"[Loop] Processing ${filePath}");

            // Read the file contents out to a string
            string sourceFile = await _markdownService.readFile(filePath);

            // Process the file contents, by replacing any localURL within the markdown to a full URL.
            string contentWithFrontMatter = await _markdownService.replaceLocalURLs(sourceFile, baseUrl);

            // Also take a copy of the file contents, but without the frontmatter. This may be needed dependant upon the third party service.
            string contentWithoutFrontMatter = await _markdownService.removeFrontMatter(contentWithFrontMatter);

            string publishedDate = await _markdownService.getFrontmatterProperty(contentWithFrontMatter, "PublishDate");

            string canonicalUrl = await _markdownService.getCanonicalUrl(protocol, baseUrl, canonicalPath);


            List <string> series = (await _markdownService.getFrontMatterPropertyList(contentWithFrontMatter, "series", 1));

            // If required, prepend the original post information.

            /*if (originalPostInformation && !string.IsNullOrEmpty(publishedDate))
             *                {
             *                        contentWithoutFrontMatter = await _markdownService.prependOriginalPostSnippet(contentWithoutFrontMatter, DateTime.ParseExact(publishedDate, "yyyy-MM-dd HH:mm:ss", null), canonicalUrl);
             *                }*/

            IThirdPartyBlogPoco payload;

            switch (thirdPartyService)
            {
            case ThirdPartyService.Medium:
                // Initialise the MediumPOCO by using several MarkDown Service methods, including getCanonicalURL, getFrontMatterProperty and getFrontMatterPropertyList.
                payload = new MediumPoco()
                {
                    title        = await _markdownService.getFrontmatterProperty(sourceFile, "title"),
                    content      = contentWithoutFrontMatter,
                    canonicalUrl = canonicalUrl,
                    tags         = await _markdownService.getFrontMatterPropertyList(contentWithFrontMatter, "tags")
                };
                break;

            case ThirdPartyService.DevTo:
                // Initialise the DevToPOCO by using several MarkDown Service methods, including getCanonicalURL, getFrontMatterProperty and getFrontMatterPropertyList.

                payload = new DevToPoco()
                {
                    article = new Article()
                    {
                        title         = await _markdownService.getFrontmatterProperty(sourceFile, "title"),
                        body_markdown = contentWithoutFrontMatter,
                        canonical_url = canonicalUrl,
                        tags          = await _markdownService.getFrontMatterPropertyList(contentWithFrontMatter, "tags", 4, true),
                        description   = await _markdownService.getFrontmatterProperty(contentWithFrontMatter, "description")
                    }
                };

                if (series.Count > 0)
                {
                    (payload as DevToPoco).article.series = series[0];
                }

                int organization_id;

                if (int.TryParse(devtoOrganization, out organization_id))
                {
                    (payload as DevToPoco).article.organization_id = organization_id;
                }

                break;

            default:
                payload = new DevToPoco();
                break;
            }

            // If we were successful, it means we have both pieces of information and should be able to authenticate to Medium.
            _logger.LogInformation($"[{thirdPartyService.ToString()}] Crossposting {filePath}...");

            if (logPayloadOutput.ToLower().Equals("true"))
            {
                _logger.LogInformation($"[{thirdPartyService.ToString()}] {JsonSerializer.Serialize(payload, payload.GetType())}");
            }

            try
            {
                HttpResponseMessage responseMessage = new HttpResponseMessage()
                {
                    StatusCode = System.Net.HttpStatusCode.NotFound
                };

                if (!cts.Token.IsCancellationRequested)
                {
                    switch (thirdPartyService)
                    {
                    case ThirdPartyService.Medium:
                        responseMessage = await _mediumService.CreatePostAsync(payload as MediumPoco, mediumToken, cts, mediumAuthorId, await _markdownService.getFrontmatterProperty(contentWithFrontMatter, "youtube"));

                        break;

                    case ThirdPartyService.DevTo:
                        responseMessage = await _devToService.CreatePostAsync(payload as DevToPoco, devtoToken, cts, null, await _markdownService.getFrontmatterProperty(contentWithFrontMatter, "youtube"));

                        break;

                    default:
                        break;
                    }
                }

                if (responseMessage.IsSuccessStatusCode)
                {
                    _logger.LogInformation($"[{thirdPartyService.ToString()}] Crossposting of {filePath} complete.");
                    return(new ProcessedResultObject()
                    {
                        result = Result.Success
                    });
                }
                else
                {
                    _logger.LogWarning($"[{thirdPartyService.ToString()}] Crossposting of {filePath} cancelled. A previous response was received as Unauthorized, so all operations have been cancelled for this third party service. Please confirm your authentication details are correct for this Third Party Service.");

                    return(new ProcessedResultObject()
                    {
                        result = Result.Unauthorized
                    });
                }
            }
            catch (UnauthorizedResponseException)
            {
                _logger.LogWarning($"[{thirdPartyService.ToString()}] Crossposting of {filePath} cancelled. A previous response was received as Unauthorized, so all operations have been cancelled for this third party service. Please confirm your authentication details are correct for this Third Party Service.");

                return(new ProcessedResultObject()
                {
                    result = Result.Unauthorized
                });
            }
            catch (UnprocessableEntityException ex)
            {
                _logger.LogWarning($"[{thirdPartyService.ToString()}] Crossposting of {filePath} failed, as entity could not be processed.");

                return(new ProcessedResultObject()
                {
                    result = Result.Unprocessable,
                    jsonObject = ex.Message
                });
            }
        }
Пример #14
0
        async Task <ProcessedResultsCollection> Orchestrate(List <string> matchedFiles, ThirdPartyService thirdPartyService)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            List <Task <ProcessedResultObject> > listOfTasks = new List <Task <ProcessedResultObject> >();

            for (int i = 0; i < matchedFiles.Count; i++)
            {
                listOfTasks.Add(ConvertAndPostAsync(matchedFiles[i], thirdPartyService, cts));
                Thread.Sleep(50);
            }



            ProcessedResultObject[] resultArray = await Task.WhenAll(listOfTasks);

            List <ProcessedResultObject> _results = resultArray.ToList();

            ProcessedResultsCollection resultsCollection = new ProcessedResultsCollection()
            {
                service = thirdPartyService,
                results = _results
            };

            //cts.Dispose();

            return(resultsCollection);
        }