Advertisement
Guest User

ProcessGitHubWebhookEvents Backup

a guest
Mar 12th, 2016
5
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 29.48 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Text;
  5. using System.Linq;
  6. using System.Net;
  7. using log4net;
  8. using Newtonsoft.Json;
  9. using PlayFab.AddOnService;
  10. using PlayFab.DataModel;
  11. using PlayFab.WebAPIModels.LogicServer;
  12. using PlayFab.Services;
  13. using PlayFab.WebAPIModels.Inventory;
  14. using QueueUtilities;
  15.  
  16. namespace ProcessGitHubWebhookEvents
  17. {
  18.  
  19.     public class StoreContainer
  20.     {
  21.         public string CatalogVersion;
  22.         public string StoreId;
  23.         public List<StoreItem> StoreItems;
  24.     }
  25.  
  26.     public class CatalogContainer
  27.     {
  28.         public string CatalogVersion { get; set; }
  29.         public CatalogItem[] Catalog { get; set; }
  30.     }
  31.  
  32.     public class ProcessGitHubWebhookEvents : IMessageProcessor<GitCommit>
  33.     {
  34.         private enum FileProcessingType
  35.         {
  36.             CloudScript,
  37.             Catalog,
  38.             TitleData,
  39.             Store,
  40.             DropTable,
  41.             Currency,
  42.             TitleNews
  43.         }
  44.  
  45.         private static readonly ILog Log = LogManager.GetLogger("ProcessGitHubWebHookEvents");
  46.         private const string UpdateStatusMessage = "Updating status for title {0} webook commit {1} from {2} to {3}";
  47.         private const string DeserilizationMessage = "{0} {1} in the repository could not be deserialized";
  48.         private const string ValidationMessage = "{1} {0} Did not pass validation";
  49.         private const string OverlimitMessage = "File is over the size limit for a {0}. {1}";
  50.         private const string CloudScriptFileName = "CloudScript.js";
  51.         private const string CatalogPath = "/Catalogs/";
  52.         private const string TitleDataPath = "/TitleData/";
  53.         private const string StorePath = "/Stores/";
  54.         private const string DropTablePath = "/DropTables/";
  55.         private const string CurrencyPath = "/Currency/";
  56.         private const string TitleNewsPath = "/TitleNews/";
  57.         private const string JsonExt = ".json";
  58.  
  59.         /// <summary>
  60.         /// Main is for debugging only.
  61.         /// </summary>
  62.         /// <param name="args"></param>
  63.         static void Main(string[] args)
  64.         {
  65.             log4net.Config.XmlConfigurator.Configure();
  66.             Log.Info("Process GitHub Webhook Events startings");
  67.             var processor = new QueueProcessor<ProcessGitHubWebhookEvents, GitCommit>(new ProcessGitHubWebhookEvents());
  68.             processor.ProcessEvents();
  69.         }
  70.  
  71.         public bool Process(GitCommit gitCommit)
  72.         {
  73.             var cloudScriptFileToUpdate = string.Empty;
  74.             var catalogItemsToUpdate = new List<CatalogContainer>();
  75.             var titleDataToUpdate = new Dictionary<string, string>();
  76.             var storesDataToUpdate = new List<StoreContainer>();
  77.             var dropTableToUpdate = new List<RandomResultTableListing>();  //note that this is a list of List<ResultTableNode>
  78.             var virtualCurrenciesToUpdate = new List<VirtualCurrencyModel>();
  79.             var titleNewsToUpdate = new List<TitleNews>();
  80.  
  81.             var title = Title.Get(gitCommit.TitleId, false);
  82.             var dev = Developer.Get(title.DeveloperId, false);
  83.             var gitHubAddOn = new GitHubAddOn(title, dev);
  84.  
  85.             var settings = gitHubAddOn.GetSettings();
  86.             //populate gitCommit object;
  87.             gitCommit.RepositoryName = settings.RepositoryName;
  88.             gitCommit.RepositoryOwner = settings.RepositoryOwner;
  89.             gitCommit.AccessToken = settings.AccessToken;
  90.  
  91.  
  92.             try {
  93.  
  94.             #region validation
  95.             if (gitHubAddOn.GetSettings().UserEnabledCloudScript)
  96.             {
  97.                 var cloudScriptReady = ProcessCloudScript(gitHubAddOn, gitCommit, title, out cloudScriptFileToUpdate);
  98.                 if (!cloudScriptReady)
  99.                 {
  100.                     return true;
  101.                 }
  102.             }
  103.  
  104.             if (gitHubAddOn.GetSettings().UserEnabledCatalogs)
  105.             {
  106.                 var catalogsReady = ProcessCatalog(gitHubAddOn, gitCommit, title, out catalogItemsToUpdate);
  107.                 if (!catalogsReady)
  108.                 {
  109.                     return true;
  110.                 }
  111.             }
  112.  
  113.             if (gitHubAddOn.GetSettings().UserEnabledTitleData)
  114.             {
  115.                 var titleDataReady = ProcessTitleData(gitHubAddOn, gitCommit, title, out titleDataToUpdate);
  116.                 if (!titleDataReady)
  117.                 {
  118.                     return true;
  119.                 }
  120.             }
  121.  
  122.             if (gitHubAddOn.GetSettings().UserEnabledStores)
  123.             {
  124.                 var storesReady = ProcessStores(gitHubAddOn, gitCommit, title, out storesDataToUpdate);
  125.                 if (!storesReady)
  126.                 {
  127.                     return true;
  128.                 }
  129.             }
  130.  
  131.             if (gitHubAddOn.GetSettings().UserEnabledDropTables)
  132.             {
  133.                 var dropTablesReady = ProcessDropTables(gitHubAddOn, gitCommit, title, out dropTableToUpdate);
  134.                 if(!dropTablesReady)
  135.                 {
  136.                     return true;
  137.                 }
  138.             }
  139.  
  140.             if (gitHubAddOn.GetSettings().UserEnabledCurrency)
  141.             {
  142.                 var currencyReady = ProcessCurrency(gitHubAddOn, gitCommit, title, out virtualCurrenciesToUpdate);
  143.                 if (!currencyReady)
  144.                 {
  145.                     return true;
  146.                 }
  147.             }
  148.  
  149.             if (gitHubAddOn.GetSettings().UserEnabledTitleNews)
  150.             {
  151.                 var titleNewsReady = ProcessTitleNews(gitHubAddOn, gitCommit, title, out titleNewsToUpdate);
  152.                 if (!titleNewsReady)
  153.                 {
  154.                     return true;
  155.                 }
  156.             }
  157.             #endregion
  158.  
  159.             }
  160.             catch(Exception e)
  161.             {
  162.                 Log.Error("Failed to process webhook", e);
  163.                 UpdateWebHookStatus(gitCommit, GitHubCommitStatus.FailedToprocess, "Unable to determine if the commit is valid");
  164.                 throw;
  165.             }
  166.  
  167.             try
  168.             {
  169.                 #region save data
  170.                 //We are good to save all the data at this point.
  171.  
  172.                 //Save Cloudscript file.
  173.                 if (gitHubAddOn.GetSettings().UserEnabledCloudScript)
  174.                 {
  175.                     SaveOrDeployCloudScript(title, gitCommit, cloudScriptFileToUpdate);
  176.                 }
  177.  
  178.                 //Save virtual currency, we should do this before we save the catalog.
  179.                 if (gitHubAddOn.GetSettings().UserEnabledCurrency)
  180.                 {
  181.                     //Find Currencies to remove.
  182.                     var currentCurrency = VirtualCurrencyService.GetVirtualCurrencies(title.Id);
  183.                     var currencyToDelete = new List<string>();
  184.                     var currencyToAdd = new List<VirtualCurrencyModel>();
  185.                     foreach (var currency in virtualCurrenciesToUpdate)
  186.                     {
  187.                         currencyToAdd.Add(currency);
  188.                     }
  189.  
  190.                     //Find Currencies to remove
  191.                     foreach (var currency in currentCurrency)
  192.                     {
  193.                         var curr = virtualCurrenciesToUpdate.Find(c => c.CurrencyCode == currency.CurrencyCode);
  194.                         if (curr == null)
  195.                         {
  196.                             currencyToDelete.Add(currency.CurrencyCode);
  197.                         }
  198.                     }
  199.  
  200.                     //Delete Currencies that need to be deleted.
  201.                     if (currencyToDelete.Count > 0)
  202.                     {
  203.                         VirtualCurrencyService.DeleteCurrencies(title.Id, currencyToDelete);
  204.                     }
  205.  
  206.                     foreach (var currency in currencyToAdd)
  207.                     {
  208.                         VirtualCurrencyService.SetVirtualCurrency(title.Id, new VirtualCurrencyModel()
  209.                         {
  210.                             TitleId = currency.TitleId,
  211.                             CurrencyCode = currency.CurrencyCode,
  212.                             DisplayName = currency.DisplayName,
  213.                             InitialDeposit = currency.InitialDeposit,
  214.                             RechargeMax = currency.RechargeMax,
  215.                             RechargeRate = currency.RechargeRate,
  216.                             MaxAmount = currency.MaxAmount
  217.                         });
  218.                     }
  219.  
  220.  
  221.                 }
  222.  
  223.                 //Save catalog items ( will it fail if the VC doesn't exist? It doesn't in GameManager )
  224.                 if (gitHubAddOn.GetSettings().UserEnabledCatalogs)
  225.                 {
  226.                     //For each catalog, set the catalog data.
  227.                     foreach (var catalog in catalogItemsToUpdate)
  228.                     {
  229.                         CatalogService.SetItems(catalog.Catalog, title.Id, catalog.CatalogVersion);
  230.                     }
  231.                 }
  232.  
  233.                 if (gitHubAddOn.GetSettings().UserEnabledTitleData)
  234.                 {
  235.                     if (titleDataToUpdate != null && titleDataToUpdate.Keys.Count > 0)
  236.                     {
  237.                         TitleDataService.SetTitleData<TitleData>(title.Id, titleDataToUpdate);
  238.                     }
  239.                 }
  240.  
  241.                 if (gitHubAddOn.GetSettings().UserEnabledStores)
  242.                 {
  243.                     foreach (var store in storesDataToUpdate)
  244.                     {
  245.                         StoreItem.SetItems(store.StoreItems, title.Id, store.CatalogVersion, store.StoreId);
  246.                     }
  247.                 }
  248.  
  249.                 if (gitHubAddOn.GetSettings().UserEnabledDropTables)
  250.                 {
  251.                     foreach (var droptable in dropTableToUpdate)
  252.                     {
  253.                         DropTableService.SaveTable(droptable, title.Id, droptable.CatalogVersion);
  254.                     }
  255.                 }
  256.  
  257.                 if (gitHubAddOn.GetSettings().UserEnabledTitleNews)
  258.                 {
  259.                     if (titleNewsToUpdate != null && titleNewsToUpdate.Count > 0)
  260.                     {
  261.                         TitleNewsService.SaveTitleNewsFromRepository(title.Id, titleNewsToUpdate);
  262.                     }
  263.                 }
  264.                 #endregion
  265.  
  266.             }
  267.             catch (Exception e)
  268.             {
  269.                 //If there was a problem saving anywhere along the way, set the commit to a failure.
  270.                 UpdateWebHookStatus(gitCommit, GitHubCommitStatus.FailedToprocess, e.Message);
  271.                 //Catch any exception and throw it back to the queue processor.
  272.                 throw;
  273.             }
  274.  
  275.             //we are good to go, set the active commit and save the commit status as available.
  276.             gitHubAddOn.SetActiveCommit(gitCommit.CommitId);
  277.             UpdateWebHookStatus(gitCommit, GitHubCommitStatus.Available, string.Empty);
  278.             return true;
  279.  
  280.         }
  281.  
  282.  
  283.         private static void SaveOrDeployCloudScript(Title title, GitCommit gitCommit, string cloudScriptFile)
  284.         {
  285.             var logicVersion = CloudLogicService.GetVersion(title.Id, 1, true);
  286.            
  287.             if (gitCommit.IsDeployment)
  288.             {
  289.                 var revision = CloudLogicService.GetRevision(title.Id, gitCommit.CommitId, true, true);
  290.                 var revisionNumber = int.Parse(revision.VersionRevision);
  291.                 title.LatestCloudLogicVersion = logicVersion.Version;
  292.                 title.Update();
  293.  
  294.                 //Set this revision as the active revision.
  295.                 CloudLogicService.SetProdRevision(logicVersion, revisionNumber);
  296.                 return;
  297.             }
  298.  
  299.             var newRevisionNumber = 0;
  300.             //Get existing cloud script revision
  301.             var csVersion = CloudLogicService.GetVersion(title.Id, 1, true);
  302.  
  303.             //Insert files into the database.
  304.             CloudLogicService.CreateRevision(title.Id, new List<string> { CloudScriptFileName },
  305.                 new List<string> { cloudScriptFile }, false, out newRevisionNumber, gitCommit.CommitId);
  306.  
  307.             //Reacquire the version object, because CreateRevision has incremented invalidating csVersion.
  308.             logicVersion = CloudLogicService.GetVersion(title.Id, csVersion.Version, true);
  309.             title.LatestCloudLogicVersion = logicVersion.Version;
  310.             title.Update();
  311.         }
  312.  
  313.         private static bool CheckOverLimit(FileProcessingType type, string content, GitCommit gitCommit)
  314.         {
  315.             var limitsResult = new ValidateLimitsResult();
  316.            
  317.             switch (type)
  318.             {
  319.                 case FileProcessingType.CloudScript:
  320.                     limitsResult = CloudLogicService.ValidateLimits(content);
  321.                     break;
  322.                 case FileProcessingType.Catalog:
  323.                     limitsResult = CatalogService.ValidateLimits(content);
  324.                     break;
  325.                 case FileProcessingType.TitleData:
  326.                     limitsResult = TitleDataService.ValidateLimits(content);
  327.                     break;
  328.                 case FileProcessingType.Store:
  329.                     limitsResult = StoreService.ValidateLimits(content);
  330.                     break;
  331.                 case FileProcessingType.DropTable:
  332.                     limitsResult = DropTableService.ValidateLimits(content);
  333.                     break;
  334.                 case FileProcessingType.Currency:
  335.                     limitsResult = VirtualCurrencyService.ValidateLimits(content);
  336.                     break;
  337.                 case FileProcessingType.TitleNews:
  338.                     limitsResult = TitleNewsService.ValidateLimits(content);
  339.                     break;
  340.             }
  341.  
  342.             if (!limitsResult.Result)
  343.             {
  344.                 if (!gitCommit.IsDeployment)
  345.                 {
  346.                     UpdateWebHookStatus(gitCommit, GitHubCommitStatus.FailedToprocess,
  347.                         string.Format(OverlimitMessage, limitsResult.Name, limitsResult.ErrorMessage));
  348.                 }
  349.             }
  350.  
  351.             return limitsResult.Result;
  352.         }
  353.  
  354.         public static bool ProcessCloudScript(GitHubAddOn gitHubAddOn, GitCommit gitCommit, Title title, out string cloudScriptFileToUpdate)
  355.         {
  356.             var cloudScriptFileList = gitHubAddOn.GetCloudScriptFiles(gitCommit.CommitId);
  357.  
  358.             //Combine all the files they have that are .js into a single concatenated .js file.
  359.             var builder = new StringBuilder();
  360.             foreach (var rf in cloudScriptFileList)
  361.             {
  362.                 builder.Append(rf.Content);
  363.                 builder.Append("\n");
  364.             }
  365.  
  366.             cloudScriptFileToUpdate = builder.ToString();
  367.  
  368.             //Check to make sure that the files are within the limits and rules defined for cloud script files.
  369.             if (!CheckOverLimit(FileProcessingType.CloudScript, builder.ToString(), gitCommit))
  370.             {
  371.                 return false;
  372.             }
  373.  
  374.             var cloudScriptFilesToValidate = new List<CloudScriptFile>()
  375.             {
  376.                 new CloudScriptFile()
  377.                 {
  378.                     Filename = CloudScriptFileName,
  379.                     FileContents = builder.ToString()
  380.                 }
  381.             };
  382.  
  383.             //Validate CloudScript Logic to ensure the script is runnable.
  384.             var result = CloudLogicService.ValidateCloudLogic(title, 0, cloudScriptFilesToValidate);
  385.  
  386.             if (result.Status != HttpStatusCode.OK)
  387.             {
  388.                 if (result.Error != null && result.Error.errorDetails != null)
  389.                 {
  390.                     var sbErrorDetails = new StringBuilder();
  391.                     foreach (var error in result.Error.errorDetails)
  392.                     {
  393.                         sbErrorDetails.Append(error);
  394.                     }
  395.  
  396.                     UpdateWebHookStatus(gitCommit, GitHubCommitStatus.FailedToprocess, result.Error.errorMessage);
  397.                 }
  398.                 else
  399.                 {
  400.                     UpdateWebHookStatus(gitCommit, GitHubCommitStatus.FailedToprocess,
  401.                         result.Error != null ? result.Error.errorMessage : string.Empty);
  402.                     Log.DebugFormat("Failed to process webhook - {0}",
  403.                         result.Error != null ? result.Error.errorMessage : string.Empty);
  404.                 }
  405.                 return false;
  406.             }
  407.  
  408.             return true;
  409.         }
  410.  
  411.         public static bool ProcessCatalog(GitHubAddOn gitHubAddOn, GitCommit gitCommit, Title title, out List<CatalogContainer> catalogItemsToUpdate )
  412.         {
  413.             var catalogFiles = gitHubAddOn.GetDataFiles(gitCommit.CommitId, CatalogPath, JsonExt);
  414.  
  415.             //Setting to null, so that if we fail this value is null and can be null checked.
  416.             catalogItemsToUpdate = null;
  417.  
  418.             //Get All catalogs
  419.             if (catalogFiles.Count == 0)
  420.             {
  421.                 return false;
  422.             }
  423.  
  424.             var catalogs = new List<CatalogContainer>();
  425.             //First loop make sure no files have issues.
  426.             foreach (var rf in catalogFiles)
  427.             {
  428.                 if (!CheckOverLimit(FileProcessingType.Catalog, rf.Content, gitCommit))
  429.                 {
  430.                     return false;
  431.                 }
  432.                 try
  433.                 {
  434.                     var data = JsonConvert.DeserializeObject<CatalogContainer>(rf.Content);
  435.                     if (data == null)
  436.                     {
  437.                         UpdateWebHookStatus(gitCommit, GitHubCommitStatus.FailedToprocess,
  438.                             string.Format(DeserilizationMessage,"Catalog", rf.Name));
  439.                         return false;
  440.                     }
  441.                     catalogs.Add(data);
  442.                 }
  443.                 catch (Exception e)
  444.                 {
  445.                     Log.DebugFormat(string.Format(DeserilizationMessage, "Catalog", rf.Name),e);
  446.                     //Not sure if it would be helpful for the user to know the stacktrace of a desearilization failure
  447.                     UpdateWebHookStatus(gitCommit, GitHubCommitStatus.FailedToprocess,
  448.                         string.Format(DeserilizationMessage, "Catalog", rf.Name));
  449.                     return false;
  450.                 }
  451.             }
  452.  
  453.             catalogItemsToUpdate = catalogs;
  454.             return true;
  455.         }
  456.  
  457.         public static bool ProcessTitleData(GitHubAddOn gitHubAddOn, GitCommit gitCommit, Title title, out Dictionary<string,string> titleDataToUpdate )
  458.         {
  459.             //Setting to null, so that if we fail this value is null and can be null checked.
  460.             titleDataToUpdate = null;
  461.  
  462.             var titleDataFiles = gitHubAddOn.GetDataFiles(gitCommit.CommitId, TitleDataPath, JsonExt);
  463.             var titleDataFile = titleDataFiles.Find(tdf => tdf.Name.ToLower().Equals("titledata"));
  464.             if (titleDataFile == null || !CheckOverLimit(FileProcessingType.TitleData, titleDataFile.Content, gitCommit))
  465.             {
  466.                 return false;
  467.             }
  468.  
  469.             //Find only the file named TitleData;
  470.             var titleData = new Dictionary<string, string>();
  471.             try
  472.             {
  473.                 titleData = JsonConvert.DeserializeObject<Dictionary<string,string>>(titleDataFile.Content);
  474.                 if (titleData == null)
  475.                 {
  476.                     UpdateWebHookStatus(gitCommit, GitHubCommitStatus.FailedToprocess,
  477.                         string.Format(DeserilizationMessage,"TitleData", titleDataFile.Name));
  478.                     return false;
  479.                 }
  480.                
  481.             }
  482.             catch (Exception e)
  483.             {
  484.  
  485.                 Log.DebugFormat(string.Format(DeserilizationMessage, "TitleData", titleDataFile.Name), e);
  486.                 //Not sure if it would be helpful for the user to know the stacktrace of a desearilization failure
  487.                 UpdateWebHookStatus(gitCommit, GitHubCommitStatus.FailedToprocess,
  488.                     string.Format(DeserilizationMessage,"TitleData", titleDataFile.Name));
  489.  
  490.                 return false;
  491.             }
  492.  
  493.             titleDataToUpdate = titleData;
  494.             return true;
  495.         }
  496.  
  497.         public static bool ProcessStores(GitHubAddOn gitHubAddOn, GitCommit gitCommit, Title title, out List<StoreContainer> storesDataToUpdate)
  498.         {
  499.             //Setting to null, so that if we fail this value is null and can be null checked.
  500.             storesDataToUpdate = null;
  501.  
  502.             var storesFiles = gitHubAddOn.GetDataFiles(gitCommit.CommitId, StorePath, JsonExt);
  503.            
  504.             //Get All Stores
  505.             if (storesFiles.Count == 0)
  506.             {
  507.                 return false;
  508.             }
  509.            
  510.             //First loop make sure no files have issues.
  511.             foreach (var rf in storesFiles)
  512.             {
  513.                 if (!CheckOverLimit(FileProcessingType.Store, rf.Content, gitCommit))
  514.                 {
  515.                     return false;
  516.                 }
  517.             }
  518.  
  519.             var stores = new List<StoreContainer>();
  520.             //if no files have issues then go ahead and update them.
  521.             foreach (var rf in storesFiles)
  522.             {
  523.                 try
  524.                 {
  525.                     var store = JsonConvert.DeserializeObject<StoreContainer>(rf.Content);
  526.                     stores.Add(store);
  527.                 }
  528.                 catch (Exception e)
  529.                 {
  530.                     Log.DebugFormat(string.Format(DeserilizationMessage, "Store", rf.Name), e);
  531.                     UpdateWebHookStatus(gitCommit, GitHubCommitStatus.FailedToprocess,
  532.                     string.Format(DeserilizationMessage,"Store", rf.Name));
  533.                     return false;
  534.                 }
  535.             }
  536.            
  537.             storesDataToUpdate = stores;
  538.             return true;
  539.         }
  540.  
  541.         public static bool ProcessDropTables(GitHubAddOn gitHubAddOn, GitCommit gitCommit, Title title, out List<RandomResultTableListing> dropTableToUpdate)
  542.         {
  543.             //Setting to null, so that if we fail this value is null and can be null checked.
  544.             dropTableToUpdate = null;
  545.  
  546.             var dropTables = gitHubAddOn.GetDataFiles(gitCommit.CommitId, DropTablePath, JsonExt);
  547.            
  548.             //Get All DropTables
  549.             if (dropTables.Count == 0)
  550.             {
  551.                 return false;
  552.             }
  553.  
  554.             //First loop make sure no files have issues and deserialize.
  555.             var droptables = new List<RandomResultTableListing>();
  556.             var alldropTables = new Dictionary<string, RandomResultTable>();
  557.             foreach (var rf in dropTables)
  558.             {
  559.                 if (!CheckOverLimit(FileProcessingType.DropTable, rf.Content, gitCommit))
  560.                 {
  561.                     return false;
  562.                 }
  563.  
  564.                 try
  565.                 {
  566.                     var dropTable = JsonConvert.DeserializeObject<RandomResultTableListing>(rf.Content);
  567.                     alldropTables.Add(dropTable.TableId, dropTable);
  568.                 }
  569.                 catch (Exception e)
  570.                 {
  571.                     Log.DebugFormat(string.Format(DeserilizationMessage, "DropTable", rf.Name), e);
  572.                     UpdateWebHookStatus(gitCommit, GitHubCommitStatus.FailedToprocess,
  573.                     string.Format(DeserilizationMessage,"DropTable", rf.Name));
  574.                     return false;
  575.                 }
  576.             }
  577.            
  578.             //all validations must pass in order to continue processing the droptables.
  579.             foreach (var droptable in droptables)
  580.             {
  581.                 var catalog = CatalogService.GetCatalogForTitle(title.Id, droptable.CatalogVersion);
  582.                 var errors = new StringBuilder();
  583.                 if (DropTableService.ValidateTable(droptable, alldropTables ,catalog, errors))
  584.                 {
  585.                     UpdateWebHookStatus(gitCommit, GitHubCommitStatus.FailedToprocess,
  586.                     string.Format(ValidationMessage, "DropTable", droptable.TableId));
  587.                     droptables.Remove(droptable);
  588.                     return false;
  589.                 }
  590.             }
  591.  
  592.             dropTableToUpdate = droptables;
  593.             return true;
  594.         }
  595.  
  596.         public static bool ProcessCurrency(GitHubAddOn gitHubAddOn, GitCommit gitCommit, Title title, out List<VirtualCurrencyModel> virtualCurrenciesToUpdate)
  597.         {
  598.             //Setting to null, so that if we fail this value is null and can be null checked.
  599.             virtualCurrenciesToUpdate = null;
  600.  
  601.             var currencyFiles = gitHubAddOn.GetDataFiles(gitCommit.CommitId, CurrencyPath, JsonExt);
  602.             //We are only going to support one file in this directroy.
  603.             //It can be named anything .json
  604.             if (currencyFiles.Count == 0 || !CheckOverLimit(FileProcessingType.Currency, currencyFiles[0].Content, gitCommit))
  605.             {
  606.                 return false;
  607.             }
  608.            
  609.             //Only get a file named Currency.
  610.             var currencyDataFile = currencyFiles.Find(cf => cf.Name.ToLower().Contains("currency"));
  611.             var currencyData = new List<VirtualCurrencyModel>();
  612.  
  613.             try
  614.             {
  615.                 currencyData = JsonConvert.DeserializeObject<List<VirtualCurrencyModel>>(currencyDataFile.Content);
  616.                 if (currencyData == null)
  617.                 {
  618.                     UpdateWebHookStatus(gitCommit, GitHubCommitStatus.FailedToprocess,
  619.                         string.Format(DeserilizationMessage,"Currency", currencyDataFile.Name));
  620.                     return false;
  621.                 }
  622.  
  623.             }
  624.             catch (Exception e)
  625.             {
  626.                 Log.DebugFormat(string.Format(DeserilizationMessage, "Currency", currencyDataFile.Name), e);
  627.                 //Not sure if it would be helpful for the user to know the stacktrace of a desearilization failure
  628.                 UpdateWebHookStatus(gitCommit, GitHubCommitStatus.FailedToprocess,
  629.                     string.Format(DeserilizationMessage,"Currency", currencyDataFile.Name));
  630.  
  631.                 return false;
  632.             }
  633.  
  634.             if (currencyData.Count == 0)
  635.             {
  636.                 return false;
  637.             }
  638.  
  639.             virtualCurrenciesToUpdate = currencyData;
  640.             return true;
  641.         }
  642.  
  643.         public static bool ProcessTitleNews(GitHubAddOn gitHubAddOn, GitCommit gitCommit, Title title, out List<TitleNews> titleNewsToUpdate )
  644.         {
  645.             //Setting to null, so that if we fail this value is null and can be null checked.
  646.             titleNewsToUpdate = null;
  647.  
  648.             var titleNews = gitHubAddOn.GetDataFiles(gitCommit.CommitId, TitleNewsPath, JsonExt);
  649.            
  650.             //We are only going to support one file in this directroy.
  651.             //It can be named anything .json
  652.             if (titleNews.Count == 0 || !CheckOverLimit(FileProcessingType.Catalog, titleNews[0].Content, gitCommit))
  653.             {
  654.                 return false;
  655.             }
  656.  
  657.             //Get the file named TitleNews.json
  658.             var titleNewsFile = titleNews.Find(tn => tn.Name.ToLower().Contains("titlenews"));
  659.             if (titleNewsFile == null)
  660.             {
  661.                 return false;
  662.             }
  663.  
  664.             var titlenews = new List<TitleNews>();
  665.             try
  666.             {
  667.                 titlenews = JsonConvert.DeserializeObject<List<TitleNews>>(titleNewsFile.Content);
  668.             }
  669.             catch(Exception e)
  670.             {
  671.                 Log.DebugFormat(string.Format(DeserilizationMessage, "Title News", titleNewsFile.Name), e);
  672.                 //Not sure if it would be helpful for the user to know the stacktrace of a desearilization failure
  673.                 UpdateWebHookStatus(gitCommit, GitHubCommitStatus.FailedToprocess,
  674.                     string.Format(DeserilizationMessage, "Title News", titleNewsFile.Name));
  675.                 return false;
  676.             }
  677.  
  678.             titleNewsToUpdate = titlenews;
  679.  
  680.             return true;
  681.         }
  682.  
  683.         public static void UpdateWebHookStatus(GitCommit gitHubCommit, GitHubCommitStatus status, Exception error = null)
  684.         {
  685.             var errorMessage = error != null ? error.Message : string.Empty;
  686.             Log.DebugFormat(errorMessage, error);
  687.             UpdateWebHookStatus(gitHubCommit, status, errorMessage);
  688.         }
  689.  
  690.         private static void UpdateWebHookStatus(GitCommit gitHubCommit, GitHubCommitStatus status, string errorMessage)
  691.         {
  692.             Log.DebugFormat(UpdateStatusMessage, gitHubCommit.TitleId, gitHubCommit.CommitId, gitHubCommit.Status, status);
  693.             //TODO: Log playstream Event.
  694.  
  695.             try
  696.             {
  697.                 gitHubCommit.Status = status;
  698.                 gitHubCommit.ProcessErrorMessage = errorMessage;
  699.  
  700.                 var gitCommit = GitCommit.Get(gitHubCommit.CommitId, gitHubCommit.TitleId, false);
  701.                 if (gitCommit == null)
  702.                 {
  703.                     GitCommit.Create(gitHubCommit, false);
  704.                 }
  705.                 else
  706.                 {
  707.                     gitHubCommit.SetDynamoStore();                    
  708.                     gitHubCommit.Update(true);
  709.                 }
  710.             }
  711.             catch
  712.             {
  713.                 Log.ErrorFormat(
  714.                     "Failed to Update Commit record - GitCommit:{0} for Repo:{1} on Title:{2} ",
  715.                     gitHubCommit.CommitId, gitHubCommit.RepositoryName, gitHubCommit.TitleId);
  716.                 throw;
  717.             }
  718.         }
  719.    
  720.  
  721.     }
  722. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement